import { useForm, Controller, useWatch, type Control } from 'react-hook-form'
import { PatternFormat } from 'react-number-format'
import { zodResolver } from '@hookform/resolvers/zod'
import { ErrorMessage } from '@hookform/error-message'
import z from 'zod'
import { ArrowRightIcon, CircleQuestionMarkIcon } from 'lucide-react'

import { Button } from '@repo/ui/components/ui/button'
import { Kbd } from '@repo/ui/components/ui/kbd'
import { Label } from '@repo/ui/components/ui/label'
import { RadioGroup, RadioGroupItem } from '@repo/ui/components/ui/radio-group'
import { Separator } from '@repo/ui/components/ui/separator'
import { Input } from '@repo/ui/components/ui/input'
import { Card, CardContent } from '@repo/ui/components/ui/card'
import {
  HoverCard,
  HoverCardContent,
  HoverCardTrigger
} from '@repo/ui/components/ui/hover-card'
import {
  Field,
  FieldGroup,
  FieldLabel,
  FieldSet
} from '@repo/ui/components/ui/field'
import {
  NativeSelect,
  NativeSelectOption
} from '@repo/ui/components/ui/native-select'

import { useWizard } from '@/components/wizard'

const creditCard = z.object({
  holder_name: z.string().min(1),
  number: z.string().min(13).max(19),
  exp_month: z.string().min(2),
  exp_year: z.string().min(4),
  cvv: z.string().min(3).max(4)
})

const formSchema = z.discriminatedUnion(
  'payment_method',
  [
    z.object({
      payment_method: z.literal('PIX')
    }),
    z.object({
      payment_method: z.literal('BANK_SLIP')
    }),
    z.object({
      payment_method: z.literal('CREDIT_CARD'),
      credit_card: creditCard
    })
  ],
  { error: 'Escolha uma forma de pagamento' }
)

type Schema = z.infer<typeof formSchema>

export type CreditCard = z.infer<typeof creditCard>

type PaymentProps = {
  onSubmit: (value: any) => void | Promise<void>
  payment_method?: 'PIX' | 'BANK_SLIP' | 'CREDIT_CARD'
  credit_card?: CreditCard
}

export function Payment({
  onSubmit,
  payment_method: paymentMethodInit,
  credit_card: creditCardInit = undefined
}: PaymentProps) {
  const wizard = useWizard()
  const { control, handleSubmit } = useForm<Schema>({
    defaultValues: {
      payment_method: paymentMethodInit,
      credit_card: creditCardInit
    },
    resolver: zodResolver(formSchema)
  })
  const paymentMethod = useWatch({ control, name: 'payment_method' })

  const onSubmit_ = async (data: Schema) => {
    await onSubmit({ credit_card: undefined, ...data })
    wizard('review')
  }

  return (
    <form onSubmit={handleSubmit(onSubmit_)} className="space-y-4">
      <Controller
        name="payment_method"
        control={control}
        render={({ field: { name, value, onChange }, formState }) => (
          <div className="space-y-1.5">
            <RadioGroup
              value={value}
              onValueChange={onChange}
              className="lg:flex gap-3
                         *:p-5 *:border *:rounded-xl *:flex-1
                         *:cursor-pointer *:bg-accent/25
                         *:has-[button[data-state=checked]]:bg-accent"
            >
              <Label>
                <RadioGroupItem value="PIX" />
                <span>Pix</span>
              </Label>

              <Label>
                <RadioGroupItem value="BANK_SLIP" />
                <span>Boleto bancário</span>
              </Label>

              <Label>
                <RadioGroupItem value="CREDIT_CARD" />
                <span>Cartão de crédito</span>
              </Label>
            </RadioGroup>

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

      {paymentMethod === 'CREDIT_CARD' ? (
        <CreditCard control={control} />
      ) : null}

      <Separator />

      <div className="flex justify-between gap-4 *:cursor-pointer">
        <Button
          type="button"
          variant="link"
          className="text-black dark:text-white"
          onClick={() => wizard('cart')}
          tabIndex={-1}
        >
          Voltar
        </Button>
        <Button type="submit" variant="secondary">
          Continuar <ArrowRightIcon />
        </Button>
      </div>
    </form>
  )
}

export function CreditCard({ control }: { control: Control<Schema> }) {
  const currentYear = new Date().getFullYear()
  const years = Array.from({ length: 10 }, (_, i) => currentYear + i)

  return (
    <Card className="lg:w-1/2">
      <CardContent>
        <FieldGroup>
          <FieldSet>
            <FieldGroup>
              <Controller
                control={control}
                name="credit_card.number"
                render={({
                  field: { onChange, ref, ...field },
                  fieldState
                }) => (
                  <Field data-invalid={fieldState.invalid}>
                    <FieldLabel htmlFor={field.name}>
                      Número do cartão
                    </FieldLabel>
                    <PatternFormat
                      id={field.name}
                      format="#### #### #### ####"
                      mask="_"
                      placeholder="•••• •••• •••• ••••"
                      customInput={Input}
                      getInputRef={ref}
                      aria-invalid={fieldState.invalid}
                      onValueChange={({ value }) => {
                        onChange(value)
                      }}
                      {...field}
                    />
                  </Field>
                )}
              />

              <Controller
                control={control}
                name="credit_card.holder_name"
                defaultValue=""
                render={({ field, fieldState }) => (
                  <Field data-invalid={fieldState.invalid}>
                    <FieldLabel htmlFor={field.name}>
                      Nome do titular
                    </FieldLabel>
                    <Input
                      id={field.name}
                      aria-invalid={fieldState.invalid}
                      {...field}
                    />
                  </Field>
                )}
              />

              <div className="grid grid-cols-3 gap-4">
                <Controller
                  control={control}
                  name="credit_card.exp_month"
                  defaultValue=""
                  render={({ field, fieldState }) => (
                    <Field data-invalid={fieldState.invalid}>
                      <FieldLabel htmlFor={field.name}>Mês</FieldLabel>
                      <NativeSelect
                        id={field.name}
                        value={field.value}
                        onChange={field.onChange}
                        aria-invalid={fieldState.invalid}
                      >
                        <NativeSelectOption value="" disabled>
                          Selecione
                        </NativeSelectOption>

                        {Array.from({ length: 12 }, (_, i) => {
                          const v = String(i + 1).padStart(2, '0')
                          return (
                            <NativeSelectOption key={v} value={v}>
                              {v}
                            </NativeSelectOption>
                          )
                        })}
                      </NativeSelect>
                    </Field>
                  )}
                />

                <Controller
                  control={control}
                  name="credit_card.exp_year"
                  defaultValue=""
                  render={({ field, fieldState }) => (
                    <Field data-invalid={fieldState.invalid}>
                      <FieldLabel htmlFor={field.name}>Ano</FieldLabel>
                      <NativeSelect
                        id={field.name}
                        value={field.value}
                        onChange={field.onChange}
                        aria-invalid={fieldState.invalid}
                      >
                        <NativeSelectOption value="" disabled>
                          Selecione
                        </NativeSelectOption>

                        {years.map((year) => (
                          <NativeSelectOption key={year} value={String(year)}>
                            {year}
                          </NativeSelectOption>
                        ))}
                      </NativeSelect>
                    </Field>
                  )}
                />

                <Controller
                  control={control}
                  name="credit_card.cvv"
                  defaultValue=""
                  render={({ field, fieldState }) => (
                    <Field data-invalid={fieldState.invalid}>
                      <FieldLabel htmlFor={field.name}>
                        CVC
                        <HoverCard openDelay={0}>
                          <HoverCardTrigger asChild>
                            <button type="button" tabIndex={-1}>
                              <CircleQuestionMarkIcon className="size-4 text-muted-foreground" />
                            </button>
                          </HoverCardTrigger>
                          <HoverCardContent
                            align="end"
                            className="text-sm space-y-1.5 lg:w-78"
                          >
                            <p>
                              O <Kbd>CVC</Kbd> é o código de segurança do cartão
                              de crédito.
                            </p>

                            <p>
                              Ele fica no verso do cartão e geralmente possui{' '}
                              <Kbd>3 dígitos</Kbd> (ou <Kbd>4 dígitos</Kbd> na
                              frente, no caso do American Express).
                            </p>
                          </HoverCardContent>
                        </HoverCard>
                      </FieldLabel>
                      <Input
                        id={field.name}
                        aria-invalid={fieldState.invalid}
                        {...field}
                      />
                    </Field>
                  )}
                />
              </div>
            </FieldGroup>
          </FieldSet>
        </FieldGroup>
      </CardContent>
    </Card>
  )
}
