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

import { Form } from '@repo/ui/components/ui/form'
import { Input } from '@repo/ui/components/ui/input'
import { Button } from '@repo/ui/components/ui/button'
import { InputGroup, InputGroupInput } from '@repo/ui/components/ui/input-group'
import { Separator } from '@repo/ui/components/ui/separator'

import { Cell } from '../_.$orgid.enrollments.add/route'
import { CoursePicker } from '../_.$orgid.enrollments.add/course-picker'
import { MAX_ITEMS, type Course } from '../_.$orgid.enrollments.add/data'

const emptyRow = {
  course: undefined,
  quantity: undefined
}

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

const item = z.object({
  course: z
    .object(
      {
        id: z.string(),
        name: z.string(),
        access_period: z.number(),
        unit_price: z.number()
      },
      { error: 'Escolha um curso' }
    )
    .required(),
  quantity: z.number()
})

const formSchema = z.object({
  items: z.array(item).min(1).max(MAX_ITEMS)
})

type Schema = z.infer<typeof formSchema>

export function Bulk({ courses }: BulkProps) {
  const form = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: { items: [emptyRow] }
  })
  const { formState, control, handleSubmit } = form
  const { fields, remove, append } = useFieldArray({
    control,
    name: 'items'
  })
  const items = useWatch({
    control,
    name: 'items'
  })

  const onSubmit = async (data: Schema) => {
    console.log(data)
  }

  return (
    <Form {...form}>
      <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
        <div className="grid w-full gap-1.5 lg:grid-cols-[repeat(3,1fr)_auto]">
          {/* Header */}
          <>
            <Cell>Curso</Cell>
            <Cell>Quantidade</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={`items.${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>
                  )}
                />

                <Input type="number" defaultValue={1} />
                <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>
    </Form>
  )
}

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