import { Fragment } from 'react'
import { MinusIcon, 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 { Button } from '@repo/ui/components/ui/button'
import {
  InputGroup,
  InputGroupAddon,
  InputGroupButton,
  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().min(1)
})

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, register, setValue, getValues } =
    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-[4fr_2fr_2fr_2fr_auto]">
          {/* Header */}
          <>
            <Cell>Curso</Cell>
            <Cell>Quantidade</Cell>
            <Cell>Valor unit.</Cell>
            <Cell>Total</Cell>
            <Cell>{/**/}</Cell>
          </>

          {/* Rows */}
          {fields.map((field, index) => {
            const item = items?.[index] || { course: {}, quantity: 1 }
            const { course, quantity } = item

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

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

                <InputGroup>
                  <InputGroupInput
                    type="number"
                    min={1}
                    defaultValue={1}
                    className="no-spinner"
                    {...register(`items.${index}.quantity`, {
                      valueAsNumber: true,
                      onBlur: (e) => {
                        const value = Number(e.target.value)

                        if (!value || value < 1) {
                          setValue(`items.${index}.quantity`, 1)
                        }
                      }
                    })}
                  />

                  <InputGroupAddon align="inline-end">
                    <InputGroupButton
                      type="button"
                      size="icon-xs"
                      className="border cursor-pointer"
                      onClick={() => {
                        const quantity =
                          getValues(`items.${index}.quantity`) || 1
                        setValue(
                          `items.${index}.quantity`,
                          Math.max(1, quantity - 1)
                        )
                      }}
                    >
                      <MinusIcon />
                    </InputGroupButton>
                  </InputGroupAddon>

                  <InputGroupAddon align="inline-end">
                    <InputGroupButton
                      type="button"
                      size="icon-xs"
                      className="border cursor-pointer"
                      onClick={() => {
                        const quantity =
                          getValues(`items.${index}.quantity`) || 1
                        setValue(`items.${index}.quantity`, quantity + 1)
                      }}
                    >
                      <PlusIcon />
                    </InputGroupButton>
                  </InputGroupAddon>
                </InputGroup>

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

                <InputGroup>
                  <InputGroupInput
                    className="pointer-events-none"
                    readOnly
                    value={currency.format(
                      (course?.unit_price || 0) *
                        (Number.isFinite(quantity) && quantity > 0
                          ? quantity
                          : 1)
                    )}
                  />
                </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'
})
