import type { Route } from './+types/route'

import { useToggle } from 'ahooks'
import { ErrorMessage } from '@hookform/error-message'
import {
  CalendarIcon,
  CopyIcon,
  CopyPlusIcon,
  Trash2Icon,
  PlusIcon,
  XIcon,
  ChevronsUpDownIcon,
  CheckIcon,
  BookIcon,
  ArrowDownAZIcon,
  ArrowDownZAIcon
} from 'lucide-react'
import { Link, useParams, useFetcher } from 'react-router'
import { Controller, useFieldArray, useForm } from 'react-hook-form'
import { Fragment, use, useEffect, useMemo, useRef, useState } from 'react'
import { format } from 'date-fns'
import { ptBR } from 'react-day-picker/locale'
import { zodResolver } from '@hookform/resolvers/zod'
import Fuse from 'fuse.js'

import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList
} from '@repo/ui/components/ui/command'
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator
} from '@repo/ui/components/ui/breadcrumb'
import {
  InputGroup,
  InputGroupAddon,
  InputGroupInput
} from '@repo/ui/components/ui/input-group'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle
} from '@repo/ui/components/ui/card'
import { Spinner } from '@repo/ui/components/ui/spinner'
import { Input } from '@repo/ui/components/ui/input'
import { Button } from '@repo/ui/components/ui/button'
import { Separator } from '@repo/ui/components/ui/separator'
import {
  Popover,
  PopoverContent,
  PopoverTrigger
} from '@repo/ui/components/ui/popover'
import { Label } from '@repo/ui/components/ui/label'
import { Calendar } from '@repo/ui/components/ui/calendar'
import { createSearch } from '@repo/util/meili'
import { cn } from '@repo/ui/lib/utils'
import { HttpMethod, request as req } from '@repo/util/request'
import { useIsMobile } from '@repo/ui/hooks/use-mobile'

import { formSchema, type Schema, MAX_ITEMS } from './data'
import { AsyncCombobox } from './async-combobox'
import { redirect } from 'react-router'

export function meta({}: Route.MetaArgs) {
  return [{ title: 'Adicionar matrícula' }]
}

export async function loader({ context }: Route.LoaderArgs) {
  const courses = createSearch({
    index: 'saladeaula_courses',
    sort: ['created_at:desc'],
    filter: 'unlisted NOT EXISTS',
    hitsPerPage: 100,
    env: context.cloudflare.env
  })

  return { courses }
}

export async function action({ params, request, context }: Route.ActionArgs) {
  const body = (await request.json()) as object
  const r = await req({
    url: `enrollments`,
    headers: new Headers({ 'Content-Type': 'application/json' }),
    method: HttpMethod.POST,
    body: JSON.stringify({ org_id: params.orgid, ...body }),
    request,
    context
  })

  const data = (await r.json()) as { sk: string }
  return redirect(`/${params.orgid}/enrollments/${data.sk}/submitted`)
}

const emptyRow = {
  user: undefined,
  course: undefined,
  scheduled_for: undefined
}

export default function Route({
  loaderData: { courses }
}: Route.ComponentProps) {
  const { orgid } = useParams()
  const fetcher = useFetcher()
  const form = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: { enrollments: [emptyRow] }
  })
  const { formState, control, handleSubmit, getValues, reset } = form
  const { fields, insert, remove, append } = useFieldArray({
    control,
    name: 'enrollments'
  })

  const onSubmit = async (data: Schema) => {
    await fetcher.submit(JSON.stringify(data), {
      method: 'post',
      encType: 'application/json'
    })
  }

  const onSearch = async (search: string) => {
    const params = new URLSearchParams({ q: search })
    const r = await fetch(`/${orgid}/users.json?${params.toString()}`)
    const { hits } = (await r.json()) as { hits: any[] }
    return hits
  }

  const duplicateRow = (index: number, times: number = 1) => {
    if (fields.length + times > MAX_ITEMS) {
      return null
    }

    const { user, ...rest } = getValues(`enrollments.${index}`)
    Array.from({ length: times }, (_, i) => {
      // @ts-ignore
      insert(index + 1 + i, rest)
    })
  }

  return (
    <div className="space-y-2.5">
      <Breadcrumb>
        <BreadcrumbList>
          <BreadcrumbItem>
            <BreadcrumbLink asChild>
              <Link to="../enrollments">Matrículas</Link>
            </BreadcrumbLink>
          </BreadcrumbItem>
          <BreadcrumbSeparator />
          <BreadcrumbItem>
            <BreadcrumbPage>Adicionar matrículas</BreadcrumbPage>
          </BreadcrumbItem>
        </BreadcrumbList>
      </Breadcrumb>

      <form
        onSubmit={handleSubmit(onSubmit)}
        className="lg:max-w-4xl mx-auto space-y-2.5"
        autoComplete="off"
        data-1p-ignore="true"
        data-lpignore="true"
      >
        <Card>
          <CardHeader>
            <CardTitle className="text-2xl">Adicionar matrículas</CardTitle>
            <CardDescription>
              Siga os passos abaixo para adicionar novas matrículas.
            </CardDescription>
          </CardHeader>

          <CardContent className="space-y-4">
            <div className="grid lg:grid-cols-[repeat(3,1fr)_auto] w-full gap-1.5">
              {/* Header */}
              <>
                <div className="max-lg:hidden text-foreground font-medium text-sm">
                  Colaborador
                </div>
                <div className="max-lg:hidden text-foreground font-medium text-sm">
                  Curso
                </div>
                <div className="max-lg:hidden text-foreground font-medium text-sm">
                  Matriculado em
                </div>
                <div>{/**/}</div>
              </>

              {/* Rows */}
              <>
                {fields.map((field, index) => (
                  <Fragment key={field.id}>
                    {/* Separator only for mobile */}
                    {index >= 1 && <div className="h-2.5 lg:hidden"></div>}

                    <Controller
                      control={control}
                      name={`enrollments.${index}.user`}
                      render={({
                        field: { name, value, onChange },
                        fieldState
                      }) => (
                        <div className="grid gap-1">
                          <AsyncCombobox
                            value={value}
                            title="Colaborador"
                            onChange={onChange}
                            onSearch={onSearch}
                            error={fieldState.error}
                          />
                          <ErrorMessage
                            errors={formState.errors}
                            name={name}
                            render={({ message }) => (
                              <p className="text-destructive text-sm">
                                {message}
                              </p>
                            )}
                          />
                        </div>
                      )}
                    />

                    <Controller
                      control={control}
                      name={`enrollments.${index}.course`}
                      render={({
                        field: { name, value, onChange },
                        fieldState
                      }) => (
                        <div className="grid gap-1">
                          <FacetedFilter
                            value={value}
                            onChange={onChange}
                            options={courses}
                            error={fieldState.error}
                          />
                          <ErrorMessage
                            errors={formState.errors}
                            name={name}
                            render={({ message }) => (
                              <p className="text-destructive text-sm">
                                {message}
                              </p>
                            )}
                          />
                        </div>
                      )}
                    />

                    <Controller
                      control={control}
                      name={`enrollments.${index}.scheduled_for`}
                      render={({ field: { value, onChange } }) => (
                        <ScheduledForInput value={value} onChange={onChange} />
                      )}
                    />

                    {/* Action */}
                    <div className="flex gap-1.5">
                      <Button
                        type="button"
                        tabIndex={-1}
                        variant="outline"
                        className="cursor-pointer"
                        onClick={() => duplicateRow(index)}
                        title="Duplicar linha"
                      >
                        <CopyIcon />
                      </Button>

                      <DuplicateRowMultipleTimes
                        index={index}
                        duplicateRow={duplicateRow}
                      />

                      <Button
                        tabIndex={-1}
                        variant="destructive"
                        className="cursor-pointer"
                        disabled={fields.length == 1}
                        onClick={() => remove(index)}
                      >
                        <Trash2Icon />
                      </Button>
                    </div>
                  </Fragment>
                ))}
              </>
            </div>

            <Button
              type="button"
              // @ts-ignore
              onClick={() => append(emptyRow)}
              className="cursor-pointer"
              disabled={fields.length == MAX_ITEMS}
              variant="outline"
              size="sm"
            >
              <PlusIcon /> Adicionar
            </Button>

            <Separator />

            <Button
              type="submit"
              className="cursor-pointer"
              disabled={formState.isSubmitting}
            >
              {formState.isSubmitting && <Spinner />}
              Matricular
            </Button>
          </CardContent>
        </Card>
      </form>
    </div>
  )
}

type Course = {
  id: string
  name: string
  access_period: number
  metadata__unit_price?: number
}

interface FacetedFilterProps {
  value?: Course
  options: Promise<{ hits: any[] }>
  onChange?: (value: any) => void
  error?: any
}

function FacetedFilter({
  value,
  onChange,
  options,
  error
}: FacetedFilterProps) {
  const [search, setSearch] = useState<string>('')
  const [open, { set }] = useToggle()
  const [sort, { toggle }] = useToggle('a-z', 'z-a')
  const { hits } = use(options)
  const listRef = useRef<HTMLDivElement | null>(null)
  const fuse = useMemo(() => {
    return new Fuse(hits, {
      keys: ['name'],
      threshold: 0.3,
      includeMatches: true
    })
  }, [hits])

  const filtered = useMemo(() => {
    const results = !search ? hits : fuse.search(search).map(({ item }) => item)

    return results.sort((a, b) => {
      const comparison = a.name.localeCompare(b.name)
      return sort === 'a-z' ? comparison : -comparison
    })
  }, [search, fuse, hits, sort])

  return (
    <Popover open={open} onOpenChange={set}>
      <PopoverTrigger asChild>
        <InputGroup>
          <InputGroupInput
            readOnly
            placeholder="Curso"
            value={value?.name || ''}
            aria-invalid={!!error}
          />
          <InputGroupAddon>
            <BookIcon />
          </InputGroupAddon>
          <InputGroupAddon align="inline-end">
            <ChevronsUpDownIcon />
          </InputGroupAddon>
        </InputGroup>
      </PopoverTrigger>

      <PopoverContent className="lg:w-84 p-0" align="start">
        <Command shouldFilter={false}>
          <div className="flex">
            <div className="flex-1">
              <CommandInput
                placeholder="Curso"
                autoComplete="off"
                onValueChange={setSearch}
              />
            </div>
            <div className="border-b flex items-center justify-end">
              <Button
                variant="link"
                size="icon-sm"
                className="cursor-pointer text-muted-foreground"
                onClick={toggle}
              >
                {sort == 'a-z' ? <ArrowDownAZIcon /> : <ArrowDownZAIcon />}
              </Button>
            </div>
          </div>
          {/* Force rerender to reset the scroll position  */}
          <CommandList key={sort}>
            <CommandEmpty>Nenhum resultado encontrado.</CommandEmpty>
            <CommandGroup>
              {filtered
                .filter(
                  ({ metadata__unit_price = 0 }) => metadata__unit_price > 0
                )
                .map(
                  ({
                    id,
                    name,
                    access_period,
                    metadata__unit_price: unit_price
                  }) => (
                    <CommandItem
                      key={id}
                      value={id}
                      className="cursor-pointer"
                      onSelect={() => {
                        onChange?.({
                          id,
                          name,
                          access_period: Number(access_period),
                          unit_price: Number(unit_price)
                        })
                        set(false)
                      }}
                    >
                      {name}
                      <CheckIcon
                        className={cn(
                          'ml-auto',
                          value?.id === id ? 'opacity-100' : 'opacity-0'
                        )}
                      />
                    </CommandItem>
                  )
                )}
            </CommandGroup>
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  )
}

interface ScheduledForInputProps {
  value?: Date
  onChange?: (value: Date | undefined) => void
}

function ScheduledForInput({ value, onChange }: ScheduledForInputProps) {
  const today = new Date()
  const tomorrow = new Date()
  tomorrow.setDate(today.getDate() + 1)
  const [open, { set }] = useToggle()
  const [selected, setDate] = useState<Date | undefined>(value)
  const displayValue = selected ? format(selected, 'dd/MM/yyyy') : ''

  return (
    <Popover open={open} onOpenChange={set}>
      <PopoverTrigger asChild>
        <InputGroup>
          <InputGroupInput
            readOnly
            placeholder="Imediatamente"
            value={displayValue}
          />

          <InputGroupAddon>
            <CalendarIcon />
          </InputGroupAddon>

          {selected && (
            <InputGroupAddon align="inline-end" className="mr-0">
              <Button
                variant="link"
                size="icon-sm"
                className="cursor-pointer text-muted-foreground"
                onClick={(e) => {
                  e.preventDefault()
                  setDate(undefined)
                  onChange?.(undefined)
                  set(false)
                }}
              >
                <XIcon />
              </Button>
            </InputGroupAddon>
          )}
        </InputGroup>
      </PopoverTrigger>

      <PopoverContent className="w-full p-0" align="start">
        <Calendar
          mode="single"
          selected={selected}
          onSelect={(date: Date | undefined) => {
            setDate(date)
            onChange?.(date)
            set(false)
          }}
          disabled={{ before: tomorrow }}
          startMonth={new Date(today.getFullYear(), 0)}
          endMonth={new Date(today.getFullYear() + 3, 11)}
          captionLayout="dropdown"
          locale={ptBR}
        />
      </PopoverContent>
    </Popover>
  )
}

function DuplicateRowMultipleTimes({
  index,
  duplicateRow
}: {
  index: number
  duplicateRow: (index: number, times: number) => void
}) {
  const [open, { toggle, set }] = useToggle()
  const isMobile = useIsMobile()

  return (
    <Popover open={open} onOpenChange={toggle}>
      <PopoverTrigger asChild>
        <Button
          tabIndex={-1}
          variant="outline"
          className="cursor-pointer"
          title="Duplicar várias vezes"
        >
          <CopyPlusIcon />
        </Button>
      </PopoverTrigger>

      <PopoverContent align={isMobile ? 'start' : 'end'} className="w-82">
        <form
          onSubmit={(e) => {
            e.stopPropagation()
            e.preventDefault()
            const formData = new FormData(e.currentTarget)
            const times = parseInt(formData.get('quantity') as string)
            duplicateRow(index, times)
            set(false)
          }}
        >
          <div className="space-y-2.5">
            <h4 className="leading-none font-medium">Duplicar várias vezes</h4>
            <p className="text-muted-foreground text-sm">
              Duplique o curso desta linha na quantidade desejada para agilizar
              o preenchimento.
            </p>

            <div className="grid grid-cols-3 items-center gap-4">
              <Label htmlFor="quantity">Quantidade</Label>
              <Input
                id="quantity"
                name="quantity"
                type="number"
                defaultValue="2"
                min="2"
                max={String(MAX_ITEMS - 1)}
                className="col-span-2"
              />
            </div>

            <div className="flex justify-end gap-2.5">
              <Button
                type="button"
                variant="link"
                tabIndex={-1}
                className="cursor-pointer dark:text-white text-black"
                onClick={() => set(false)}
              >
                Cancelar
              </Button>
              <Button type="submit" className="cursor-pointer">
                Duplicar
              </Button>
            </div>
          </div>
        </form>
      </PopoverContent>
    </Popover>
  )
}
