"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 { updateAssignment } from "@/lib/actions/assignament.actions"
import {
  UpdateAssignmentFormType,
  updateAssignmentSchema,
} from "@/lib/schemas/assignment.schemas"
import { Asset, Item, Recipient } from "@/lib/types"

interface Props {
  recipients: Recipient[]
  items: Item[]
  assets: Asset[]
  initialData: UpdateAssignmentFormType
}

export default function EditAssignmentForm({
  recipients,
  items,
  assets,
  initialData,
}: Props) {
  const router = useRouter()

  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting, isSubmitSuccessful },
    watch,
  } = useForm<UpdateAssignmentFormType>({
    resolver: zodResolver(updateAssignmentSchema),
    defaultValues: {
      ...initialData,
      id: initialData.id || undefined,
    },
    mode: "onSubmit",
  })

  const itemId = watch("itemId")
  const assetId = watch("assetId")

  const onSubmit = async (formData: UpdateAssignmentFormType) => {
    const response = await updateAssignment(formData)

    if (response?.errors) {
      Object.values(response.errors as Record<string, string[]>).forEach(
        (messages) => {
          messages.forEach((msg) => toast.error(msg))
        },
      )
      return
    }
    if (response?.success) {
      toast.success(response.message)
      router.push("/assignments")
    }
  }

  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="recipientId" className="mb-2 block text-lg">
          Recipient
        </label>
        <select
          id="recipientId"
          {...register("recipientId")}
          className={`w-full rounded-lg border px-4 py-2 ${
            errors.recipientId ? "border-error" : ""
          }`}
        >
          {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>
      <div className="flex flex-col gap-2">
        <label htmlFor="itemId" className="mb-2 block text-lg">
          Item
        </label>
        <select
          id="itemId"
          {...register("itemId")}
          className={`w-full rounded-lg border px-4 py-2 ${
            errors.itemId ? "border-error" : ""
          }`}
        >
          {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 className="flex flex-col gap-2">
        <label htmlFor="assetId" className="mb-2 block text-lg">
          Asset
        </label>
        <select
          id="assetId"
          {...register("assetId")}
          className={`w-full rounded-lg border px-4 py-2 ${
            errors.assetId ? "border-error" : ""
          }`}
        >
          <option value="">Select an asset</option>
          {itemId
            ? assets.map((asset) => (
                <option key={asset.id} value={asset.id}>
                  {asset.serialNumber}
                </option>
              ))
            : null}
        </select>
        {errors.assetId && (
          <p className="text-error">{errors.assetId.message}</p>
        )}
      </div>
      <div className="flex flex-col gap-2">
        <label htmlFor="quantity" className="mb-2 block text-lg">
          Quantity
        </label>
        <input
          type="number"
          id="quantity"
          disabled={!itemId || assets.length > 0}
          min={1}
          max={itemId ? items.find((item) => item.id === itemId)?.stock : 0}
          defaultValue={1}
          {...register("quantity")}
          className={`w-full rounded-lg border px-4 py-2 ${
            !itemId || assets.length > 0 ? "border-gray-300 bg-gray-100" : ""
          }`}
        />
        {errors.quantity && (
          <p className="text-error">{errors.quantity.message}</p>
        )}
      </div>
      <SubmitButton
        isSubmitting={isSubmitting}
        isSubmitSuccessful={isSubmitSuccessful}
        disabled={!itemId || (assets.length > 0 && !assetId)}
      >
        Update Assignment
      </SubmitButton>
    </form>
  )
}
