import { Plus, Trash2 } from "lucide-react";
import { useFieldArray, type UseFormReturn } from "react-hook-form";
import type { ApiProductUnit } from "@/lib/api/types";
import { type ProductFormValues } from "./product.schema";
import { ErrorText, SectionCard, UnitSelect, inputClass } from "./fields";

type Props = {
  form: UseFormReturn<ProductFormValues>;
  units: ApiProductUnit[];
};

export default function Step5Variants({ form, units }: Props) {
  const {
    register,
    control,
    watch,
    formState: { errors },
  } = form;
  const { fields, append, remove } = useFieldArray({ control, name: "variants" });
  const rows = watch("variants");

  const rowErrors = errors.variants as
    | Array<{ size?: { message?: string }; unit?: { message?: string }; charge?: { message?: string } }>
    | undefined;
  const rootError =
    (errors.variants as { message?: string } | undefined)?.message ??
    (errors.variants as { root?: { message?: string } } | undefined)?.root?.message;

  /*
    Catalog variations are the parent product's, so this step only ticks and
    prices them — the gauges themselves are not one seller's to invent, and the
    same rows back the "Update Variation" and "Update Stock" dialogs on the
    product page. A product the seller created has none, so those rows are
    theirs to add and remove.
  */
  const fromCatalog = (rows ?? []).some((row) => (row.id ?? "").trim());

  if (fromCatalog) {
    return (
      <SectionCard
        title="Size Variants & Pricing"
        subtitle="Tick the variations you sell, then set the gauge difference and stock on each."
      >
        <div className="overflow-x-auto">
          <table className="w-full min-w-[620px] border-collapse text-sm">
            <thead>
              <tr className="border-b border-gray-200 text-left text-xs font-medium text-gray-600">
                <th className="w-16 pb-2 pr-3">Sell</th>
                <th className="pb-2 pr-3">Requirements</th>
                <th className="pb-2 pr-3">Gauge Difference (₹)</th>
                <th className="pb-2">Stock Availability</th>
              </tr>
            </thead>
            <tbody>
              {fields.map((field, index) => {
                const selected = rows?.[index]?.selected ?? false;

                return (
                  <tr key={field.id} className="border-b border-gray-100 align-top">
                    <td className="py-2 pr-3">
                      <input
                        type="checkbox"
                        {...register(`variants.${index}.selected`)}
                        className="mt-2 h-4 w-4 accent-[#CC1414]"
                        aria-label={`Sell ${rows?.[index]?.label || `variation ${index + 1}`}`}
                      />
                    </td>
                    <td className="bg-gray-50 py-2 pr-3">
                      <span className="inline-block py-2 font-medium text-gray-900">
                        {rows?.[index]?.label || "—"}
                      </span>
                    </td>
                    <td className="py-2 pr-3">
                      {selected ? (
                        <>
                          <input
                            {...register(`variants.${index}.charge`)}
                            className={inputClass}
                            placeholder="Enter price"
                            inputMode="decimal"
                          />
                          <ErrorText message={rowErrors?.[index]?.charge?.message} />
                        </>
                      ) : (
                        <span className="inline-block py-2 text-xs text-gray-400">Not Applicable</span>
                      )}
                    </td>
                    <td className="py-2">
                      {selected ? (
                        <input
                          {...register(`variants.${index}.stock`)}
                          className={inputClass}
                          placeholder="Enter stock"
                          inputMode="numeric"
                        />
                      ) : (
                        <span className="inline-block py-2 text-xs text-gray-400">—</span>
                      )}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        <ErrorText message={rootError} />

        <p className="mt-3 text-xs text-gray-500">
          Variations come from the parent product, so buyers comparing sellers compare the same
          gauges. Ask an admin to add one that is missing.
        </p>
      </SectionCard>
    );
  }

  return (
    <SectionCard title="Size Variants & Pricing">
      <div className="overflow-x-auto">
        <table className="w-full min-w-[720px] border-collapse text-sm">
          <thead>
            <tr className="text-left text-xs font-medium text-gray-600">
              <th className="pb-2 pr-3">Size / Variant *</th>
              <th className="pb-2 pr-3">Unit *</th>
              <th className="pb-2 pr-3">Variant Charge (₹)</th>
              <th className="pb-2 pr-3">Stock Availability</th>
              <th className="pb-2 text-right">Action</th>
            </tr>
          </thead>
          <tbody>
            {fields.map((field, index) => (
              <tr key={field.id} className="align-top">
                <td className="py-1.5 pr-3">
                  <input
                    {...register(`variants.${index}.size`)}
                    className={inputClass}
                    placeholder="e.g. 10, 20"
                  />
                  <ErrorText message={rowErrors?.[index]?.size?.message} />
                </td>
                <td className="py-1.5 pr-3">
                  <UnitSelect
                    units={units}
                    current={rows?.[index]?.unit}
                    {...register(`variants.${index}.unit`)}
                  />
                  <ErrorText message={rowErrors?.[index]?.unit?.message} />
                </td>
                <td className="py-1.5 pr-3">
                  <input
                    {...register(`variants.${index}.charge`)}
                    className={inputClass}
                    placeholder="Enter charge"
                    inputMode="decimal"
                  />
                </td>
                <td className="py-1.5 pr-3">
                  <input
                    {...register(`variants.${index}.stock`)}
                    className={inputClass}
                    placeholder="Enter stock"
                    inputMode="numeric"
                  />
                </td>
                <td className="py-1.5 text-right">
                  <button
                    type="button"
                    onClick={() => remove(index)}
                    disabled={fields.length === 1}
                    className="rounded-md p-2 text-[#CC1414] hover:bg-rose-50 disabled:cursor-not-allowed disabled:opacity-40"
                    aria-label="Remove variant"
                  >
                    <Trash2 className="h-4 w-4" />
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <ErrorText message={rootError} />

      <button
        type="button"
        onClick={() =>
          append({ id: "", label: "", size: "", unit: "", charge: "", stock: "", selected: true })
        }
        className="mt-3 inline-flex items-center gap-1.5 rounded-lg border border-[#CC1414] px-3 py-1.5 text-sm font-medium text-[#CC1414] hover:bg-rose-50"
      >
        <Plus className="h-4 w-4" /> Add Variant
      </button>
    </SectionCard>
  );
}
