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

import type { TCategoryResponse } from '~/apis/common/get-categories'
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 categorySchema = z.object({
  id: z.string().optional(),
  name: z.string().min(3, 'Nama minimal 3 karakter'),
  code: z.string(),
  sequence: z.preprocess(Number, z.number().optional()),
  description: z.string(),
})
export type TCategorySchema = z.infer<typeof categorySchema>
type TProperties = {
  categoryData?: TCategoryResponse
}

export const FormCategoryPage = (properties: TProperties) => {
  const { categoryData } = properties || {}
  const fetcher = useFetcher()
  const navigate = useNavigate()
  const formMethods = useRemixForm<TCategorySchema>({
    mode: 'onSubmit',
    fetcher,
    resolver: zodResolver(categorySchema),
    values: {
      id: categoryData?.id || undefined,
      code: categoryData?.code || '',
      name: categoryData?.name || '',
      sequence: categoryData?.sequence || undefined,
      description: categoryData?.description || '',
    },
  })

  const { handleSubmit, watch, setValue } = formMethods
  const watchName = watch('name')

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

    if (fetcher.data?.success === true) {
      toast.success(
        `Kategori berhasil ${categoryData ? 'diupdate' : 'dibuat'}!`,
      )
      navigate('/lg-admin/categories')
      return
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [fetcher.data])

  useEffect(() => {
    setValue('code', urlFriendlyCode(watchName))
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [watchName])

  return (
    <div className="relative">
      <TitleDashboard title={`${categoryData ? 'Update' : 'Buat'} Kategori`} />
      <div>
        <RemixFormProvider {...formMethods}>
          <fetcher.Form
            method="post"
            onSubmit={handleSubmit}
            action={`/actions/admin/categories/${categoryData ? 'update' : 'create'}`}
            className="space-y-4"
          >
            <div className="flex items-end justify-between gap-4">
              <Input
                id="name"
                label="Kategori"
                placeholder="Masukkan Nama Kategori"
                name="name"
                className="border-0 bg-white shadow read-only:bg-gray-100 focus:ring-1 focus:ring-[#2E2F7C] focus:outline-none disabled:bg-gray-100"
                labelClassName="text-sm font-medium text-[#363636]"
                containerClassName="flex-1"
              />
              <Input
                id="code"
                label="Kode"
                placeholder="Masukkan Kode Kategori"
                readOnly
                name="code"
                className="border-0 bg-white shadow read-only:bg-gray-100 focus:ring-1 focus:ring-[#2E2F7C] focus:outline-none disabled:bg-gray-100"
                labelClassName="text-sm font-medium text-[#363636]"
                containerClassName="flex-1"
              />
              <Button
                isLoading={fetcher.state !== 'idle'}
                disabled={fetcher.state !== 'idle'}
                type="submit"
                size="lg"
                className="text-md h-[42px] rounded-md"
              >
                Save
              </Button>
            </div>
            <div className="flex items-end justify-between gap-4">
              <Input
                id="sequence"
                label="Urutan"
                placeholder="Urutan Kategori"
                name="sequence"
                type="number"
                className="border-0 bg-white shadow read-only:bg-gray-100 focus:ring-1 focus:ring-[#2E2F7C] focus:outline-none disabled:bg-gray-100"
                labelClassName="text-sm font-medium text-[#363636]"
                containerClassName="w-44"
              />
              <Input
                id="description"
                label="Deskripsi"
                placeholder="Masukkan Deskripsi Kategori"
                name="description"
                className="border-0 bg-white shadow read-only:bg-gray-100 focus:ring-1 focus:ring-[#2E2F7C] focus:outline-none disabled:bg-gray-100"
                labelClassName="text-sm font-medium text-[#363636]"
                containerClassName="flex-1"
              />
            </div>
          </fetcher.Form>
        </RemixFormProvider>
      </div>
    </div>
  )
}
