import { zodResolver } from '@hookform/resolvers/zod'
import { useEffect, useState } from 'react'
import { useFetcher, useRouteLoaderData } from 'react-router'
import { RemixFormProvider, useRemixForm } from 'remix-hook-form'
import { z } from 'zod'

import { Button } from '~/components/ui/button'
import { Input } from '~/components/ui/input'
import { Select } from '~/components/ui/select'
import { useNewsContext } from '~/contexts/news'
import type { loader } from '~/routes/_layout'

export const registerSchema = z
  .object({
    email: z.string().email('Email tidak valid'),
    password: z.string().min(6, 'Kata sandi minimal 6 karakter'),
    rePassword: z.string().min(6, 'Kata sandi minimal 6 karakter'),
    phone: z.string().min(10, 'No telepon tidak valid'),
    subscribe_plan: z.string().min(1, 'Pilih salah satu subscription'),
  })
  .refine((field) => field.password === field.rePassword, {
    message: 'Kata sandi tidak sama',
    path: ['rePassword'],
  })

export type TRegisterSchema = z.infer<typeof registerSchema>

export const FormRegister = () => {
  const { setIsLoginOpen, setIsRegisterOpen } = useNewsContext()
  const [error, setError] = useState<string>()
  const [disabled, setDisabled] = useState(false)
  const fetcher = useFetcher()
  const loaderData = useRouteLoaderData<typeof loader>('routes/_layout')

  const formMethods = useRemixForm<TRegisterSchema>({
    mode: 'onSubmit',
    fetcher,
    resolver: zodResolver(registerSchema),
  })

  const { handleSubmit } = formMethods

  useEffect(() => {
    if (!fetcher.data?.success) {
      setError(fetcher.data?.message)
      setDisabled(false)
      return
    }

    setDisabled(true)
    setError(undefined)
    setIsRegisterOpen(false)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [fetcher])

  return (
    <div className="flex flex-col items-center justify-center">
      <div className="w-full max-w-md">
        <RemixFormProvider {...formMethods}>
          <fetcher.Form
            method="post"
            onSubmit={handleSubmit}
            className="space-y-4"
            action="/actions/register"
          >
            <Input
              id="email"
              label="Email"
              placeholder="Contoh: legal@legalgo.id"
              name="email"
            />

            <Input
              id="password"
              label="Kata Sandi"
              placeholder="Masukkan Kata Sandi"
              name="password"
              type="password"
            />

            <Input
              id="re-password"
              label="Ulangi Kata Sandi"
              placeholder="Masukkan Kata Sandi"
              name="rePassword"
              type="password"
            />

            <Input
              id="phone"
              label="No. Telepon"
              placeholder="Masukkan No. Telepon"
              name="phone"
            />

            <Select
              id="subscribe_plan"
              name="subscribe_plan"
              label="Subscription"
              placeholder="Pilih Subscription"
              options={loaderData?.subscriptionsData}
            />

            {error && (
              <div className="text-sm text-red-500 capitalize">{error}</div>
            )}

            <Button
              disabled={disabled}
              type="submit"
              className="w-full rounded-md bg-[#2E2F7C] py-2 text-white transition hover:bg-blue-800"
            >
              Daftar
            </Button>
          </fetcher.Form>
        </RemixFormProvider>

        {/* Link Login */}
        <div className="mt-4 text-center text-sm">
          Sudah punya akun?{' '}
          <Button
            onClick={() => {
              setIsLoginOpen(true)
              setIsRegisterOpen(false)
            }}
            className="font-semibold text-[#2E2F7C]"
            variant="link"
            size="fit"
          >
            Masuk Disini
          </Button>
        </div>
      </div>
    </div>
  )
}
