import { useEffect, useState } from "react";
import QRCode from "qrcode";
import { api } from "../api/client";
import type { BuildSummary } from "../types";
import styles from "./BuildHistory.module.css";

interface Props {
  creativeId: string;
  builds: BuildSummary[];
  onUpdated: () => void;
}

export default function BuildHistory({ creativeId, builds: initialBuilds, onUpdated }: Props) {
  const [builds, setBuilds] = useState<BuildSummary[]>(initialBuilds);
  const [qrDataUrls, setQrDataUrls] = useState<Record<string, string>>({});

  useEffect(() => {
    setBuilds(initialBuilds);
  }, [initialBuilds]);

  useEffect(() => {
    // 如果有 building/pending 状态的构建，自动刷新
    const hasActive = builds.some((b) => b.status === "building" || b.status === "pending");
    if (!hasActive) return;

    const timer = setInterval(() => {
      api.getBuilds(creativeId).then((res) => {
        setBuilds(res.data);
        onUpdated();
      });
    }, 5000);

    return () => clearInterval(timer);
  }, [builds, creativeId, onUpdated]);

  // 为已完成的构建生成二维码
  useEffect(() => {
    builds.forEach((b) => {
      if (b.status === "completed" && b.previewUrl && !qrDataUrls[b.id]) {
        const fullUrl = window.location.origin + b.previewUrl;
        QRCode.toDataURL(fullUrl, {
          width: 160,
          margin: 1,
          color: { dark: "#000", light: "#fff" },
        })
          .then((url) => setQrDataUrls((prev) => ({ ...prev, [b.id]: url })))
          .catch(() => {}); // 生成失败静默忽略
      }
    });
  }, [builds, qrDataUrls]);

  const statusLabel: Record<string, string> = {
    pending: "等待中",
    building: "构建中",
    completed: "完成",
    failed: "失败",
  };

  const statusEmoji: Record<string, string> = {
    pending: "⏳",
    building: "🔄",
    completed: "✅",
    failed: "❌",
  };

  if (builds.length === 0) {
    return <p className={styles.empty}>暂无构建记录</p>;
  }

  return (
    <div className={styles.wrapper}>
      <h3 className={styles.title}>构建历史</h3>
      <div className={styles.list}>
        {builds.map((b) => (
          <div key={b.id} className={styles.item}>
            <div className={styles.itemInfo}>
              <span className={styles.status}>
                {statusEmoji[b.status]} {statusLabel[b.status]}
              </span>
              <span className={styles.platforms}>
                {b.platforms.map((p) => (
                  <span key={p} className={styles.platformTag}>{p}</span>
                ))}
              </span>
              <span className={styles.time}>
                {new Date(b.createdAt).toLocaleString("zh-CN")}
              </span>
            </div>

            {b.status === "completed" && (
              <>
                {/* 真机扫码预览 */}
                {b.previewUrl && (
                  <div className={styles.qrSection}>
                    <div className={styles.qrLabel}>📱 真机扫码预览</div>
                    <div className={styles.qrRow}>
                      {qrDataUrls[b.id] ? (
                        <img
                          className={styles.qrCode}
                          src={qrDataUrls[b.id]}
                          alt="扫码预览"
                        />
                      ) : (
                        <div className={styles.qrLoading}>生成中…</div>
                      )}
                      <div className={styles.qrUrl}>
                        <code>{window.location.origin}{b.previewUrl}</code>
                      </div>
                    </div>
                  </div>
                )}

                {/* 下载链接 */}
                {b.results && (
                  <div className={styles.downloads}>
                    {b.results.map((r) => (
                      <a
                        key={r.platform}
                        href={`${import.meta.env.BASE_URL}api/v1/builds/${b.id}/download/${r.platform}`}
                        className={styles.downloadLink}
                        download
                      >
                        {r.platform} ↓ ({(r.fileSize / 1024).toFixed(0)} KB)
                      </a>
                    ))}
                    <a
                      href={`${import.meta.env.BASE_URL}api/v1/builds/${b.id}/download/all`}
                      className={styles.downloadAll}
                      download
                    >
                      全部 ZIP ↓
                    </a>
                  </div>
                )}
              </>
            )}

            {b.status === "failed" && b.errorLog && (
              <p className={styles.errorLog}>{b.errorLog}</p>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}
