"use client";

import { useEffect, useMemo } from "react";
import InputItem from "@/app/Components/FormItems";
import { handleChange } from "@/app/utils/form";
import { apiGetLimit } from "@/app/utils/variables";
import { parseArrayField } from "@/app/utils/parseArrayField";

import { useQuery } from "@tanstack/react-query";
import InventorySuppliers from "../InventorySuppliers";
import { inventoryTypes } from "@/app/utils/inventoryTypes";
import { getStatusById } from "@/app/utils/status";
import { getActiveItems } from "@/app/utils/getActiveItems";
import CompositeProducts from "../CompositeProducts";

/* ================= FETCHER ================= */
const fetcher = (url) =>
  fetch(url, {}).then((res) => {
    if (!res.ok) throw new Error("Unauthorized or error fetching data");
    return res.json();
  });

export default function InventoryForm({
  form,
  setForm,
  brandSettings,
  allSuppliers = [],
  isEditMode,
}) {
  const { data: getUnits } = useQuery({
    queryKey: ["unit", apiGetLimit],
    queryFn: () => fetcher(`/api/unit?limit=${apiGetLimit}`),
  });

  const activeUnits = getActiveItems(getUnits?.unit);

  /* =====================================================
     NORMALIZE STATUS
  ===================================================== */
  const normalizedStatus = useMemo(() => {
    return parseArrayField(form?.status);
  }, [form?.status]);

  /* =====================================================
     DEFAULT STATUS (ADD MODE)
  ===================================================== */
  useEffect(() => {
    if (isEditMode) return;

    if (!normalizedStatus.length) {
      const defaultStatus = getStatusById(12);
      if (!defaultStatus) return;

      setForm((prev) => ({
        ...prev,
        status: [
          {
            id: defaultStatus.id,
            key: defaultStatus.key,
            label: defaultStatus.label,
          },
        ],
      }));
    }
  }, [isEditMode, normalizedStatus, setForm]);

  /* =====================================================
     SERIALIZATION SYNC
  ===================================================== */
  useEffect(() => {
    if (form?.serialization !== undefined) {
      setForm((prev) => ({
        ...prev,
        serializationCheck: prev.serialization === "1",
      }));
    }
  }, [form?.serialization]);

  /* =====================================================
     RENDER
  ===================================================== */
  return (
    <div className="container !my-5 grid sm:gap-8 gap-6">

      {/* ================= INVENTORY INFO ================= */}
      <div className="grid gap-6">

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 w-full">

          <InputItem
            type="select"
            label="Inventory Type"
            name="inventory_type"
            value={parseArrayField(form.inventory_type)}
            onChange={(e) => handleChange(e, setForm)}
            options={inventoryTypes}
            arrayType={true}
          />

          <InputItem
            type="text"
            label="Inventory Name"
            name="inventory_name"
            value={form.inventory_name}
            onChange={(e) => handleChange(e, setForm)}
          />

          <InputItem
            type="textspecial"
            label="HSL or SKU"
            name="sku"
            value={form?.sku}
            onChange={(e) => handleChange(e, setForm)}
          />

          <InputItem
            type="select"
            label="Unit"
            name="unit"
            value={form?.unit}
            onChange={(e) => handleChange(e, setForm)}
            options={
              activeUnits?.map((unit) => ({
                label: unit.unit_name,
                value: unit.unit_name,
              })) || []
            }
          />
        </div>

        <InputItem
          type="editor"
          label="Description"
          name="description"
          value={form.description}
          onChange={(e) => handleChange(e, setForm)}
        />

        <InputItem
          type="checkbox"
          label="Serialization Required"
          checked={form.serialization === `1`}
          onChange={(e) => {
            const checked = e.target.checked;

            setForm((prev) => ({
              ...prev,
              serializationCheck: checked,
              serialization: checked ? `1` : `0`,
            }));
          }}
          className="no-width"
        />
      </div>

      {/* ================= COMPOSITE PRODUCT ================= */}
      {form.inventory_type?.[0]?.id === 3 && (
        <div className="grid gap-6">
          <CompositeProducts form={form} setForm={setForm} />
        </div>
      )}

      {/* ================= SERVICE CHARGE ================= */}
      {form.inventory_type?.[0]?.id === 3 && (
        <div className="grid gap-6">
          <InputItem
            type="number"
            placeholder="Service Charge"
            name="service_charge"
            value={form.service_charge}
            onChange={(e) => handleChange(e, setForm)}
          />
        </div>
      )}

      {/* ================= PRICING INFO ================= */}
      <div className="grid gap-6 mt-5">

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">

          {/* BUYING PRICE */}
          <div className="grid gap-5">
            <h3 className="font-semibold text-sm text-gray-600 uppercase tracking-wide">
              Buying Price
            </h3>

            {brandSettings?.currencies?.map((currency) => (
              <InputItem
                key={currency}
                classNames="no-arrow"
                type="number"
                label={`Price (${currency})`}
                value={form?.buying_price?.[0]?.[currency] || ""}
                onChange={(e) => {
                  const value = e.target.value;

                  setForm((prev) => ({
                    ...prev,
                    buying_price: [
                      {
                        ...(prev.buying_price?.[0] || {}),
                        [currency]: value,
                      },
                    ],
                  }));
                }}
              />
            ))}
          </div>

          {/* SELLING PRICE */}
          <div className="grid gap-5">
            <h3 className="font-semibold text-sm text-gray-600 uppercase tracking-wide">
              Selling Price
            </h3>

            {brandSettings?.currencies?.map((currency) => (
              <InputItem
                key={currency}
                classNames="no-arrow"
                type="number"
                label={`Price (${currency})`}
                value={form?.inventory_price?.[0]?.[currency] || ""}
                onChange={(e) => {
                  const value = e.target.value;

                  setForm((prev) => ({
                    ...prev,
                    inventory_price: [
                      {
                        ...(prev.inventory_price?.[0] || {}),
                        [currency]: value,
                      },
                    ],
                  }));
                }}
              />
            ))}
          </div>

        </div>
      </div>

      {/* ================= SUPPLIERS ================= */}
      <div className="grid gap-6 mt-5">

            <h3 className="font-semibold text-sm text-gray-600 uppercase tracking-wide">
              Suppliers
            </h3>

        <InventorySuppliers
          form={form}
          setForm={setForm}
          allSuppliers={allSuppliers}
        />
      </div>

      {/* ================= STATUS ================= */}
      <div className="grid gap-4 mt-5">
          <h3 className="font-semibold text-sm text-gray-600 uppercase tracking-wide">
              Status
            </h3>

        <InputItem
          type="select"
          label="Status"
          name="status"
          value={normalizedStatus}
          onChange={(e) => handleChange(e, setForm)}
          options={[getStatusById(12), getStatusById(13)]}
          arrayType={true}
        />
      </div>

    </div>
  );
}
