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

import { isValidCPF } from '@brazilian-utils/brazilian-utils'
import { zodResolver } from '@hookform/resolvers/zod'
import { useForm } from 'react-hook-form'
import { Link } from 'react-router'
import { MailIcon } from 'lucide-react'
import { z } from 'zod'

import logo from '@repo/ui/components/logo2.svg'
import { Button } from '@repo/ui/components/ui/button'
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage
} from '@repo/ui/components/ui/form'
import { Input } from '@repo/ui/components/ui/input'
import { useFetcher } from 'react-router'
import { Spinner } from '@repo/ui/components/ui/spinner'
import { request as req } from '@repo/util/request'
import { useEffect } from 'react'

const schema = z.object({
  username: z
    .string()
    .trim()
    .nonempty('Digite seu Email ou CPF')
    .refine((val) => {
      const onlyDigits = val.replace(/\D/g, '')

      return onlyDigits.length === 11
        ? isValidCPF(val)
        : z.email().safeParse(val).success
    }, 'Deve ser um Email ou CPF válido')
})

type Schema = z.infer<typeof schema>

export function meta({}: Route.MetaArgs) {
  return [{ title: 'Redefinir senha · EDUSEG®' }]
}

export async function action({ request, context }: Route.ActionArgs) {
  const url = new URL('/forgot', context.cloudflare.env.ISSUER_URL)
  const body = await request.json()

  console.log(url.toString())

  const r = await fetch(url.toString(), {
    method: 'POST',
    headers: new Headers({ 'Content-Type': 'application/json' }),
    body: JSON.stringify(body),
    signal: request.signal
  })
  const data = (await r.json()) as any

  if (r.ok) {
    return { ok: true, ...data }
  }

  return { ok: false, ...data }
}

export default function Forgot({}: Route.ComponentProps) {
  const fetcher = useFetcher()
  const form = useForm({ resolver: zodResolver(schema) })
  const { control, handleSubmit, formState, setError } = form

  const onSubmit = async (data: Schema) => {
    await fetcher.submit(data, {
      method: 'POST',
      encType: 'application/json'
    })
  }

  useEffect(() => {
    const message = fetcher.data?.message

    switch (message) {
      case 'User not found':
        return setError('username', {
          message:
            'Não encontramos sua conta. Verifique se está usando o Email ou CPF correto',
          type: 'manual'
        })
    }
  }, [fetcher.data, setError])

  if (fetcher.data?.ok) {
    return (
      <div className="flex flex-col text-center items-center gap-6">
        <MailIcon className="size-12" />
        <div className="space-y-1.5">
          <h1 className="text-xl text-gray-10 font-bold">
            Verifique seu email
          </h1>
          <p>
            Acabamos de enviar um email com as instruções para{' '}
            <span className="font-medium italic">{fetcher.data?.email}</span>
          </p>
        </div>
      </div>
    )
  }

  return (
    <>
      <div className="space-y-6">
        <div className="flex justify-center">
          <div className="border border-white/15 bg-white/5 px-2.5 py-3 rounded-xl">
            <img src={logo} alt="EDUSEG®" className="block size-12" />
          </div>
        </div>

        <div className="text-center space-y-1.5">
          <h1 className="text-2xl font-semibold font-display text-balance">
            Redefinir senha
          </h1>
          <p className="text-white/50 text-sm">
            Digite seu endereço de email e lhe enviaremos um email com as
            instruções para redefinir sua senha.
          </p>
        </div>

        <Form {...form}>
          <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
            <FormField
              control={control}
              name="username"
              defaultValue=""
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Email ou CPF</FormLabel>
                  <FormControl>
                    <Input
                      autoFocus={true}
                      placeholder="seu@email.com"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <Button
              type="submit"
              className="w-full cursor-pointer"
              disabled={formState.isSubmitting}
            >
              {formState.isSubmitting && <Spinner />}
              Enviar instruções
            </Button>
          </form>
        </Form>

        <p className="text-white/50 text-xs text-center">
          Lembrou da senha?{' '}
          <Link to="/" className="underline hover:no-underline">
            Faça login
          </Link>
          .
        </p>
      </div>
    </>
  )
}
