import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { api } from "../api/client";
import type { Creative } from "../types";
import styles from "./Dashboard.module.css";

export default function Dashboard() {
  const [creatives, setCreatives] = useState<Creative[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    api
      .getCreatives()
      .then((res) => setCreatives(res.data))
      .catch((e) => setError(e.message))
      .finally(() => setLoading(false));
  }, []);

  const statusLabel: Record<string, string> = {
    draft: "草稿",
    assets_ready: "素材已就绪",
    building: "构建中",
    built: "已构建",
    failed: "失败",
  };

  const statusColor: Record<string, string> = {
    draft: "#86868b",
    assets_ready: "#0071e3",
    building: "#ff9500",
    built: "#34c759",
    failed: "#ff3b30",
  };

  if (loading) {
    return <div className={styles.state}>加载中…</div>;
  }

  if (error) {
    return <div className={styles.state}>加载失败：{error}</div>;
  }

  if (creatives.length === 0) {
    return (
      <div className={styles.empty}>
        <p className={styles.emptyTitle}>暂无创意</p>
        <p className={styles.emptyDesc}>点击"新建创意"开始制作 Playable 广告</p>
        <Link to="/creatives/new" className={styles.emptyBtn}>
          新建创意
        </Link>
      </div>
    );
  }

  return (
    <div className={styles.grid}>
      {creatives.map((c) => (
        <Link to={`/creatives/${c.id}`} key={c.id} className={styles.card}>
          <h3 className={styles.cardTitle}>{c.name}</h3>
          <div className={styles.cardMeta}>
            <span>模板：{c.templateName}</span>
            <span
              className={styles.status}
              style={{ color: statusColor[c.status] }}
            >
              ● {statusLabel[c.status] || c.status}
            </span>
          </div>
          <div className={styles.cardTime}>
            更新于 {new Date(c.updatedAt).toLocaleString("zh-CN")}
          </div>
        </Link>
      ))}
    </div>
  );
}
