"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 { createItemAction } from "@/lib/actions/item.actions"
import {
  CreateItemFormType,
  createItemSchema,
} from "@/lib/schemas/item.schemas"
import { CategorySummary } from "@/lib/types"

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

  const {
    register,
    handleSubmit,
    setError,
    formState: { errors, isSubmitting, isSubmitSuccessful },
  } = useForm<CreateItemFormType>({
    resolver: zodResolver(createItemSchema),
    shouldFocusError: true,
    mode: "onSubmit",
  })

  const onSubmit = async (formData: CreateItemFormType) => {
    const response = await createItemAction(formData)

    if (response?.errors) {
      Object.entries(response.errors).forEach(([fieldName, messages]) => {
        messages.forEach((msg: string) => {
          setError(fieldName as keyof CreateItemFormType, {
            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)}>
      <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"
          {...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="0"
          {...register("stock")}
          className="w-full rounded-lg border px-4 py-2"
          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}
      >
        Create Item
      </SubmitButton>
    </form>
  )
}
