"use client";

import { useMemo, useState } from "react";
import { Calculator } from "lucide-react";
import type { ApiProductUnit } from "@/lib/api/types";
import { SECTION_DIMENSIONS, SECTION_LABELS, piecesPerTonnes, sectionWeight, type SectionKind } from "@/lib/steelWeight";
import { inputClass } from "./fields";

/**
 * Standard-formula weight for the section being listed (B12): the seller picks
 * the section and its size and gets kg/m (or kg per sheet) and pieces per MT,
 * instead of typing a weight from memory. "Use" fills the Net Weight field.
 */
export default function WeightCalculator({
  units,
  onUse,
}: {
  units: ApiProductUnit[];
  onUse: (value: string, unitShortName: string) => void;
}) {
  const [kind, setKind] = useState<SectionKind>("round");
  const [dims, setDims] = useState<Record<string, string>>({});
  const [lengthM, setLengthM] = useState("12");

  const result = useMemo(
    () => sectionWeight(kind, Object.fromEntries(Object.entries(dims).map(([k, v]) => [k, Number(v)]))),
    [kind, dims]
  );
  // The master unit that matches the result: "Kg/M" for long products, "Kg" for a sheet.
  const perMetre = (u: ApiProductUnit) => /^kg\s*\/\s*m$/i.test(u.short_name ?? "") || /^kilogram\s*\/\s*met(er|re)$/i.test(u.name);
  const kgUnit =
    result?.unit === "kg/m"
      ? units.find(perMetre)
      : units.find((u) => !perMetre(u) && (/^kgs?$/i.test(u.short_name ?? "") || /^kilograms?$/i.test(u.name)));
  const perTonne = result && result.unit === "kg/m" ? piecesPerTonnes(result.value, Number(lengthM) || 0) : 0;

  return (
    <div className="rounded-lg border border-dashed border-gray-200 bg-gray-50 p-3">
      <p className="mb-2 flex items-center gap-1.5 text-xs font-semibold text-gray-700">
        <Calculator size={14} aria-hidden /> Weight calculator (standard steel formulas)
      </p>
      <div className="grid grid-cols-2 gap-2 md:grid-cols-4">
        <select
          aria-label="Section"
          value={kind}
          onChange={(e) => {
            setKind(e.target.value as SectionKind);
            setDims({});
          }}
          className={inputClass}
        >
          {(Object.keys(SECTION_LABELS) as SectionKind[]).map((k) => (
            <option key={k} value={k}>
              {SECTION_LABELS[k]}
            </option>
          ))}
        </select>
        {SECTION_DIMENSIONS[kind].map((d) => (
          <input
            key={d.key}
            aria-label={d.label}
            placeholder={d.label}
            inputMode="decimal"
            value={dims[d.key] ?? ""}
            onChange={(e) => setDims((p) => ({ ...p, [d.key]: e.target.value.replace(/[^\d.]/g, "") }))}
            className={inputClass}
          />
        ))}
        {kind !== "sheet" && (
          <input
            aria-label="Bar length (m)"
            placeholder="Length (m)"
            inputMode="decimal"
            value={lengthM}
            onChange={(e) => setLengthM(e.target.value.replace(/[^\d.]/g, ""))}
            className={inputClass}
          />
        )}
      </div>
      {result && (
        <div className="mt-2 flex flex-wrap items-center justify-between gap-2 text-xs text-gray-700">
          <span>
            <strong className="tabular-nums">{result.value}</strong> {result.unit}
            {perTonne > 0 && <> · ≈ {perTonne} pieces of {lengthM} m per MT</>}
          </span>
          {kgUnit && (
            <button
              type="button"
              onClick={() => onUse(String(result.value), kgUnit.short_name ?? kgUnit.name)}
              className="rounded-md bg-gray-900 px-2.5 py-1 font-semibold text-white hover:bg-[#CC1414]"
            >
              Use {result.value} {kgUnit.short_name ?? kgUnit.name}
            </button>
          )}
        </div>
      )}
    </div>
  );
}
