"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 { updateItemAction } from "@/lib/actions/item.actions"
import {
  UpdateItemFormType,
  updateItemSchema,
} from "@/lib/schemas/item.schemas"
import { CategorySummary, ItemWithAssetCount } from "@/lib/types"

export default function UpdateItemForm({
  categories,
  item,
}: {
  categories: CategorySummary[]
  item: ItemWithAssetCount
}) {
  const router = useRouter()

  const isDisabled = !!item?._count.assets && item?._count.assets > 0

  const {
    register,
    handleSubmit,
    setError,
    formState: { errors, isSubmitting, isSubmitSuccessful },
  } = useForm<UpdateItemFormType>({
    resolver: zodResolver(updateItemSchema),
    defaultValues: {
      id: item?.id,
      name: item?.name,
      categoryId: item?.category.id,
      stock: item?.stock,
    },
    shouldFocusError: true,
    mode: "onSubmit",
  })

  const onSubmit = async (formData: UpdateItemFormType) => {
    const response = await updateItemAction(formData)

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

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

  return (
    <form className="flex flex-col gap-4" onSubmit={handleSubmit(onSubmit)}>
      {item?.id && <input type="hidden" name="id" value={item.id} />}
      <div>
        <label htmlFor="name" className="mb-2 block text-lg">
          Name
        </label>
        <input
          type="text"
          id="name"
          placeholder="Item name"
          {...register("name")}
          className={`w-full rounded-lg border px-4 py-2`}
        />
        {errors?.name && <p className="text-error">{errors.name.message}</p>}
      </div>
      <div>
        <label htmlFor="categoryId" className="mb-2 block text-lg">
          Category
        </label>
        <select
          id="categoryId"
          // disabled={isDisabled}
          {...register("categoryId")}
          className={`w-full rounded-lg border px-4 py-2`}
        >
          <option value="">Select a category</option>
          {categories?.map((category) => (
            <option key={category.id} value={category.id}>
              {category.name}
            </option>
          ))}
        </select>
        {errors?.categoryId && (
          <p className="text-error">{errors.categoryId.message}</p>
        )}
      </div>
      <div>
        <label htmlFor="stock" className="mb-2 block text-lg">
          Stock
        </label>
        <input
          type="number"
          id="stock"
          pattern="{[0-9]*}"
          placeholder="0"
          min={item.stock}
          disabled={isDisabled}
          {...register("stock")}
          className={`w-full rounded-lg border px-4 py-2 ${
            isDisabled ? "bg-gray-100" : ""
          }`}
          onKeyDownCapture={(event) => {
            if (!/[0-9]/.test(event.key)) {
              event.preventDefault()
            }
            if (event.key === "Backspace") {
              event.preventDefault()
              event.currentTarget.value = event.currentTarget.value.slice(
                0,
                event.currentTarget.value.length - 1,
              )
            }
          }}
        />
        {errors?.stock && <p className="text-error">{errors.stock.message}</p>}
      </div>
      <SubmitButton
        isSubmitting={isSubmitting}
        isSubmitSuccessful={isSubmitSuccessful}
      >
        Update Item
      </SubmitButton>
    </form>
  )
}
