"use client";

import Link from "next/link";
import { useCallback, useEffect, useMemo, useState } from "react";

import type { OptimizationCase } from "../../lib/cases/types";
import { apiFetch } from "./api-client";
import { CaseAuthControl } from "./case-auth-control";

interface CaseListResponse {
  cases?: OptimizationCase[];
  error?: string;
}

const caseTypeLabels: Record<OptimizationCase["case_type"], string> = {
  article: "文章优化",
  human_copy: "人味文案",
};

const statusLabels: Record<OptimizationCase["status"], string> = {
  running: "运行中",
  optimized: "已优化",
  failed: "失败",
  archived: "已归档",
};

export function CaseList() {
  const [cases, setCases] = useState<OptimizationCase[]>([]);
  const [caseType, setCaseType] = useState("");
  const [status, setStatus] = useState("");
  const [query, setQuery] = useState("");
  const [message, setMessage] = useState("");
  const [authenticated, setAuthenticated] = useState(false);
  const [sessionChecked, setSessionChecked] = useState(false);

  const search = useMemo(() => {
    const params = new URLSearchParams();
    if (caseType) params.set("case_type", caseType);
    if (status) params.set("status", status);
    if (query) params.set("q", query);
    return params.toString();
  }, [caseType, status, query]);

  useEffect(() => {
    if (!sessionChecked || !authenticated) return;

    let isCurrent = true;
    apiFetch(`/api/cases${search ? `?${search}` : ""}`)
      .then((response) => response.json() as Promise<CaseListResponse>)
      .then((body: CaseListResponse) => {
        if (!isCurrent) return;
        setCases(body.cases ?? []);
        setMessage(body.error ?? "");
      })
      .catch((error) => {
        if (!isCurrent) return;
        setMessage(error instanceof Error ? error.message : "案例加载失败");
      });
    return () => {
      isCurrent = false;
    };
  }, [authenticated, search, sessionChecked]);

  const updateAuthenticated = useCallback((nextAuthenticated: boolean) => {
    setAuthenticated(nextAuthenticated);
    setSessionChecked(true);
    setMessage("");
    if (!nextAuthenticated) {
      setCases([]);
    }
  }, []);

  const visibleMessage =
    message ||
    (sessionChecked && !authenticated ? "请先登录后查看案例库。" : "");

  return (
    <main className="app-shell">
      <header className="topbar">
        <div>
          <h1>案例库</h1>
          {visibleMessage ? <p>{visibleMessage}</p> : null}
        </div>
        <div className="topbar-actions">
          <Link className="text-link" href="/">
            返回优化台
          </Link>
          <CaseAuthControl
            authenticated={authenticated}
            onAuthenticatedChange={updateAuthenticated}
          />
        </div>
      </header>
      <section className="case-toolbar" aria-label="案例筛选">
        <input
          aria-label="关键词"
          placeholder="搜索标题、客户、品牌、备注"
          value={query}
          onChange={(event) => setQuery(event.target.value)}
        />
        <select
          aria-label="案例类型"
          value={caseType}
          onChange={(event) => setCaseType(event.target.value)}
        >
          <option value="">全部类型</option>
          <option value="article">文章优化</option>
          <option value="human_copy">人味文案</option>
        </select>
        <select
          aria-label="状态"
          value={status}
          onChange={(event) => setStatus(event.target.value)}
        >
          <option value="">全部状态</option>
          <option value="running">运行中</option>
          <option value="optimized">已优化</option>
          <option value="failed">失败</option>
        </select>
      </section>
      <section className="case-table" aria-label="案例列表">
        <div className="case-row case-row-heading">
          <span>标题/摘要</span>
          <span>类型</span>
          <span>客户/品牌</span>
          <span>项目标签</span>
          <span>发布目标</span>
          <span>状态</span>
          <span>最近更新</span>
        </div>
        {cases.map((item) => (
          <Link className="case-row" href={`/cases/${item.id}`} key={item.id}>
            <span>
              <strong>{item.title}</strong>
              <small>{item.summary}</small>
            </span>
            <span>{caseTypeLabels[item.case_type]}</span>
            <span>
              {[item.customer_name, item.brand_name].filter(Boolean).join(" / ") ||
                "未填写"}
            </span>
            <span>
              {item.project_tags.length > 0
                ? item.project_tags.join("、")
                : "未标记"}
            </span>
            <span>{item.publish_target || "未指定"}</span>
            <span>
              <span className={`status-pill ${statusClass(item.status)}`}>
                {statusLabels[item.status]}
              </span>
            </span>
            <span>{formatDate(item.updated_at)}</span>
          </Link>
        ))}
        {authenticated && cases.length === 0 ? (
          <p className="empty-panel">还没有可显示的案例。</p>
        ) : null}
      </section>
    </main>
  );
}

function formatDate(value: string) {
  return new Date(value).toLocaleString("zh-CN", {
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
}

function statusClass(status: OptimizationCase["status"]) {
  if (status === "failed") return "fail";
  if (status === "running") return "warn";
  return "pass";
}
