import { useForm, Controller } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { ErrorMessage } from '@hookform/error-message'
import z from 'zod'

import { Button } from '@repo/ui/components/ui/button'
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 { useWizard } from '@/components/wizard'

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

type Schema = z.infer<typeof formSchema>

type PaymentProps = {
  onSubmit: (value: any) => void | Promise<void>
  defaultValues?: object
}

export function Payment({ onSubmit, defaultValues }: PaymentProps) {
  const wizard = useWizard()
  const { control, handleSubmit } = useForm<Schema>({
    defaultValues: {
      payment_method: '' as any,
      ...defaultValues
    },
    resolver: zodResolver(formSchema)
  })

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

  return (
    <form onSubmit={handleSubmit(onSubmit_)} className="space-y-6">
      <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>
        )}
      />

      <Separator />

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