"use client";

import { useEffect, useState } from "react";

import type { PublicationRecord } from "../../lib/calibration/types";
import { apiFetch } from "./api-client";
import { formatDate } from "./case-format";

interface CasePublicationPanelProps {
  caseId: string;
  versionId: string | null;
  publishTarget: string;
}

interface PublicationListResponse {
  publications?: PublicationRecord[];
  error?: string;
}

interface PublicationCreateResponse {
  publication?: PublicationRecord;
  error?: string;
}

interface PerformanceResponse {
  snapshot?: { metrics: Record<string, number> };
  calibrationEvent?: { observations: string[]; recommended_action: string } | null;
  error?: string;
}

export function CasePublicationPanel({
  caseId,
  versionId,
  publishTarget,
}: CasePublicationPanelProps) {
  const [publications, setPublications] = useState<PublicationRecord[]>([]);
  const [url, setUrl] = useState("");
  const [publishedAt, setPublishedAt] = useState(() =>
    new Date().toISOString().slice(0, 16),
  );
  const [notes, setNotes] = useState("");
  const [publicationId, setPublicationId] = useState<string | null>(null);
  const [views, setViews] = useState("");
  const [clicks, setClicks] = useState("");
  const [inquiries, setInquiries] = useState("");
  const [feedbackSummary, setFeedbackSummary] = useState("");
  const [message, setMessage] = useState("");
  const [observations, setObservations] = useState<string[]>([]);

  useEffect(() => {
    if (!versionId) {
      return;
    }
    let isCurrent = true;
    apiFetch(`/api/cases/${caseId}/versions/${versionId}/publications`)
      .then((response) => response.json() as Promise<PublicationListResponse>)
      .then((body: PublicationListResponse) => {
        if (!isCurrent) return;
        setPublications(body.publications ?? []);
        setMessage(body.error ?? "");
      })
      .catch((error) => {
        if (!isCurrent) return;
        setMessage(error instanceof Error ? error.message : "发布记录加载失败");
      });
    return () => {
      isCurrent = false;
    };
  }, [caseId, versionId]);

  async function registerPublication() {
    if (!versionId || !url || !publishedAt) return;
    setMessage("");
    const response = await apiFetch(
      `/api/cases/${caseId}/versions/${versionId}/publications`,
      {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          publish_target: publishTarget || "未指定",
          url,
          published_at: new Date(publishedAt).toISOString(),
          notes,
        }),
      },
    );
    const body = (await response.json()) as PublicationCreateResponse;
    if (!response.ok || !body.publication) {
      setMessage(body.error ?? "发布记录保存失败");
      return;
    }
    setPublicationId(body.publication.id);
    setPublications((items) => [body.publication!, ...items]);
    setMessage("发布记录已保存。");
  }

  async function recordPerformance() {
    if (!publicationId) return;
    setMessage("");
    const response = await apiFetch(`/api/publications/${publicationId}/performance`, {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({
        window_label: "T+7d",
        views,
        clicks,
        inquiries,
        feedback_summary: feedbackSummary,
      }),
    });
    const body = (await response.json()) as PerformanceResponse;
    if (!response.ok || !body.snapshot) {
      setMessage(body.error ?? "表现数据保存失败");
      return;
    }
    setObservations(body.calibrationEvent?.observations ?? []);
    setMessage(
      body.calibrationEvent?.recommended_action ?? "表现数据已保存。",
    );
  }

  return (
    <section className="panel stack">
      <div className="panel-heading">发布表现</div>
      {versionId && publications.length > 0 ? (
        <ul className="case-publication-list">
          {publications.map((publication) => (
            <li key={publication.id}>
              <a href={publication.url}>{publication.url}</a>
              <small>
                {publication.publish_target} · {formatDate(publication.published_at)}
              </small>
              {publication.notes ? <small>{publication.notes}</small> : null}
            </li>
          ))}
        </ul>
      ) : (
        <p className="empty-panel">还没有发布记录，可以先登记发布链接和手动表现。</p>
      )}

      <div className="case-publication-form">
        <label>
          <span>发布链接</span>
          <input
            disabled={!versionId}
            placeholder="https://example.com/article"
            value={url}
            onChange={(event) => setUrl(event.target.value)}
          />
        </label>
        <label>
          <span>发布时间</span>
          <input
            disabled={!versionId}
            type="datetime-local"
            value={publishedAt}
            onChange={(event) => setPublishedAt(event.target.value)}
          />
        </label>
        <label>
          <span>备注</span>
          <input
            disabled={!versionId}
            value={notes}
            onChange={(event) => setNotes(event.target.value)}
          />
        </label>
        <button disabled={!versionId || !url || !publishedAt} onClick={registerPublication} type="button">
          保存发布记录
        </button>
      </div>

      <div className="calibration-metrics">
        <label>
          <span>阅读/浏览</span>
          <input
            min="0"
            type="number"
            value={views}
            onChange={(event) => setViews(event.target.value)}
          />
        </label>
        <label>
          <span>点击</span>
          <input
            min="0"
            type="number"
            value={clicks}
            onChange={(event) => setClicks(event.target.value)}
          />
        </label>
        <label>
          <span>询盘</span>
          <input
            min="0"
            type="number"
            value={inquiries}
            onChange={(event) => setInquiries(event.target.value)}
          />
        </label>
      </div>
      <label>
        <span>反馈摘要</span>
        <textarea
          value={feedbackSummary}
          onChange={(event) => setFeedbackSummary(event.target.value)}
        />
      </label>
      <button disabled={!publicationId} onClick={recordPerformance} type="button">
        记录表现
      </button>
      {message ? <p className="status-text">{message}</p> : null}
      {observations.length > 0 ? (
        <ul className="calibration-observations">
          {observations.map((observation) => (
            <li key={observation}>{observation}</li>
          ))}
        </ul>
      ) : null}
    </section>
  );
}
