import { useState } from "react";
import { useNavigate } from "react-router-dom";
import api from "../api/client";

const BOARD_TYPES = [
  { value: "vesper_pro",  name: "VESPER PRO",   codename: "vesper-pro",    desc: "Full-featured pro controller",  family: "vesper"  },
  { value: "vesper_plus", name: "VESPER PLUS",  codename: "vesper-plus",   desc: "Extended output controller",    family: "vesper"  },
  { value: "vesper",      name: "VESPER",       codename: "vesper-basic",  desc: "Standard bell controller",      family: "vesper"  },
  { value: "agnus",       name: "AGNUS",        codename: "agnus-basic",   desc: "Standard carillon module",      family: "agnus"   },
  { value: "agnus_mini",  name: "AGNUS MINI",   codename: "agnus-mini",    desc: "Compact carillon module",       family: "agnus"   },
  { value: "chronos_pro", name: "CHRONOS PRO",  codename: "chronos-pro",   desc: "Pro clock controller",          family: "chronos" },
  { value: "chronos",     name: "CHRONOS",      codename: "chronos-basic", desc: "Basic clock controller",        family: "chronos" },
];

const BOARD_FAMILY_COLORS = {
  vesper:  { selectedBg: "#0a1929", selectedBorder: "#3b82f6", selectedText: "#60a5fa", hoverBorder: "#3b82f6", glowColor: "rgba(59,130,246,0.35)", idleBorder: "#1d3a5c", idleText: "#7ca8d4" },
  agnus:   { selectedBg: "#1a1400", selectedBorder: "#f59e0b", selectedText: "#fbbf24", hoverBorder: "#f59e0b", glowColor: "rgba(245,158,11,0.35)",  idleBorder: "#4a3800", idleText: "#c79d3a" },
  chronos: { selectedBg: "#1a0808", selectedBorder: "#ef4444", selectedText: "#f87171", hoverBorder: "#ef4444", glowColor: "rgba(239,68,68,0.35)",   idleBorder: "#5c1a1a", idleText: "#d47a7a" },
};

function BoardTile({ bt, isSelected, onClick }) {
  const [hovered, setHovered] = useState(false);
  const pal = BOARD_FAMILY_COLORS[bt.family];
  const borderColor = isSelected ? pal.selectedBorder : hovered ? pal.hoverBorder : pal.idleBorder;
  const boxShadow = isSelected
    ? `0 0 0 1px ${pal.selectedBorder}, 0 0 14px 4px ${pal.glowColor}`
    : hovered ? `0 0 12px 3px ${pal.glowColor}` : "none";
  return (
    <button
      type="button"
      onClick={onClick}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      className="rounded-lg border p-3 text-left cursor-pointer"
      style={{
        backgroundColor: isSelected ? pal.selectedBg : "var(--bg-card)",
        borderColor, boxShadow,
        transition: "border-color 0.15s, box-shadow 0.15s, background-color 0.15s",
      }}
    >
      <p className="font-bold text-xs tracking-wide"
        style={{ color: isSelected ? pal.selectedText : hovered ? pal.idleText : "var(--text-heading)" }}>
        {bt.name}
      </p>
      <p className="text-xs mt-0.5 font-mono opacity-60" style={{ color: "var(--text-muted)" }}>{bt.codename}</p>
      <p className="text-xs mt-1 leading-snug" style={{ color: "var(--text-muted)", opacity: 0.75 }}>{bt.desc}</p>
    </button>
  );
}

export default function BatchCreator() {
  const navigate = useNavigate();
  const [boardType, setBoardType]       = useState(null);
  const [boardVersion, setBoardVersion] = useState("1.0");
  const [quantity, setQuantity]         = useState(1);
  const [saving, setSaving]             = useState(false);
  const [error, setError]               = useState("");
  const [result, setResult]             = useState(null);
  const [copied, setCopied]             = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!boardType) return;
    setError("");
    setResult(null);
    setSaving(true);
    try {
      const data = await api.post("/manufacturing/batch", {
        board_type: boardType,
        board_version: boardVersion.trim(),
        quantity: Number(quantity),
      });
      setResult(data);
    } catch (err) {
      setError(err.message);
    } finally {
      setSaving(false);
    }
  };

  const copyAll = () => {
    if (!result) return;
    navigator.clipboard.writeText(result.serial_numbers.join("\n"));
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  const inputStyle = {
    backgroundColor: "var(--bg-input)",
    borderColor: "var(--border-input)",
    color: "var(--text-primary)",
  };

  return (
    <div style={{ maxWidth: 640 }}>
      <h1 className="text-2xl font-bold mb-6" style={{ color: "var(--text-heading)" }}>
        New Batch
      </h1>

      {!result ? (
        <div
          className="ui-section-card"
        >
          <div className="ui-section-card__title-row">
            <h2 className="ui-section-card__title">Batch Parameters</h2>
          </div>

          {error && (
            <div className="text-sm rounded-md p-3 mb-4 border"
              style={{ backgroundColor: "var(--danger-bg)", borderColor: "var(--danger)", color: "var(--danger-text)" }}>
              {error}
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-5">
            {/* Board Type tiles — Vesper: 3 col, Agnus: 2 col, Chronos: 2 col */}
            <div>
              <label className="ui-form-label">
                Board Type
              </label>
              <div className="space-y-2">
                {/* Row 1: Vesper family */}
                <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8 }}>
                  {BOARD_TYPES.filter((b) => b.family === "vesper").map((bt) => (
                    <BoardTile key={bt.value} bt={bt} isSelected={boardType === bt.value} onClick={() => setBoardType(bt.value)} />
                  ))}
                </div>
                {/* Row 2: Agnus family — 2 cols left-aligned */}
                <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8 }}>
                  <div style={{ gridColumn: "1 / 3", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                    {BOARD_TYPES.filter((b) => b.family === "agnus").map((bt) => (
                      <BoardTile key={bt.value} bt={bt} isSelected={boardType === bt.value} onClick={() => setBoardType(bt.value)} />
                    ))}
                  </div>
                </div>
                {/* Row 3: Chronos family — 2 cols left-aligned */}
                <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8 }}>
                  <div style={{ gridColumn: "1 / 3", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                    {BOARD_TYPES.filter((b) => b.family === "chronos").map((bt) => (
                      <BoardTile key={bt.value} bt={bt} isSelected={boardType === bt.value} onClick={() => setBoardType(bt.value)} />
                    ))}
                  </div>
                </div>
              </div>
            </div>

            {/* Board Revision */}
            <div>
              <label className="ui-form-label">
                Board Revision
              </label>
              <div className="flex items-center gap-2">
                <span className="text-sm font-medium" style={{ color: "var(--text-muted)" }}>Rev</span>
                <input
                  type="text"
                  value={boardVersion}
                  onChange={(e) => setBoardVersion(e.target.value)}
                  placeholder="1.0"
                  required
                  className="px-3 py-2 rounded-md text-sm border w-32"
                  style={inputStyle}
                />
              </div>
              <p className="text-xs mt-1" style={{ color: "var(--text-muted)" }}>
                Use semantic versioning: 1.0, 1.1, 2.0, etc.
              </p>
            </div>

            {/* Quantity */}
            <div>
              <label className="ui-form-label">
                Quantity
              </label>
              <input
                type="number"
                value={quantity}
                onChange={(e) => setQuantity(e.target.value)}
                min={1}
                max={100}
                required
                className="w-full px-3 py-2 rounded-md text-sm border"
                style={inputStyle}
              />
            </div>

            <div className="flex gap-3 pt-2">
              <button
                type="submit"
                disabled={saving || !boardType}
                className="px-5 py-2 text-sm rounded-md font-medium hover:opacity-90 transition-opacity cursor-pointer disabled:opacity-40"
                style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
              >
                {saving ? "Generating…" : `Generate ${quantity} Serial Number${Number(quantity) > 1 ? "s" : ""}`}
              </button>
              <button
                type="button"
                onClick={() => navigate("/manufacturing")}
                className="px-4 py-2 text-sm rounded-md hover:opacity-80 transition-opacity cursor-pointer"
                style={{ backgroundColor: "var(--bg-card-hover)", color: "var(--text-secondary)" }}
              >
                Cancel
              </button>
            </div>
          </form>
        </div>
      ) : (
        <div
          className="ui-section-card"
        >
          <div className="flex items-start justify-between mb-4">
            <div>
              <h2 className="text-base font-semibold" style={{ color: "var(--text-heading)" }}>
                Batch Created
              </h2>
              <p className="text-sm mt-0.5" style={{ color: "var(--text-muted)" }}>
                {result.batch_id} · {result.serial_numbers.length} device{result.serial_numbers.length !== 1 ? "s" : ""}
              </p>
            </div>
            <span
              className="px-2 py-0.5 text-xs rounded-full font-medium"
              style={{ backgroundColor: "var(--badge-blue-bg)", color: "var(--badge-blue-text)" }}
            >
              {BOARD_TYPES.find((b) => b.value === result.board_type)?.name || result.board_type} Rev {result.board_version}
            </span>
          </div>

          <div
            className="rounded-md border p-3 mb-4 font-mono text-xs overflow-y-auto"
            style={{
              backgroundColor: "var(--bg-primary)",
              borderColor: "var(--border-secondary)",
              color: "var(--text-primary)",
              maxHeight: "280px",
            }}
          >
            {result.serial_numbers.map((sn) => (
              <div key={sn} className="py-0.5">{sn}</div>
            ))}
          </div>

          <div className="flex gap-3">
            <button
              onClick={copyAll}
              className="px-4 py-2 text-sm rounded-md hover:opacity-90 transition-opacity cursor-pointer"
              style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
            >
              {copied ? "Copied!" : "Copy All"}
            </button>
            <button
              onClick={() => navigate("/manufacturing")}
              className="px-4 py-2 text-sm rounded-md hover:opacity-80 transition-opacity cursor-pointer"
              style={{ backgroundColor: "var(--bg-card-hover)", color: "var(--text-secondary)" }}
            >
              View Inventory
            </button>
            <button
              onClick={() => { setResult(null); setQuantity(1); setBoardType(null); }}
              className="px-4 py-2 text-sm rounded-md hover:opacity-80 transition-opacity cursor-pointer"
              style={{ backgroundColor: "var(--bg-card-hover)", color: "var(--text-secondary)" }}
            >
              New Batch
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
