"use client";

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

const OWN_FIELDS = ["qualities"];

/**
 * Which grades from the parent catalog this seller offers, and the price
 * difference charged on each.
 *
 * The grade list is the catalog's, not a free-text field: a buyer comparing
 * sellers on "Fe 500" has to be comparing the same thing. Unticking a grade
 * simply drops it from the seller's offer.
 */
export default function QualityForm({
  id,
  qualities,
  onDone,
}: {
  id: number;
  qualities: ApiProductQualityRow[];
  onDone: () => void;
}) {
  const [state, formAction] = useActionState(updateProductQuality, INITIAL_UPDATE_STATE);
  const [rows, setRows] = useState(qualities);

  useUpdateResult(state, onDone);

  if (qualities.length === 0) {
    return (
      <EmptyPanel>
        The catalog does not list any quality grades for this product, so there is nothing to price
        here.
      </EmptyPanel>
    );
  }

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

  const setRow = (index: number, patch: Partial<ApiProductQualityRow>) =>
    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="qualities" value={JSON.stringify(payload)} />

      <p className="text-sm text-emerald-700">
        Select the qualities 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-[520px] 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">Quality</th>
              <th className="pb-2">Price Difference (₹)</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((row, index) => (
              <tr key={row.name} 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.name}`}
                  />
                </td>
                <td className="bg-gray-50 py-2 pr-3">
                  <span className="font-medium text-gray-900">{row.name}</span>
                  <span className="ml-2 text-xs text-gray-500">
                    catalog ₹{row.catalog_price || "0"}
                  </span>
                </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[`qualities.${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 quality" />
      </div>
    </form>
  );
}
