"use client";

import { useState, type FormEvent } from "react";

import type {
  CopyOptimizationIntensity,
  CopyOptimizationResult,
} from "../lib/domain/types";

interface RenweiCopyOptimizerPanelProps {
  apiAccessKey: string;
}

interface CopyOptimizeResponse {
  case?: { id: string; case_type: "human_copy" };
  result_version?: { id: string; version: number };
  result?: CopyOptimizationResult;
  error?: string;
}

const intensityOptions: Array<{
  value: CopyOptimizationIntensity;
  label: string;
}> = [
  { value: "light", label: "轻微整理" },
  { value: "medium", label: "适度润色" },
  { value: "conversational", label: "更口语自然" },
];

export function RenweiCopyOptimizerPanel({
  apiAccessKey,
}: RenweiCopyOptimizerPanelProps) {
  const [sourceText, setSourceText] = useState("");
  const [goal, setGoal] = useState("保留原意，减少 AI 味");
  const [intensity, setIntensity] =
    useState<CopyOptimizationIntensity>("light");
  const [userInstructions, setUserInstructions] = useState("");
  const [publishTarget, setPublishTarget] = useState("朋友圈");
  const [result, setResult] = useState<CopyOptimizationResult | null>(null);
  const [caseId, setCaseId] = useState<string | null>(null);
  const [message, setMessage] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);

  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setIsSubmitting(true);
    setMessage("");
    setResult(null);
    setCaseId(null);

    try {
      const response = await fetch("/api/copy/renwei-optimize", {
        method: "POST",
        headers: apiHeaders(apiAccessKey),
        body: JSON.stringify({
          source_text: sourceText,
          goal,
          intensity,
          user_instructions: userInstructions,
          publish_target: publishTarget,
        }),
      });
      const body = (await response.json()) as CopyOptimizeResponse;
      if (!response.ok || !body.result) {
        throw new Error(body.error ?? "文案优化失败");
      }
      setResult(body.result);
      setCaseId(body.case?.id ?? null);
      setMessage("文案优化完成，已保存到案例库。");
    } catch (error) {
      setMessage(error instanceof Error ? error.message : "文案优化失败");
    } finally {
      setIsSubmitting(false);
    }
  }

  async function copyResult() {
    if (!result?.optimized_text) return;
    await navigator.clipboard.writeText(result.optimized_text);
    setMessage("已复制优化结果。");
  }

  return (
    <section className="copy-optimizer-grid">
      <form className="panel stack" onSubmit={submit}>
        <div className="panel-heading">
          <span>普通文案优化</span>
          <button disabled={isSubmitting} type="submit">
            {isSubmitting ? "优化中..." : "优化文案"}
          </button>
        </div>
        <label>
          <span>原始文案</span>
          <textarea
            className="body-input"
            required
            value={sourceText}
            onChange={(event) => setSourceText(event.target.value)}
          />
        </label>
        <label>
          <span>优化目标</span>
          <input value={goal} onChange={(event) => setGoal(event.target.value)} />
        </label>
        <label>
          <span>修改强度</span>
          <select
            value={intensity}
            onChange={(event) =>
              setIntensity(event.target.value as CopyOptimizationIntensity)
            }
          >
            {intensityOptions.map((option) => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
        </label>
        <label>
          <span>补充要求</span>
          <textarea
            value={userInstructions}
            onChange={(event) => setUserInstructions(event.target.value)}
          />
        </label>
        <label>
          <span>发布目标</span>
          <input
            value={publishTarget}
            onChange={(event) => setPublishTarget(event.target.value)}
          />
        </label>
        {message ? <p className="status-text">{message}</p> : null}
      </form>

      <section className="panel stack">
        <div className="panel-heading">
          <span>优化后文案</span>
          <button disabled={!result} onClick={copyResult} type="button">
            复制结果
          </button>
        </div>
        {result ? (
          <>
            {caseId ? (
              <a className="text-link" href={`/cases/${caseId}`}>
                查看案例详情
              </a>
            ) : null}
            <pre className="copy-result">{result.optimized_text}</pre>
            <section className="stack">
              <h3>改动说明</h3>
              <ul className="qa-list">
                {result.change_notes.map((note, index) => (
                  <li className="qa-item" key={`${note.original}-${index}`}>
                    <p>{note.reason}</p>
                    <small>原句：{note.original}</small>
                    <small>改后：{note.revised}</small>
                    {note.revertible ? <em>这处可还原。</em> : null}
                  </li>
                ))}
              </ul>
            </section>
            <section className="stack">
              <h3>AI 味检查</h3>
              <ul className="qa-list">
                {result.ai_taste_checks.map((check) => (
                  <li className="qa-item" key={check.rule_id}>
                    <p>
                      <span className={`status-pill ${check.status}`}>
                        {check.status}
                      </span>
                    </p>
                    <small>{check.evidence}</small>
                    {check.suggestion ? <small>{check.suggestion}</small> : null}
                  </li>
                ))}
              </ul>
            </section>
            {result.warnings.length > 0 ? (
              <ul className="calibration-observations">
                {result.warnings.map((warning) => (
                  <li key={warning}>{warning}</li>
                ))}
              </ul>
            ) : null}
          </>
        ) : (
          <p className="empty-panel">优化结果会显示在这里。</p>
        )}
      </section>
    </section>
  );
}

function apiHeaders(apiAccessKey: string) {
  const headers: Record<string, string> = { "content-type": "application/json" };
  if (apiAccessKey) {
    headers["x-api-key"] = apiAccessKey;
  }
  return headers;
}
