"use client";

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

const OWN_FIELDS = ["stock"];

/**
 * Stock held against each variation.
 *
 * Only the variations the seller actually offers are editable — the rest are
 * shown as "Not Selected" so the table still reads as the full catalog list.
 * Whether a row is offered is decided by the server, not by this form, which is
 * why unselected rows carry no input at all.
 */
export default function StockForm({
  id,
  variants,
  onDone,
}: {
  id: number;
  variants: ApiProductVariantRow[];
  onDone: () => void;
}) {
  const [state, formAction] = useActionState(updateProductStock, 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 no stock to track here.
      </EmptyPanel>
    );
  }

  if (!variants.some((row) => row.is_selected)) {
    return (
      <EmptyPanel>
        Select the variations you sell under <strong>Update Variation</strong> first — stock is held
        per variation.
      </EmptyPanel>
    );
  }

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

  const setStock = (index: number, value: string) =>
    setRows((current) => current.map((row, i) => (i === index ? { ...row, stock: value } : row)));

  /** The server errors are keyed by position within the submitted rows only. */
  const payloadIndex = (rowIndex: number) =>
    rows.slice(0, rowIndex).filter((row) => row.is_selected).length;

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

      <p className="text-sm text-emerald-700">
        You can change the stock of the variations you sell.
      </p>

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

      <div className="overflow-x-auto">
        <table className="w-full min-w-[520px] border-collapse text-sm">
          <thead>
            <tr className="border-b border-gray-200 text-left text-xs font-medium text-gray-600">
              <th className="pb-2 pr-3">Action</th>
              <th className="pb-2 pr-3">Requirements</th>
              <th className="pb-2">Stock</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">
                  {row.is_selected ? (
                    <span className="font-semibold text-emerald-600">Selected</span>
                  ) : (
                    <span className="font-semibold text-gray-400">Not Selected</span>
                  )}
                </td>
                <td className="bg-gray-50 py-2 pr-3 text-gray-900">
                  {row.attributes.length > 0
                    ? row.attributes.map((a) => `${a.name} - ${a.value}`).join(", ")
                    : row.label || "—"}
                </td>
                <td className="py-2">
                  {row.is_selected ? (
                    <>
                      <input
                        value={row.stock}
                        onChange={(e) => setStock(index, e.target.value)}
                        className={inputClass}
                        placeholder="Enter stock"
                        inputMode="numeric"
                      />
                      <FieldError messages={state.errors[`stock.${payloadIndex(index)}.stock`]} />
                    </>
                  ) : (
                    <span className="text-xs text-gray-400">Not Applicable</span>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

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