import { Fragment } from 'react'
import { Trash2Icon, PlusIcon } 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 { Form } from '@repo/ui/components/ui/form'
import { InputGroup, 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 {
  MAX_ITEMS,
  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'

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

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

export function Assigned({ courses }: AssignedProps) {
  const { orgid } = useParams()
  const form = useForm({
    // resolver: zodResolver(formSchema),
    defaultValues: { enrollments: [emptyRow] }
  })
  const { formState, control, handleSubmit, getValues, watch } = form
  const { fields, insert, remove, append } = useFieldArray({
    control,
    name: 'enrollments'
  })
  const items = 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
  }

  return (
    <Form {...form}>
      <div className="grid w-full gap-1.5 lg:grid-cols-[repeat(4,1fr)_auto]">
        {/* Header */}
        <>
          <Cell>Colaborador</Cell>
          <Cell>Curso</Cell>
          <Cell>Matricular em</Cell>
          <Cell>Valor unit.</Cell>
          <Cell>{/**/}</Cell>
        </>

        {/* Rows */}
        {fields.map((field, index) => {
          const course = items?.[index]?.course
          return (
            <Fragment key={field.id}>
              <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>
                )}
              />

              <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}
                    />

                    <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} />
                )}
              />

              <InputGroup>
                {/*<InputGroupAddon>
                <InputGroupText>R$</InputGroupText>
              </InputGroupAddon>*/}

                <InputGroupInput
                  className="pointer-events-none"
                  value={currency.format(course?.unit_price || 0)}
                />
              </InputGroup>

              <Button
                tabIndex={-1}
                variant="destructive"
                className="cursor-pointer"
                disabled={fields.length == 1}
                onClick={() => remove(index)}
              >
                <Trash2Icon />
              </Button>
            </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">
        Continuar
      </Button>
    </Form>
  )
}

const currency = new Intl.NumberFormat('pt-BR', {
  style: 'currency',
  currency: 'BRL'
})
