"use client"

import { zodResolver } from "@hookform/resolvers/zod"
import { useRouter } from "next/navigation"
import { useMemo } from "react"
import { useForm } from "react-hook-form"
import { toast } from "sonner"

import { SubmitButton } from "@/components/forms/submitButton"
import { createAssignment } from "@/lib/actions/assignament.actions"
import {
  CreateAssignmentFormType,
  createAssignmentSchema,
} from "@/lib/schemas/assignment.schemas"
import { Asset, Item, Recipient } from "@/lib/types"

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

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

  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting, isSubmitSuccessful },
    watch,
  } = useForm<CreateAssignmentFormType>({
    resolver: zodResolver(createAssignmentSchema),
    mode: "onSubmit",
  })

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

  const itemAssets = useMemo(() => {
    return assets.filter((asset) => asset.itemId === itemId)
  }, [assets, itemId])

  const onSubmit = async (formData: CreateAssignmentFormType) => {
    const response = await createAssignment(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)}>
      <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" : ""
          }`}
        >
          <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>
      <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" : ""
          }`}
        >
          <option value="">Select an 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>
      {itemId && itemAssets.length !== 0 && (
        <div className="flex flex-col gap-2">
          <label htmlFor="assetId" className="mb-2 block text-lg">
            Asset
          </label>
          <select
            id="assetId"
            {...register("assetId")}
            disabled={!itemId || itemAssets.length === 0}
            className={`w-full rounded-lg border px-4 py-2 ${
              !itemId || itemAssets.length === 0
                ? "border-gray-300 bg-gray-100"
                : ""
            }`}
          >
            <option value="">Select an asset</option>
            {itemId
              ? itemAssets.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 || itemAssets.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 || itemAssets.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 || (itemAssets.length > 0 && !assetId)}
      >
        Create Assignment
      </SubmitButton>
    </form>
  )
}
