"use client";

import { useActionState, useState } from "react";
import type { ApiProductVariantRow } from "@/lib/api/types";
import { updateProductVariants } from "../actions";
import {
  EmptyPanel,
  FieldError,
  FormErrorSummary,
  INITIAL_UPDATE_STATE,
  SubmitButton,
  inputClass,
  useUpdateResult,
} from "./shared";

const OWN_FIELDS = ["variants"];

/**
 * Which of the catalog's variations this seller offers, and the gauge
 * difference charged on each over the product's base price.
 *
 * The rows are fixed — they come from the catalog the product was created from —
 * so this table only ticks and prices them; it never adds or removes rows. The
 * price input appears only for a ticked row, which is what makes "selected but
 * unpriced" impossible to submit by accident.
 */
export default function VariationForm({
  id,
  variants,
  onDone,
}: {
  id: number;
  variants: ApiProductVariantRow[];
  onDone: () => void;
}) {
  const [state, formAction] = useActionState(updateProductVariants, INITIAL_UPDATE_STATE);
  const [rows, setRows] = useState(variants);

  useUpdateResult(state, onDone);

  if (variants.length === 0) {
    return (
      <EmptyPanel>
        This product has no catalog variations, so there is nothing to price here.
      </EmptyPanel>
    );
  }

  const payload = rows.map((row) => ({
    id: row.id,
    price: row.price,
    is_selected: row.is_selected,
  }));

  const setRow = (index: number, patch: Partial<ApiProductVariantRow>) =>
    setRows((current) => current.map((row, i) => (i === index ? { ...row, ...patch } : row)));

  return (
    <form action={formAction} className="space-y-4">
      <input type="hidden" name="id" value={id} />
      <input type="hidden" name="variants" value={JSON.stringify(payload)} />

      <p className="text-sm text-emerald-700">
        Select the variations you sell and set the price difference for each.
      </p>

      <FormErrorSummary state={state} own={OWN_FIELDS} />

      <div className="overflow-x-auto">
        <table className="w-full min-w-[480px] 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">Action</th>
              <th className="pb-2 pr-3">Requirements</th>
              <th className="pb-2">Gauge Difference (₹)</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((row, index) => (
              <tr key={row.id} className="border-b border-gray-100 align-top">
                <td className="py-2 pr-3">
                  <input
                    type="checkbox"
                    checked={row.is_selected}
                    onChange={(e) => setRow(index, { is_selected: e.target.checked })}
                    className="h-4 w-4 accent-[#CC1414]"
                    aria-label={`Sell ${row.label}`}
                  />
                </td>
                <td className="bg-gray-50 py-2 pr-3 font-medium text-gray-900">
                  {row.label || "—"}
                </td>
                <td className="py-2">
                  {row.is_selected ? (
                    <>
                      <input
                        value={row.price}
                        onChange={(e) => setRow(index, { price: e.target.value })}
                        className={inputClass}
                        placeholder="Enter price"
                        inputMode="decimal"
                      />
                      <FieldError messages={state.errors[`variants.${index}.price`]} />
                    </>
                  ) : (
                    <span className="text-xs text-gray-400">Not Applicable</span>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="flex justify-end">
        <SubmitButton label="Update variation" />
      </div>
    </form>
  );
}
