import type { Route } from './+types/route'

import { isValidCNPJ } from '@brazilian-utils/brazilian-utils'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { PatternFormat } from 'react-number-format'

import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage
} from '@repo/ui/components/ui/form'
import { Input } from '@repo/ui/components/ui/input'
import { Button } from '@repo/ui/components/ui/button'
import z from 'zod'

const formSchema = z.object({
  cnpj: z
    .string('CNPJ obrigatório')
    .refine(isValidCNPJ, { message: 'CNPJ inválido' })
})

export type Schema = z.infer<typeof formSchema>

export default function Route({}: Route.ComponentProps) {
  const form = useForm({ resolver: zodResolver(formSchema) })
  const { handleSubmit, control } = form
  const onSubmit = async (data: Schema) => {
    console.log(data)
  }

  return (
    <>
      <div className="text-center space-y-1.5">
        <h1 className="text-2xl font-semibold font-display text-balance">
          Crie a conta da sua empresa
        </h1>
        <p className="text-white/50 text-sm">
          Uma plataforma única para gerenciar os treinamentos dos seus
          colaboradores.
        </p>
      </div>

      <Form {...form}>
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
          <FormField
            control={control}
            name="cnpj"
            render={({ field: { onChange, ref } }) => (
              <FormItem className="grid gap-3">
                <FormLabel>CNPJ</FormLabel>
                <FormControl>
                  <PatternFormat
                    format="##.###.###/####-##"
                    mask="_"
                    autoFocus={true}
                    placeholder="__.___.__/____-__"
                    customInput={Input}
                    getInputRef={ref}
                    onValueChange={({ value }) => {
                      onChange(value)
                    }}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <Button type="submit" className="w-full cursor-pointer">
            Continuar
          </Button>
        </form>
      </Form>
    </>
  )
}
