import { zodResolver } from '@hookform/resolvers/zod'
import { useEffect, useState } from 'react'
import { useFetcher } 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 { useNewsContext } from '~/contexts/news'

export const loginSchema = z.object({
  email: z.string().email('Email tidak valid'),
  password: z.string().min(6, 'Kata sandi minimal 6 karakter'),
})

export type TLoginSchema = z.infer<typeof loginSchema>

export const FormLogin = () => {
  const {
    setIsRegisterOpen,
    setIsLoginOpen,
    setIsForgetOpen,
    setIsSubscribeOpen,
  } = useNewsContext()
  const fetcher = useFetcher()
  const [error, setError] = useState<string>()
  const [disabled, setDisabled] = useState(false)

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

  const { handleSubmit } = formMethods

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

    setDisabled(true)
    setError(undefined)
    setIsLoginOpen(false)

    if (fetcher.data?.user.subscribe_plan_code === 'basic') {
      setIsSubscribeOpen(true)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [fetcher])

  return (
    <div className="flex 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/login"
          >
            <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"
            />

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

            <div className="flex items-center justify-between text-sm">
              <span className="text-gray-600">Lupa Kata Sandi?</span>
              <Button
                onClick={() => {
                  setIsLoginOpen(false)
                  setIsForgetOpen(true)
                }}
                className="font-semibold text-[#2E2F7C]"
                variant="link"
                size="fit"
              >
                Reset Kata Sandi
              </Button>
            </div>

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

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