"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 { ItemStatus } from "@/generated/prisma/client"
import { createAssetAction } from "@/lib/actions/asset.actions"
import {
  CreateAssetFormType,
  createAssetSchema,
} from "@/lib/schemas/asset.schemas"
import { ItemWithoutStock, Recipient } from "@/lib/types"

interface NewAssetFormProps {
  items: ItemWithoutStock[]
  recipients: Recipient[]
}

export default function NewAssetForm({ items, recipients }: NewAssetFormProps) {
  const router = useRouter()

  const {
    register,
    handleSubmit,
    setError,
    formState: { errors, isSubmitting, isSubmitSuccessful },
    watch,
  } = useForm<CreateAssetFormType>({
    resolver: zodResolver(createAssetSchema),
    defaultValues: {
      status: "AVAILABLE",
    },
    shouldFocusError: true,
    mode: "onSubmit",
  })

  const status = watch("status")

  const onSubmit = async (formData: CreateAssetFormType) => {
    const response = await createAssetAction(formData)

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

    if (response?.success) {
      toast.success("Asset created successfully")
      router.push(`/inventory/assets`)
    }
  }
  return (
    <form className="flex flex-col gap-4" onSubmit={handleSubmit(onSubmit)}>
      <input type="hidden" {...register("id")} />
      <div>
        <label htmlFor="categoryId" className="mb-2 block text-lg">
          Item
        </label>
        <select
          id="itemId"
          {...register("itemId")}
          className="w-full rounded-lg border px-4 py-2"
        >
          <option value="">Select a item:</option>
          {items?.map((item) => (
            <option key={item.id} value={item.id}>
              {item.name}
            </option>
          ))}
        </select>
        {errors?.itemId && (
          <p className="text-error">{errors.itemId.message}</p>
        )}
      </div>
      <div>
        <label htmlFor="serialNumber" className="mb-2 block text-lg">
          Serial Number
        </label>
        <input
          type="text"
          id="serialNumber"
          placeholder="Serial number"
          {...register("serialNumber")}
          className="w-full rounded-lg border px-4 py-2"
        />
        {errors?.serialNumber && (
          <p className="text-error">{errors?.serialNumber?.message}</p>
        )}
      </div>
      <div>
        <label htmlFor="deliveryNote" className="mb-2 block text-lg">
          Delivery Note
        </label>
        <input
          type="text"
          id="deliveryNote"
          placeholder="Delivery note"
          {...register("deliveryNote")}
          className="w-full rounded-lg border px-4 py-2"
        />
        {errors?.deliveryNote && (
          <p className="text-error">{errors.deliveryNote.message}</p>
        )}
      </div>
      <div>
        <label htmlFor="status" className="mb-2 block text-lg">
          Status
        </label>
        <select
          id="status"
          {...register("status")}
          className="w-full rounded-lg border px-4 py-2"
        >
          <option value="">Select a status</option>
          {Object.values(ItemStatus).map((status) => (
            <option key={status} value={status}>
              {status}
            </option>
          ))}
        </select>
        {errors?.status && (
          <p className="text-error">{errors.status.message}</p>
        )}
      </div>
      {status === "ASSIGNED" && (
        <div>
          <label htmlFor="recipientId" className="mb-2 block text-lg">
            Recipient
          </label>
          <select
            id="recipientId"
            {...register("recipientId")}
            className="w-full rounded-lg border px-4 py-2"
          >
            <option value="">Select a Recipient</option>
            {recipients?.map((recipient) => (
              <option key={recipient.id} value={recipient.id}>
                {recipient.firstName} {recipient.lastName}
              </option>
            ))}
          </select>
          {errors?.recipientId && (
            <p className="text-error">{errors.recipientId.message}</p>
          )}
        </div>
      )}
      <SubmitButton
        isSubmitting={isSubmitting}
        isSubmitSuccessful={isSubmitSuccessful}
      >
        Create Asset
      </SubmitButton>
    </form>
  )
}
