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

import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage
} from '@/components/ui/form'
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 { useFetcher } from 'react-router'
import { z } from 'zod'

import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import * as httpStatus from '@/lib/http-status'

import logo from '@/components/logo.svg'

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

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

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 !== httpStatus.OK) {
      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: httpStatus.FOUND,
      headers
    })
  } catch {
    return Response.json({}, { status: httpStatus.INTERNAL_SERVER })
  }
}

export default function Index({}: Route.ComponentProps) {
  const [show, setShow] = useState(false)
  const fetcher = useFetcher()

  const form = useForm({
    resolver: zodResolver(schema),
    defaultValues: { username: '', password: '' }
  })
  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: 'Usuário não encontrado',
            type: 'manual'
          })
        case 'Invalid credentials':
          return setError('password', {
            message: 'A senha está incorreta',
            type: 'manual'
          })
      }
    }
  }, [fetcher.state, fetcher.data])

  return (
    <>
      <div className="w-full max-w-xs grid gap-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="React Router" className="block size-12" />
          </div>
        </div>

        <Form {...form}>
          <form onSubmit={handleSubmit(onSubmit)}>
            <div className="grid gap-6">
              <div className="text-center space-y-1.5">
                <h1 className="text-2xl font-semibold font-display text-balance">
                  Faça login
                </h1>
                <p className="text-white/50 text-sm">
                  Não tem uma conta?{' '}
                  <a href="#" className="font-medium text-white">
                    Cadastre-se
                  </a>
                  .
                </p>
              </div>

              <FormField
                control={control}
                name="username"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Email ou CPF</FormLabel>
                    <FormControl>
                      <Input autoFocus={true} {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={control}
                name="password"
                render={({ field }) => (
                  <FormItem>
                    <div className="flex">
                      <FormLabel>Senha</FormLabel>
                      <a
                        href="#"
                        tabIndex={-1}
                        className="ml-auto text-sm underline-offset-4 hover:underline"
                      >
                        Esqueceu sua senha?
                      </a>
                    </div>
                    <FormControl>
                      <Input type={show ? 'text' : 'password'} {...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 bg-lime-400 cursor-pointer"
                disabled={formState.isSubmitting}
              >
                {formState.isSubmitting && (
                  <Loader2Icon className="animate-spin" />
                )}
                Entrar
              </Button>
            </div>
          </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>
    </>
  )
}
