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

import { DialogNews } from '~/components/dialog/news'
import { Button } from '~/components/ui/button'
import { Combobox } from '~/components/ui/combobox'
import { Input } from '~/components/ui/input'
import { useNewsContext } from '~/contexts/news'
import type { loader } from '~/routes/_news'

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
      .object({
        id: z.string(),
        code: z.string(),
        name: z.string(),
      })
      .optional()
      .nullable()
      .refine((data) => !!data, {
        message: 'Please select a Subscribe Plan',
      }),
  })
  .refine((field) => field.password === field.rePassword, {
    message: 'Kata sandi tidak sama',
    path: ['rePassword'],
  })

export type TRegisterSchema = z.infer<typeof registerSchema>

export const DialogRegister = () => {
  const {
    setIsLoginOpen,
    setIsRegisterOpen,
    setIsSuccessOpen,
    isRegisterOpen,
  } = useNewsContext()
  const fetcher = useFetcher()
  const loaderData = useRouteLoaderData<typeof loader>('routes/_news')
  const { subscribePlanData: subscribePlan } = loaderData || {}

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

  const { handleSubmit, control } = formMethods

  useEffect(() => {
    if (!fetcher.data?.success && fetcher.data?.message) {
      toast.error(fetcher.data.message)
    }

    if (fetcher.data?.success) {
      setIsRegisterOpen(false)
      setIsSuccessOpen('register')
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [fetcher.data])

  return (
    <DialogNews
      isOpen={isRegisterOpen}
      onClose={() => {
        if (fetcher.state === 'idle') {
          setIsRegisterOpen(false)
        }
      }}
      description="Selamat Datang, silakan isi keterangan akun Anda untuk melanjutkan!"
    >
      <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"
              />

              <Combobox
                id="subscribe_plan"
                name="subscribe_plan"
                label="Subscribe Plan"
                placeholder="Pilih Subscribe Plan"
                options={subscribePlan}
              />

              <Button
                isLoading={fetcher.state !== 'idle'}
                disabled={fetcher.state !== 'idle'}
                type="submit"
                className="w-full rounded-md py-2"
              >
                Daftar
              </Button>
            </fetcher.Form>
          </RemixFormProvider>

          {/* Link Login */}
          <div className="mt-4 text-center text-sm">
            Sudah punya akun?{' '}
            <Button
              onClick={() => {
                setIsLoginOpen(true)
                setIsRegisterOpen(false)
              }}
              variant="link"
              size="fit"
            >
              Masuk Disini
            </Button>
          </div>
        </div>
        <DevTool control={control} />
      </div>
    </DialogNews>
  )
}
