import { zodResolver } from '@hookform/resolvers/zod'
import { useEffect, useState, type ChangeEvent } from 'react'
import { useFetcher, useNavigate } 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 { TitleDashboard } from '~/components/ui/title-dashboard'
import { urlFriendlyCode } from '~/utils/formatter'

export const createCategorySchema = z.object({
  code: z.string().min(3, 'Kode minimal 3 karakter'),
  name: z.string().min(3, 'Nama minimal 3 karakter'),
})
export type TCategorySchema = z.infer<typeof createCategorySchema>

export const FormCategoryPage = () => {
  const fetcher = useFetcher()
  const navigate = useNavigate()
  const formMethods = useRemixForm<TCategorySchema>({
    mode: 'onSubmit',
    fetcher,
    resolver: zodResolver(createCategorySchema),
  })
  const [error, setError] = useState<string>()
  const [disabled, setDisabled] = useState(false)
  const [code, setCode] = useState<string>('')
  const [name, setName] = useState<string>('')

  const { handleSubmit } = formMethods

  useEffect(() => {
    if (!fetcher.data?.success) {
      setError(fetcher.data?.message)
      setDisabled(false)
      return
    }
    navigate('/lg-admin/categories')
    setDisabled(true)
    setError(undefined)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [fetcher])

  const handelCodeAuto = (name: ChangeEvent<HTMLInputElement>) => {
    const inputName = name.target.value
    setName(inputName)
    setCode(urlFriendlyCode(inputName))
  }

  return (
    <div className="relative">
      <TitleDashboard title="Buat Kategory" />
      <div>
        <RemixFormProvider {...formMethods}>
          <fetcher.Form
            method="post"
            onSubmit={handleSubmit}
            action="/actions/admin/categories/create"
            className="space-y-4"
          >
            {error && (
              <div className="text-sm text-red-500 capitalize">{error}</div>
            )}
            <div className="flex items-end justify-between gap-4">
              <Input
                id="name"
                label="Nama Kategory"
                placeholder="Masukkan Nama Kategory"
                name="name"
                onChange={handelCodeAuto}
                className="border-0 bg-white shadow focus:ring-1 focus:ring-[#2E2F7C] focus:outline-none"
                labelClassName="text-sm font-medium text-[#363636]"
                containerClassName="flex-1"
                value={name}
              />
              <Input
                id="code"
                label="Kode Kategory"
                readOnly
                placeholder="Masukkan Kode Kategory"
                name="code"
                className="border-0 bg-gray-100 shadow focus:ring-1 focus:ring-[#2E2F7C] focus:outline-none"
                labelClassName="text-sm font-medium text-[#363636]"
                containerClassName="flex-1"
                value={code}
              />
              <Button
                disabled={disabled}
                type="submit"
                size="lg"
                className="text-md h-[42px] rounded-md"
              >
                Save
              </Button>
            </div>
          </fetcher.Form>
        </RemixFormProvider>
      </div>
    </div>
  )
}
