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

import { isValidCPF } from '@brazilian-utils/brazilian-utils'
import { zodResolver } from '@hookform/resolvers/zod'
import { Loader2Icon } from 'lucide-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 { useState } from 'react'
import logo from './logo.svg'

const cpf = z.string().refine(isValidCPF, { message: 'CPF inválido' })
const email = z.string().email({ message: 'Email inválido' })

const schema = z.object({
  username: z.union([cpf, email]),
  password: z.string().nonempty()
})

type Schema = z.infer<typeof schema>

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

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

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

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

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

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

  const { register, handleSubmit, formState } = useForm({
    resolver: zodResolver(schema)
  })

  const onSubmit = async (data: Schema) => {
    await fetcher.submit(data, { method: 'post' })
    console.log(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 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>

            <div className="grid gap-3">
              <Label htmlFor="email">Email ou CPF</Label>
              <Input id="email" {...register('username')} />
            </div>

            <div className="grid gap-3">
              <div className="flex items-center">
                <Label htmlFor="password">Senha</Label>
                <a
                  href="#"
                  tabIndex={-1}
                  className="ml-auto text-sm underline-offset-4 hover:underline"
                >
                  Esqueceu sua senha?
                </a>
              </div>

              <Input
                id="password"
                type={show ? 'text' : 'password'}
                {...register('password')}
              />

              <div className="flex items-center gap-3">
                <Checkbox
                  id="showPassword"
                  onClick={() => setShow((x) => !x)}
                />
                <Label htmlFor="showPassword">Mostrar senha</Label>
              </div>
            </div>

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

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