import { Fragment, useEffect } from 'react'
import {
  Trash2Icon,
  PlusIcon,
  CircleQuestionMarkIcon,
  ArrowRightIcon
} from 'lucide-react'
import { useForm, useFieldArray, Controller, useWatch } from 'react-hook-form'
import { useParams } from 'react-router'
import { ErrorMessage } from '@hookform/error-message'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { DateTime } from 'luxon'

import { Form } from '@repo/ui/components/ui/form'
import {
  InputGroup,
  InputGroupAddon,
  InputGroupInput
} from '@repo/ui/components/ui/input-group'
import { Button } from '@repo/ui/components/ui/button'
import { Separator } from '@repo/ui/components/ui/separator'
import { Kbd } from '@repo/ui/components/ui/kbd'
import { Spinner } from '@repo/ui/components/ui/spinner'
import {
  HoverCard,
  HoverCardContent,
  HoverCardTrigger
} from '@repo/ui/components/ui/hover-card'

import {
  MAX_ITEMS,
  formSchema,
  type Course,
  type User
} from '../_.$orgid.enrollments.add/data'
import { ScheduledForInput } from '../_.$orgid.enrollments.add/scheduled-for'
import { Cell } from '../_.$orgid.enrollments.add/route'
import { CoursePicker } from '../_.$orgid.enrollments.add/course-picker'
import { UserPicker } from '../_.$orgid.enrollments.add/user-picker'
import { Summary } from './bulk'
import { currency } from './utils'
import { useWizard } from '@/components/wizard'
import { useWizardStore } from './store'

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

type Schema = z.infer<typeof formSchema>

type AssignedProps = {
  courses: Promise<{ hits: Course[] }>
}

export function Assigned({ courses }: AssignedProps) {
  const wizard = useWizard()
  const { orgid } = useParams()
  const { update, ...state } = useWizardStore()
  const form = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: {
      enrollments: state.enrollments.length
        ? state.enrollments.map((e: any) => ({
            ...e,
            scheduled_for: e.scheduled_for
              ? DateTime.fromISO(e.scheduled_for, {
                  zone: 'America/Sao_Paulo'
                }).toJSDate()
              : undefined
          }))
        : [emptyRow]
    }
  })

  const { formState, control, handleSubmit, setValue } = form
  const { fields, remove, append } = useFieldArray({
    control,
    name: 'enrollments'
  })
  const enrollments = useWatch({
    control,
    name: 'enrollments'
  })

  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: User[] }
    return hits
  }

  const onSubmit = async ({ enrollments }: Schema) => {
    update({ enrollments })
    wizard('payment')
  }

  useEffect(() => {
    const parsed = formSchema.safeParse({ enrollments })

    if (parsed.success) {
      update(parsed.data)
    }
  }, [enrollments])

  return (
    <Form {...form}>
      <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
        <div className="grid w-full gap-3 lg:grid-cols-[3fr_3fr_2fr_2fr_auto]">
          {/* Header */}
          <>
            <Cell>Colaborador</Cell>
            <Cell>Curso</Cell>
            <Cell className="flex items-center gap-1.5">
              Matricular em
              <HoverCard openDelay={0}>
                <HoverCardTrigger asChild>
                  <button type="button">
                    <CircleQuestionMarkIcon className="size-4 text-muted-foreground" />
                  </button>
                </HoverCardTrigger>
                <HoverCardContent
                  align="end"
                  className="text-sm space-y-1.5 lg:w-76"
                >
                  <p>
                    Escolha a data em que o colaborador será matriculado no
                    curso.
                  </p>

                  <p>
                    Você poderá acompanhar as matrículas em{' '}
                    <Kbd>Agendamentos</Kbd>
                  </p>
                </HoverCardContent>
              </HoverCard>
            </Cell>
            <Cell>Valor unit.</Cell>
            <Cell>{/**/}</Cell>
          </>

          {/* Rows */}
          {fields.map((field, index) => {
            const { unit_price } = enrollments?.[index]?.course || {
              unit_price: 0
            }

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

                {/* User */}
                <Controller
                  control={control}
                  name={`enrollments.${index}.user`}
                  render={({
                    field: { name, value, onChange },
                    fieldState
                  }) => (
                    <div className="grid gap-1">
                      <UserPicker
                        value={value}
                        onChange={onChange}
                        onSearch={onSearch}
                        fieldState={fieldState}
                      />

                      <ErrorMessage
                        errors={formState.errors}
                        name={name}
                        render={({ message }) => (
                          <p className="text-destructive text-sm">{message}</p>
                        )}
                      />
                    </div>
                  )}
                />

                {/* Course */}
                <Controller
                  control={control}
                  name={`enrollments.${index}.course`}
                  render={({
                    field: { name, value, onChange },
                    fieldState
                  }) => (
                    <div className="grid gap-1">
                      <CoursePicker
                        value={value}
                        onChange={onChange}
                        options={courses}
                        error={fieldState.error}
                        readOnly
                      />

                      <ErrorMessage
                        errors={formState.errors}
                        name={name}
                        render={({ message }) => (
                          <p className="text-destructive text-sm">{message}</p>
                        )}
                      />
                    </div>
                  )}
                />

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

                {/* Unit price */}
                <InputGroup>
                  <InputGroupAddon className="border-r pr-2.5 w-1/3 lg:hidden justify-end">
                    Valor unit.
                  </InputGroupAddon>

                  <InputGroupInput
                    className="pointer-events-none"
                    tabIndex={-1}
                    readOnly
                    value={currency(unit_price)}
                  />
                </InputGroup>

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

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

          {/* Summary */}
          <Summary />
        </div>

        <Separator />

        <div className="flex justify-end">
          <Button
            type="submit"
            variant="secondary"
            className="cursor-pointer"
            disabled={formState.isSubmitting}
          >
            {formState.isSubmitting && <Spinner />}
            Continuar <ArrowRightIcon />
          </Button>
        </div>
      </form>
    </Form>
  )
}
