import { createSignal, For, Show, createMemo } from 'solid-js';
import type { PageData } from './hooks/usePDFExport';
import type { CardPath } from '../../plotcutter';
import type { CardShape } from '../../plotcutter';
import {
  getCardShapePoints,
  calculateCenter,
  contourToSvgPath
} from '../../plotcutter';
import { generateTravelPaths, travelPathsToSvg } from '../../plotcutter';
import { pts2plotter } from '../../plotcutter';

export interface PltPreviewProps {
  pages: PageData[];
  cardWidth: number;
  cardHeight: number;
  shape: CardShape;
  bleed: number;
  cornerRadius: number;
  onClose: () => void;
}

/**
 * 生成卡片切割路径
 */
function generateCardPaths(
  pages: PageData[],
  cardWidth: number,
  cardHeight: number,
  shape: CardShape,
  bleed: number,
  cornerRadius: number,
  a4Height: number
): CardPath[] {
  const cardPaths: CardPath[] = [];
  let pathIndex = 0;

  // 计算切割尺寸（排版尺寸减去出血）
  const cutWidth = cardWidth - bleed * 2;
  const cutHeight = cardHeight - bleed * 2;

  for (const page of pages) {
    for (const card of page.cards) {
      if (card.side !== 'front') continue;

      // 生成形状轮廓点（相对于卡片左下角）
      const shapePoints = getCardShapePoints(shape, cutWidth, cutHeight, cornerRadius);

      // 平移到页面坐标并翻转 Y 轴
      const pagePoints = shapePoints.map(([x, y]) => [
        card.x + bleed + x,
        a4Height - (card.y + bleed + y)
      ] as [number, number]);

      const center = calculateCenter(pagePoints);
      const pathD = contourToSvgPath(pagePoints);

      // 起点和终点（对于闭合路径是同一点）
      const startPoint = pagePoints[0];
      const endPoint = pagePoints[pagePoints.length - 1];

      cardPaths.push({
        pageIndex: page.pageIndex,
        cardIndex: pathIndex++,
        points: pagePoints,
        centerX: center.x,
        centerY: center.y,
        pathD,
        startPoint,
        endPoint
      });
    }
  }

  return cardPaths;
}

/**
 * PLT 预览组件 - 显示切割路径预览
 */
export function PltPreview(props: PltPreviewProps) {
  const a4Width = 297; // 横向 A4
  const a4Height = 210;

  // 使用传入的圆角值，但也允许用户修改
  const [cornerRadius, setCornerRadius] = createSignal(props.cornerRadius);

  // 生成所有卡片路径
  const cardPaths = createMemo(() =>
    generateCardPaths(
      props.pages,
      props.cardWidth,
      props.cardHeight,
      props.shape,
      props.bleed,
      cornerRadius(),
      a4Height
    )
  );

  // 生成空走路径
  const travelPathD = createMemo(() => {
    const travelPaths = generateTravelPaths(cardPaths(), a4Height);
    return travelPathsToSvg(travelPaths);
  });

  // 生成 HPGL 代码用于下载
  const plotterCode = createMemo(() => {
    const allPaths = cardPaths().map(p => p.points);
    return allPaths.length > 0 ? pts2plotter(allPaths, a4Width, a4Height, 1) : '';
  });

  const handleDownload = () => {
    if (!plotterCode()) {
      alert('没有可导出的卡片');
      return;
    }

    const blob = new Blob([plotterCode()], { type: 'application/vnd.hp-HPGL' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `deck-export-${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.plt`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  };

  const handleCornerRadiusChange = (e: Event) => {
    const target = e.target as HTMLInputElement;
    setCornerRadius(Number(target.value));
  };

  return (
    <div class="fixed inset-0 bg-black/50 z-50 overflow-auto">
      <div class="min-h-screen py-20 px-4">
        {/* 头部控制栏 */}
        <div class="fixed top-4 left-1/2 -translate-x-1/2 bg-white shadow-lg rounded-lg px-4 py-3 flex items-center gap-4 z-50">
          <h2 class="text-base font-bold m-0">PLT 切割预览</h2>
          <div class="flex items-center gap-2">
            <label class="text-sm text-gray-600">圆角 (mm):</label>
            <input
              type="number"
              min="0"
              max="10"
              step="0.5"
              value={cornerRadius()}
              onInput={handleCornerRadiusChange}
              class="w-16 px-2 py-1 border border-gray-300 rounded text-sm"
            />
          </div>
          <div class="flex items-center gap-2 flex-1">
            <button
              onClick={handleDownload}
              class="bg-blue-600 hover:bg-blue-700 text-white px-3 py-1.5 rounded text-sm font-medium cursor-pointer flex items-center gap-1"
              disabled={cardPaths().length === 0}
            >
              📥 下载 PLT
            </button>

            <button
              onClick={props.onClose}
              class="bg-gray-200 hover:bg-gray-300 text-gray-700 px-3 py-1.5 rounded text-sm font-medium cursor-pointer"
            >
              关闭
            </button>
          </div>
        </div>

        {/* 预览区域 */}
        <div class="flex flex-col items-center gap-8 mt-20">
          <For each={props.pages}>
            {(page) => {
              const pageCardPaths = cardPaths().filter(p => p.pageIndex === page.pageIndex);

              return (
                <svg
                  class="bg-white shadow-xl"
                  viewBox={`0 0 ${a4Width} ${a4Height}`}
                  style={{
                    width: `${a4Width}mm`,
                    height: `${a4Height}mm`
                  }}
                  xmlns="http://www.w3.org/2000/svg"
                >
                  {/* A4 边框 */}
                  <rect
                    x="0"
                    y="0"
                    width={a4Width}
                    height={a4Height}
                    fill="none"
                    stroke="#ccc"
                    stroke-width="0.5"
                  />

                  {/* 页面边框 */}
                  <rect
                    x={page.frameBounds.minX}
                    y={page.frameBounds.minY}
                    width={page.frameBounds.maxX - page.frameBounds.minX}
                    height={page.frameBounds.maxY - page.frameBounds.minY}
                    fill="none"
                    stroke="#888"
                    stroke-width="0.2"
                  />

                  {/* 空走路径（虚线） */}
                  <Show when={travelPathD()}>
                    <path
                      d={travelPathD()}
                      fill="none"
                      stroke="#999"
                      stroke-width="0.2"
                      stroke-dasharray="2 2"
                    />
                  </Show>

                  {/* 切割路径 */}
                  <For each={pageCardPaths}>
                    {(path) => {
                      return (
                        <g>
                          {/* 切割路径 */}
                          <path
                            d={path.pathD}
                            fill="none"
                            stroke="#3b82f6"
                            stroke-width="0.3"
                          />

                          {/* 动画小球 */}
                          <circle
                            r="0.8"
                            fill="#ef4444"
                          >
                            <animateMotion dur="4s" repeatCount="indefinite" path={path.pathD}>
                            </animateMotion>
                          </circle>

                          {/* 序号标签 */}
                          <g transform={`translate(${path.centerX}, ${path.centerY})`}>
                            <circle
                              r="2"
                              fill="white"
                              stroke="#3b82f6"
                              stroke-width="0.1"
                            />
                            <text
                              text-anchor="middle"
                              dominant-baseline="middle"
                              font-size="1.5"
                              fill="#3b82f6"
                              font-weight="bold"
                            >
                              {path.cardIndex + 1}
                            </text>
                          </g>
                        </g>
                      );
                    }}
                  </For>
                </svg>
              );
            }}
          </For>
        </div>

        {/* 图例说明 */}
        <div class="fixed bottom-4 left-1/2 -translate-x-1/2 bg-white shadow-lg rounded-lg px-4 py-2 flex items-center gap-4 z-50">
          <div class="flex items-center gap-2">
            <div class="w-6 h-0.5" style={{ "border-bottom": "2px dashed #999" }}></div>
            <span class="text-sm text-gray-600">空走路径</span>
          </div>
          <div class="flex items-center gap-2">
            <div class="w-6 h-0.5" style={{ "border-bottom": "2px solid #3b82f6" }}></div>
            <span class="text-sm text-gray-600">切割路径</span>
          </div>
          <div class="flex items-center gap-2">
            <div class="w-4 h-4 rounded-full bg-red-500"></div>
            <span class="text-sm text-gray-600">刀头</span>
          </div>
        </div>
      </div>
    </div>
  );
}
