"use client";

/**
 * src/components/artifacts/DieStatusOverview.tsx
 *
 * 模具位置总览
 * - 截面图：描边线条风格（标量图），展示弯管成型渐进过程
 *     Die 1  → 平直钢带 + 两段浅下凹
 *     Die 2  → 平中间 + 两边微翘
 *     Die 3  → 整体圆弧（开口大）
 *     Die 4-15 → 弧度渐深，开口逐步收小
 *     Die 16 → 闭合圆
 * - 只显示模具编号 + X 位置 + Y 位置
 */

import { Layers } from "lucide-react";
import { useState } from "react";
import type {
  ArtifactComponentProps,
  DiePositionData,
  DieStatusOverviewProps,
  InteractionArtifact,
} from "@/lib/artifacts/types";

// ── 成型截面路径计算 ───────────────────────────────────────────────────────────

function getFormingPath(
  dieIndex: number,
  totalDies: number,
  cx: number,
  cy: number,
  r: number,
): string {
  // ── Die 1：平直钢带 + 两段浅下凹（最左 / 中间 / 最右保持平直）────
  if (dieIndex === 1) {
    const depth = r * 0.11;
    return [
      `M ${(cx - r * 1.1).toFixed(1)} ${cy.toFixed(1)}`,
      `L ${(cx - r * 0.64).toFixed(1)} ${cy.toFixed(1)}`,
      `C ${(cx - r * 0.58).toFixed(1)} ${cy.toFixed(1)} ${(cx - r * 0.58).toFixed(1)} ${(cy + depth).toFixed(1)} ${(cx - r * 0.5).toFixed(1)} ${(cy + depth).toFixed(1)}`,
      `C ${(cx - r * 0.42).toFixed(1)} ${(cy + depth).toFixed(1)} ${(cx - r * 0.42).toFixed(1)} ${cy.toFixed(1)} ${(cx - r * 0.36).toFixed(1)} ${cy.toFixed(1)}`,
      `L ${(cx + r * 0.36).toFixed(1)} ${cy.toFixed(1)}`,
      `C ${(cx + r * 0.42).toFixed(1)} ${cy.toFixed(1)} ${(cx + r * 0.42).toFixed(1)} ${(cy + depth).toFixed(1)} ${(cx + r * 0.5).toFixed(1)} ${(cy + depth).toFixed(1)}`,
      `C ${(cx + r * 0.58).toFixed(1)} ${(cy + depth).toFixed(1)} ${(cx + r * 0.58).toFixed(1)} ${cy.toFixed(1)} ${(cx + r * 0.64).toFixed(1)} ${cy.toFixed(1)}`,
      `L ${(cx + r * 1.1).toFixed(1)} ${cy.toFixed(1)}`,
    ].join(" ");
  }

  // ── Die 2：平中间 + 两侧边缘微翘（只有角落开始弯）──────────────────────────
  if (dieIndex === 2) {
    const flatHalf = r * 0.42;  // 中间平直段半宽
    const curlUp   = r * 0.36;  // 边缘上翘高度
    return [
      `M ${(cx - r).toFixed(1)} ${(cy - curlUp).toFixed(1)}`,
      `Q ${(cx - r * 0.65).toFixed(1)} ${cy.toFixed(1)} ${(cx - flatHalf).toFixed(1)} ${cy.toFixed(1)}`,
      `L ${(cx + flatHalf).toFixed(1)} ${cy.toFixed(1)}`,
      `Q ${(cx + r * 0.65).toFixed(1)} ${cy.toFixed(1)} ${(cx + r).toFixed(1)} ${(cy - curlUp).toFixed(1)}`,
    ].join(" ");
  }

  // ── Die 3-16：弧线，开口角从大到零（圆弧 → 闭合圆）─────────────────────────
  //   t=0 (die 3): 开口半角 = 120°（浅弧）
  //   t=1 (die 16): 开口半角 = 0°（闭合圆）
  const t = Math.min(1, (dieIndex - 3) / Math.max(1, totalDies - 3));
  const gapHalfRad = (1 - t) * ((120 * Math.PI) / 180);

  // 闭合圆（die 16 或极小开口）
  if (gapHalfRad < 0.02) {
    return [
      `M ${(cx - r).toFixed(2)} ${cy.toFixed(2)}`,
      `A ${r.toFixed(2)} ${r.toFixed(2)} 0 1 0 ${(cx + r).toFixed(2)} ${cy.toFixed(2)}`,
      `A ${r.toFixed(2)} ${r.toFixed(2)} 0 1 0 ${(cx - r).toFixed(2)} ${cy.toFixed(2)}`,
    ].join(" ");
  }

  // 开口圆弧：开口在上方，弧从右端绕底到左端
  const rightX = cx + r * Math.sin(gapHalfRad);
  const rightY = cy - r * Math.cos(gapHalfRad);
  const leftX  = cx - r * Math.sin(gapHalfRad);
  const leftY  = rightY;

  const arcSpan  = 2 * Math.PI - 2 * gapHalfRad;
  const largeArc = arcSpan > Math.PI ? 1 : 0;

  return [
    `M ${rightX.toFixed(2)} ${rightY.toFixed(2)}`,
    `A ${r.toFixed(2)} ${r.toFixed(2)} 0 ${largeArc} 1 ${leftX.toFixed(2)} ${leftY.toFixed(2)}`,
  ].join(" ");
}

// ── 成型截面 SVG 组件 ─────────────────────────────────────────────────────────

function FormingShape({
  dieIndex,
  totalDies,
  size,
}: {
  dieIndex: number;
  totalDies: number;
  size: number;
}) {
  const cx = size / 2;
  const r  = size * 0.35;
  // 小格子：底部对齐（让成型从下向上逐步收拢）
  // 大图（详情面板）：居中显示，避免圆偏角
  const cy = size >= 80 || dieIndex === totalDies
    ? size * 0.5      // 大图和闭合圆: 居中
    : size * 0.9 - r; // 小格子: 底部对齐

  const path    = getFormingPath(dieIndex, totalDies, cx, cy, r);
  const strokeW = size < 80 ? 1.6 : 2.6;

  return (
    <svg
      width={size}
      height={size}
      viewBox={`0 0 ${size} ${size}`}
      style={{ overflow: "visible" }}
    >
      <path
        d={path}
        fill="none"
        stroke="#374151"
        strokeWidth={strokeW}
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

// ── 模具格子 ──────────────────────────────────────────────────────────────────

function DieCell({
  die,
  totalDies,
  selected,
  onClick,
}: {
  die: DiePositionData;
  totalDies: number;
  selected: boolean;
  onClick: () => void;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={[
        "relative flex h-[84px] w-[112px] shrink-0 items-center justify-center rounded-xl border-2 px-2 py-2.5 transition-all",
        "hover:scale-105 hover:shadow-md cursor-pointer",
        selected
          ? "border-zinc-900 bg-zinc-50 shadow-md"
          : "border-zinc-200 bg-white hover:border-zinc-400",
      ].join(" ")}
    >
      <span className="absolute top-3 text-[10px] font-bold text-zinc-400">{die.dieIndex}</span>
      <FormingShape dieIndex={die.dieIndex} totalDies={totalDies} size={44} />
    </button>
  );
}

// ── 详情面板 ──────────────────────────────────────────────────────────────────

function DieDetailPanel({ die, totalDies }: { die: DiePositionData; totalDies: number }) {
  // 大图的 stage 标签
  const progress = die.dieIndex / totalDies;
  const stageLabel =
    die.dieIndex === 1 ? "原料钢带（平）" :
    die.dieIndex === 2 ? "边缘初弯" :
    progress < 0.35    ? "浅弧成型" :
    progress < 0.6     ? "U 形成型" :
    progress < 0.85    ? "近圆成型" :
                         "圆管闭合";

  return (
    <div className="flex flex-col gap-5">
      <div className="flex items-center justify-between">
        <h3 className="text-lg font-bold text-zinc-950">{die.label}</h3>
        <span className="rounded-full bg-zinc-100 px-2.5 py-1 text-xs text-zinc-500">{stageLabel}</span>
      </div>

      {/* 大截面图 */}
      <div className="flex justify-center rounded-xl border border-zinc-100 bg-zinc-50 py-4">
        <FormingShape dieIndex={die.dieIndex} totalDies={totalDies} size={150} />
      </div>

      {/* 只显示 X / Y */}
      <div className="space-y-2">
        <div className="flex items-center justify-between rounded-lg bg-zinc-50 px-4 py-3">
          <span className="text-sm text-zinc-500">X 位置</span>
          <span className="font-mono text-sm font-semibold text-zinc-950">
            {die.xPos.toFixed(3)}&thinsp;mm
          </span>
        </div>
        <div className="flex items-center justify-between rounded-lg bg-zinc-50 px-4 py-3">
          <span className="text-sm text-zinc-500">Y 位置</span>
          <span className="font-mono text-sm font-semibold text-zinc-950">
            {die.yPos.toFixed(3)}&thinsp;mm
          </span>
        </div>
      </div>
    </div>
  );
}

// ── 主组件 ────────────────────────────────────────────────────────────────────

export function DieStatusOverview({
  artifact,
}: ArtifactComponentProps<Extract<InteractionArtifact, { type: "die_status_overview" }>>) {
  const props = artifact.props as DieStatusOverviewProps;
  const [selectedIdx, setSelectedIdx] = useState<number | null>(props.selectedDieIndex);

  const selectedDie = selectedIdx !== null
    ? props.dies.find((d) => d.dieIndex === selectedIdx) ?? null
    : null;

  return (
    <section className="w-full max-w-5xl">
      {/* 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">
          <Layers 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>
        {props.lastScanTime && (
          <span className="ml-auto text-xs text-zinc-400">读取时间：{props.lastScanTime}</span>
        )}
      </div>

      <div className="rounded-lg border border-zinc-200 bg-white shadow-sm">
        <div
          className={[
            "grid divide-y divide-zinc-100",
            selectedDie ? "lg:grid-cols-[1fr_220px] lg:divide-y-0 lg:divide-x" : "",
          ].join(" ")}
        >

          {/* 左：模具格子 */}
          <div className="p-5">
            <p className="mb-3 text-xs text-zinc-400">
              截面线图展示该模具出口处管材的成型状态（平板 → 圆管）· 点击查看坐标
            </p>
            <div className="flex flex-wrap justify-center gap-2">
              {props.dies.map((die) => (
                <DieCell
                  key={die.dieIndex}
                  die={die}
                  totalDies={props.totalDies}
                  selected={selectedIdx === die.dieIndex}
                  onClick={() =>
                    setSelectedIdx(selectedIdx === die.dieIndex ? null : die.dieIndex)
                  }
                />
              ))}
            </div>
          </div>

          {/* 右：详情 */}
          {selectedDie && (
            <div className="p-5">
              <DieDetailPanel die={selectedDie} totalDies={props.totalDies} />
            </div>
          )}
        </div>
      </div>
    </section>
  );
}
