"use client";

/**
 * src/components/artifacts/DieMaterialAdjust.tsx
 *
 * 三步流程：
 *   Step 1 (form)     → 选择材料 / 外径 / 壁厚
 *   Step 2 (adjusting) → 模拟等待 2s
 *   Step 3 (done)     → 显示各模具调节后的 X / Y 位置
 */

import { CheckCircle2, Loader2, Settings } from "lucide-react";
import { useState } from "react";
import type {
  ArtifactAction,
  ArtifactComponentProps,
  DieMaterialAdjustProps,
  InteractionArtifact,
} from "@/lib/artifacts/types";
import { generateDiePositions } from "@/lib/artifacts/die-mock-data";

// ── 材料选项 ──────────────────────────────────────────────────────────────────
const MATERIALS = [
  "304 不锈钢",
  "316L 不锈钢",
  "201 不锈钢",
  "Q235 碳钢",
  "Q345 低合金钢",
];

// ── 表单界面 ──────────────────────────────────────────────────────────────────
function FormStep({
  onConfirm,
}: {
  onConfirm: (material: string, od: number, thickness: number) => void;
}) {
  const [material, setMaterial] = useState(MATERIALS[0]);
  const [od, setOd] = useState(20);
  const [thickness, setThickness] = useState(2);

  return (
    <div className="p-6">
      <p className="mb-5 text-sm text-zinc-500">
        选择材料规格后，系统将根据成型工艺数据自动计算各模具伺服位置并写入。
      </p>
      <div className="space-y-4">
        <div>
          <label className="mb-1 block text-xs font-semibold text-zinc-600">材料</label>
          <select
            value={material}
            onChange={(e) => setMaterial(e.target.value)}
            className="w-full rounded-lg border border-zinc-200 bg-white px-3 py-2 text-sm text-zinc-900 outline-none focus:border-zinc-950"
          >
            {MATERIALS.map((m) => (
              <option key={m} value={m}>{m}</option>
            ))}
          </select>
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="mb-1 block text-xs font-semibold text-zinc-600">外径 (mm)</label>
            <input
              type="number"
              value={od}
              min={6}
              max={219}
              step={0.5}
              onChange={(e) => setOd(Number(e.target.value))}
              className="w-full rounded-lg border border-zinc-200 bg-white px-3 py-2 text-sm text-zinc-900 outline-none focus:border-zinc-950"
            />
          </div>
          <div>
            <label className="mb-1 block text-xs font-semibold text-zinc-600">壁厚 (mm)</label>
            <input
              type="number"
              value={thickness}
              min={0.5}
              max={20}
              step={0.1}
              onChange={(e) => setThickness(Number(e.target.value))}
              className="w-full rounded-lg border border-zinc-200 bg-white px-3 py-2 text-sm text-zinc-900 outline-none focus:border-zinc-950"
            />
          </div>
        </div>

        {/* 预览标签 */}
        <div className="rounded-lg bg-zinc-50 px-4 py-3 text-sm text-zinc-600">
          <span className="font-medium">{material}</span>
          &ensp;圆管&ensp;Φ<span className="font-medium">{od}</span>
          &ensp;×&ensp;壁厚 <span className="font-medium">{thickness}</span> mm
        </div>
      </div>

      <div className="mt-6 flex gap-3">
        <button
          type="button"
          onClick={() => onConfirm(material, od, thickness)}
          className="inline-flex items-center gap-2 rounded-lg bg-zinc-950 px-5 py-2.5 text-sm font-semibold text-white hover:bg-zinc-800 transition-colors"
        >
          <Settings className="h-4 w-4" />
          确认并调节模具
        </button>
      </div>
    </div>
  );
}

// ── 等待界面 ──────────────────────────────────────────────────────────────────
function AdjustingStep({ material, od, thickness }: { material: string; od: number; thickness: number }) {
  return (
    <div className="flex flex-col items-center justify-center py-16 text-center">
      <Loader2 className="mb-4 h-10 w-10 animate-spin text-zinc-400" />
      <p className="text-base font-semibold text-zinc-700">正在调节模具伺服位置…</p>
      <p className="mt-1 text-sm text-zinc-400">
        {material} · Φ{od} × {thickness}mm
      </p>
    </div>
  );
}

// ── 结果界面（仅显示编号 + X + Y）─────────────────────────────────────────────
function DoneStep({
  material,
  od,
  thickness,
  dies,
}: {
  material: string;
  od: number;
  thickness: number;
  dies: ReturnType<typeof generateDiePositions>;
}) {
  return (
    <div>
      {/* 成功提示 */}
      <div className="flex items-center gap-3 border-b border-zinc-100 bg-emerald-50 px-5 py-3">
        <CheckCircle2 className="h-5 w-5 text-emerald-600" />
        <div>
          <p className="text-sm font-semibold text-emerald-800">调节完成</p>
          <p className="text-xs text-emerald-600">
            {material} · Φ{od} × {thickness}mm · {dies.length} 个模具
          </p>
        </div>
      </div>

      {/* 位置表 */}
      <div className="overflow-x-auto">
        <table className="w-full text-left">
          <thead>
            <tr className="border-b border-zinc-100 bg-zinc-50">
              <th className="px-4 py-2.5 text-xs font-semibold text-zinc-500">模具</th>
              <th className="px-4 py-2.5 text-xs font-semibold text-zinc-500">X 位置 (mm)</th>
              <th className="px-4 py-2.5 text-xs font-semibold text-zinc-500">Y 位置 (mm)</th>
            </tr>
          </thead>
          <tbody>
            {dies.map((die) => (
              <tr key={die.dieIndex} className="border-b border-zinc-50 hover:bg-zinc-50/60">
                <td className="px-4 py-2 text-sm font-medium text-zinc-700">{die.label}</td>
                <td className="px-4 py-2 font-mono text-sm text-zinc-900">{die.xPos.toFixed(3)}</td>
                <td className="px-4 py-2 font-mono text-sm text-zinc-900">{die.yPos.toFixed(3)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ── 主组件 ────────────────────────────────────────────────────────────────────
export function DieMaterialAdjust({
  artifact,
}: ArtifactComponentProps<Extract<InteractionArtifact, { type: "die_material_adjust" }>>) {
  type Step = "form" | "adjusting" | "done";
  const [step, setStep] = useState<Step>("form");
  const [result, setResult] = useState<{
    material: string;
    od: number;
    thickness: number;
    dies: ReturnType<typeof generateDiePositions>;
  } | null>(null);

  function handleConfirm(material: string, od: number, thickness: number) {
    setStep("adjusting");
    setTimeout(() => {
      const dies = generateDiePositions({ outerDiameter: od, thickness, totalDies: 15 });
      setResult({ material, od, thickness, dies });
      setStep("done");
    }, 2000);
  }

  return (
    <section className="w-full max-w-2xl">
      {/* Header */}
      <div className="mb-4 flex items-center gap-3">
        <div className="flex h-11 w-11 items-center justify-center rounded-lg bg-zinc-950 text-white">
          <Settings className="h-5 w-5" />
        </div>
        <div>
          <p className="text-xs font-semibold uppercase tracking-[0.18em] text-zinc-500">模具伺服调节</p>
          <h2 className="text-2xl font-semibold text-zinc-950">{artifact.title}</h2>
        </div>
        {step === "done" && (
          <span className="ml-auto rounded-full bg-emerald-50 px-3 py-1 text-sm font-medium text-emerald-700">
            已完成
          </span>
        )}
      </div>

      <div className="rounded-lg border border-zinc-200 bg-white shadow-sm">
        {step === "form" && <FormStep onConfirm={handleConfirm} />}
        {step === "adjusting" && result === null && (
          <AdjustingStep material="正在计算…" od={0} thickness={0} />
        )}
        {step === "adjusting" && (
          <AdjustingStep
            material="正在计算…"
            od={0}
            thickness={0}
          />
        )}
        {step === "done" && result && (
          <DoneStep
            material={result.material}
            od={result.od}
            thickness={result.thickness}
            dies={result.dies}
          />
        )}
      </div>
    </section>
  );
}
