"use client";

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

import type {
  OptimizationCase,
  OptimizationCaseDetail,
} from "../../lib/cases/types";
import { apiFetch } from "./api-client";
import { ArticleCaseDetail } from "./article-case-detail";
import { CaseAuthControl } from "./case-auth-control";
import { CasePublicationPanel } from "./case-publication-panel";
import { formatDate } from "./case-format";
import { CaseResultVersionList } from "./case-result-version-list";
import { HumanCopyCaseDetail } from "./human-copy-case-detail";

interface CaseDetailProps {
  caseId: string;
}

type CaseDetailResponse = Partial<OptimizationCaseDetail> & {
  error?: string;
};

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

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

export function CaseDetail({ caseId }: CaseDetailProps) {
  const [detail, setDetail] = useState<OptimizationCaseDetail | null>(null);
  const [selectedVersionId, setSelectedVersionId] = useState<string | null>(null);
  const [authenticated, setAuthenticated] = useState(false);
  const [sessionChecked, setSessionChecked] = useState(false);
  const [message, setMessage] = useState("");

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

    let isCurrent = true;
    apiFetch(`/api/cases/${caseId}`)
      .then((response) => response.json() as Promise<CaseDetailResponse>)
      .then((body: CaseDetailResponse) => {
        if (!isCurrent) return;
        if (body.error || !body.case || !body.versions) {
          setMessage(body.error ?? "案例加载失败");
          setDetail(null);
          return;
        }
        const nextDetail = {
          case: body.case,
          input: body.input ?? null,
          versions: body.versions,
        };
        setDetail(nextDetail);
        setSelectedVersionId(
          body.case.latest_result_version_id ??
            body.versions[0]?.id ??
            null,
        );
        setMessage("");
      })
      .catch((error) => {
        if (!isCurrent) return;
        setMessage(error instanceof Error ? error.message : "案例加载失败");
        setDetail(null);
      });
    return () => {
      isCurrent = false;
    };
  }, [authenticated, caseId, sessionChecked]);

  const selectedVersion = useMemo(() => {
    if (!detail) return null;
    return (
      detail.versions.find((version) => version.id === selectedVersionId) ??
      detail.versions[0] ??
      null
    );
  }, [detail, selectedVersionId]);

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

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

  return (
    <main className="app-shell">
      <header className="topbar">
        <div>
          <h1>{detail?.case.title ?? "案例详情"}</h1>
          {visibleMessage ? (
            <p>{visibleMessage}</p>
          ) : detail ? (
            <p>{detail.case.summary}</p>
          ) : null}
        </div>
        <div className="topbar-actions">
          <Link className="text-link" href="/cases">
            返回案例库
          </Link>
          <CaseAuthControl
            authenticated={authenticated}
            onAuthenticatedChange={updateAuthenticated}
          />
        </div>
      </header>

      {detail ? (
        <>
          <section className="panel compact-panel stack">
            <div className="case-meta-grid">
              <MetaItem label="类型" value={caseTypeLabels[detail.case.case_type]} />
              <MetaItem label="状态" value={statusLabels[detail.case.status]} />
              <MetaItem label="客户" value={detail.case.customer_name || "未填写"} />
              <MetaItem label="品牌" value={detail.case.brand_name || "未填写"} />
              <MetaItem
                label="项目标签"
                value={
                  detail.case.project_tags.length > 0
                    ? detail.case.project_tags.join("、")
                    : "未标记"
                }
              />
              <MetaItem
                label="发布目标"
                value={detail.case.publish_target || "未指定"}
              />
              <MetaItem label="版本" value={`v${detail.case.latest_version_number ?? 0}`} />
              <MetaItem label="更新" value={formatDate(detail.case.updated_at)} />
            </div>
            {detail.case.notes ? <p>{detail.case.notes}</p> : null}
          </section>

          {detail.case.last_error_summary ? (
            <section className="panel compact-panel stack">
              <div className="panel-heading">最近失败</div>
              <p className="status-text">{detail.case.last_error_stage}</p>
              <p>{detail.case.last_error_summary}</p>
            </section>
          ) : null}

          <section className="case-detail-grid">
            <CaseResultVersionList
              selectedVersionId={selectedVersion?.id ?? null}
              versions={detail.versions}
              onSelect={setSelectedVersionId}
            />
            <section className="stack">
              {detail.case.case_type === "article" ? (
                <ArticleCaseDetail
                  input={detail.input?.payload ?? null}
                  version={selectedVersion}
                />
              ) : (
                <HumanCopyCaseDetail
                  input={detail.input?.payload ?? null}
                  version={selectedVersion}
                />
              )}
              <CasePublicationPanel
                caseId={detail.case.id}
                publishTarget={detail.case.publish_target}
                versionId={selectedVersion?.id ?? null}
              />
            </section>
          </section>
        </>
      ) : (
        <section className="panel empty-panel">案例详情会显示在这里。</section>
      )}
    </main>
  );
}

function MetaItem({ label, value }: { label: string; value: string }) {
  return (
    <div>
      <span>{label}</span>
      <strong>{value}</strong>
    </div>
  );
}
