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

import { isValidCPF } from '@brazilian-utils/brazilian-utils'
import { zodResolver } from '@hookform/resolvers/zod'
import { Loader2Icon } from 'lucide-react'
import { useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'
import { Link, useFetcher } from 'react-router'
import { z } from 'zod'

import logo from '@repo/ui/components/logo2.svg'
import { Button } from '@repo/ui/components/ui/button'
import { Checkbox } from '@repo/ui/components/ui/checkbox'
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage
} from '@repo/ui/components/ui/form'
import { Input } from '@repo/ui/components/ui/input'
import { Label } from '@repo/ui/components/ui/label'

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'),
  password: z
    .string()
    .nonempty('Digite sua senha')
    .min(6, 'Deve ter no mínimo 6 caracteres')
})

type Schema = z.infer<typeof schema>

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

export async function action({ request, context }: Route.ActionArgs) {
  const issuerUrl = new URL('/session', context.cloudflare.env.ISSUER_URL)
  const formData = Object.fromEntries(await request.formData())

  try {
    const r = await fetch(issuerUrl.toString(), {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(formData)
    })

    if (r.status === 200) {
      return Response.json(await r.json(), {
        status: r.status,
        headers: r.headers
      })
    }

    const url = new URL(request.url)
    url.pathname = '/authorize'

    const headers = new Headers(r.headers)
    headers.set('Location', url.toString())

    return new Response(await r.text(), {
      status: 302,
      headers
    })
  } catch (error) {
    console.error(error)
    return Response.json({}, { status: 500 })
  }
}

export default function Index({}: Route.ComponentProps) {
  const [show, setShow] = useState(false)
  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' })
  }

  useEffect(() => {
    if (fetcher.state === 'idle' && fetcher.data) {
      const message = fetcher.data?.message

      switch (message) {
        case 'User not found':
          return setError('username', {
            message:
              'Conta não encontrada. Certifique-se de que está usando o Email ou CPF correto.',
            type: 'manual'
          })
        case 'Invalid credentials':
          return setError('password', {
            message: 'A senha está incorreta.',
            type: 'manual'
          })
      }
    }
  }, [fetcher.state, fetcher.data])

  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>

        <Form {...form}>
          <form onSubmit={handleSubmit(onSubmit)} className="grid gap-6">
            <div className="text-center space-y-1.5">
              <h1 className="text-2xl font-semibold font-display text-balance">
                Entrar
              </h1>
              <p className="text-white/50 text-sm">
                Não tem uma senha?{' '}
                <Link
                  to="/signup"
                  className="font-medium text-white hover:underline"
                >
                  Criar senha
                </Link>
                .
              </p>
            </div>

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

            <FormField
              control={control}
              name="password"
              defaultValue=""
              render={({ field }) => (
                <FormItem>
                  <div className="flex">
                    <FormLabel>Senha</FormLabel>
                    <Link
                      to="/forgot"
                      tabIndex={-1}
                      className="ml-auto text-sm underline-offset-4 hover:underline"
                    >
                      Esqueceu sua senha?
                    </Link>
                  </div>
                  <FormControl>
                    <Input
                      type={show ? 'text' : 'password'}
                      placeholder="••••••••"
                      {...field}
                    />
                  </FormControl>
                  <div className="flex items-center gap-3">
                    <Checkbox
                      id="showPassword"
                      onClick={() => setShow((x) => !x)}
                      tabIndex={-1}
                    />
                    <Label htmlFor="showPassword">Mostrar senha</Label>
                  </div>
                  <FormMessage />
                </FormItem>
              )}
            />

            <Button
              type="submit"
              className="w-full cursor-pointer"
              disabled={formState.isSubmitting}
            >
              {formState.isSubmitting && (
                <Loader2Icon className="animate-spin" />
              )}
              Entrar
            </Button>
          </form>
        </Form>

        <p className="text-white/50 text-xs text-center">
          Ao fazer login, você concorda com nossa{' '}
          <a
            href="//eduseg.com.br/politica"
            target="_blank"
            className="underline hover:no-underline"
          >
            política de privacidade
          </a>
          .
        </p>
      </div>
    </>
  )
}
