"use client"

import { zodResolver } from "@hookform/resolvers/zod"
import { useRouter } from "next/navigation"
import { useForm } from "react-hook-form"
import { toast } from "sonner"

import { SubmitButton } from "@/components/forms/submitButton"
import { createCategoryAction } from "@/lib/actions/category.actions"
import {
  CreateCategoryFormType,
  createCategorySchema,
} from "@/lib/schemas/category.schemas"

export default function NewCategoryForm() {
  const router = useRouter()

  const {
    register,
    handleSubmit,
    setError,
    formState: { errors, isSubmitting, isSubmitSuccessful },
  } = useForm<CreateCategoryFormType>({
    resolver: zodResolver(createCategorySchema),
  })

  const onSubmit = async (formData: CreateCategoryFormType) => {
    const response = await createCategoryAction(formData)

    if (response?.errors) {
      Object.entries(response.errors).forEach(([fieldName, messages]) => {
        messages.forEach((msg: string) => {
          setError(fieldName as keyof CreateCategoryFormType, {
            type: "server",
            message: msg,
          })
          toast.error(msg)
        })
      })
      return
    }

    if (response?.success) {
      toast.success(response.message)
      router.push("/inventory/categories")
    }
  }

  return (
    <form className="flex flex-col gap-4" onSubmit={handleSubmit(onSubmit)}>
      <div className="flex flex-col gap-2">
        <label htmlFor="name" className="mb-2 block text-lg">
          Name
        </label>
        <input
          type="text"
          id="name"
          placeholder="Category name"
          {...register("name")}
          className={`w-full rounded-lg border px-4 py-2 ${
            errors.name ? "border-error" : ""
          }`}
        />
        {errors.name && <p className="text-error">{errors.name.message}</p>}
      </div>
      <SubmitButton
        isSubmitting={isSubmitting}
        isSubmitSuccessful={isSubmitSuccessful}
      >
        Create Category
      </SubmitButton>
    </form>
  )
}
