"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 { updateCategoryAction } from "@/lib/actions/category.actions"
import {
  UpdateCategoryFormType,
  updateCategorySchema,
} from "@/lib/schemas/category.schemas"
import { CategorySummary } from "@/lib/types"

export default function EditCategoryForm({
  category,
}: {
  category: CategorySummary
}) {
  const router = useRouter()

  const {
    register,
    handleSubmit,
    setError,
    formState: { errors, isSubmitting, isSubmitSuccessful },
  } = useForm<UpdateCategoryFormType>({
    resolver: zodResolver(updateCategorySchema),
    defaultValues: {
      id: category.id,
      name: category.name,
    },
  })

  const onSubmit = async (formData: UpdateCategoryFormType) => {
    const response = await updateCategoryAction(formData)

    if (response?.errors) {
      Object.entries(response.errors).forEach(([fieldName, messages]) => {
        messages.forEach((msg: string) => {
          setError(fieldName as keyof UpdateCategoryFormType, {
            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)}>
      <input type="hidden" {...register("id")} />
      <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}
      >
        Update Category
      </SubmitButton>
    </form>
  )
}
