"use client";

import { useCallback, useState } from "react";

import { useToast } from "@/components/Toast";
import { Button } from "@/components/ui/Button";
import { Field } from "@/components/ui/Field";
import { SectionHeader } from "@/components/ui/SectionHeader";
import { TextArea } from "@/components/ui/TextArea";
import { TextInput } from "@/components/ui/TextInput";
import { api } from "@/lib/api/client";
import type { TemplateResponse } from "@/lib/api/types";
import {
  buildTemplateCreateRequest,
  EMPTY_TEMPLATE_DRAFT,
  isTemplateDraftValid,
  type TemplateDraft,
} from "@/lib/templates/templates";

interface TemplatesManagerProps {
  // 初始模板列表（Server Component 预取；失败给空数组 + loadError 文案）。
  initial: TemplateResponse[];
}

// 提示词/模板库管理（F3，单用户本地版）：列出 / 新建 / 删除。
// 列表本地维护（乐观更新失败回滚）；CRUD 走 OpenAPI 客户端。分享/市场不做（需多租户）。
export function TemplatesManager({ initial }: TemplatesManagerProps) {
  const toast = useToast();
  const [templates, setTemplates] = useState<TemplateResponse[]>(initial);
  const [draft, setDraft] = useState<TemplateDraft>(EMPTY_TEMPLATE_DRAFT);
  const [creating, setCreating] = useState(false);

  const setField = useCallback(
    (field: keyof TemplateDraft, value: string): void => {
      setDraft((prev) => ({ ...prev, [field]: value }));
    },
    [],
  );

  const onCreate = useCallback(async (): Promise<void> => {
    if (!isTemplateDraftValid(draft)) {
      toast("请填写标题与正文。", "error");
      return;
    }
    setCreating(true);
    try {
      const { data, error } = await api.POST("/templates", {
        body: buildTemplateCreateRequest(draft),
      });
      if (error || !data) {
        toast("新建模板失败，请重试。", "error");
        return;
      }
      setTemplates((prev) => [data, ...prev]);
      setDraft(EMPTY_TEMPLATE_DRAFT);
      toast("已新建模板。", "success");
    } catch {
      toast("新建模板请求异常，请检查网络。", "error");
    } finally {
      setCreating(false);
    }
  }, [draft, toast]);

  const onDelete = useCallback(
    async (id: string): Promise<void> => {
      const prev = templates;
      // 乐观删除：先移除，失败回滚。
      setTemplates((cur) => cur.filter((t) => t.id !== id));
      try {
        const { error } = await api.DELETE("/templates/{template_id}", {
          params: { path: { template_id: id } },
        });
        if (error) {
          setTemplates(prev);
          toast("删除模板失败，请重试。", "error");
          return;
        }
        toast("已删除模板。", "success");
      } catch {
        setTemplates(prev);
        toast("删除模板请求异常，请检查网络。", "error");
      }
    },
    [templates, toast],
  );

  return (
    <div className="flex flex-col gap-6">
      <form
        className="flex flex-col gap-3 rounded border border-line bg-panel p-5"
        aria-label="新建模板"
        onSubmit={(e) => {
          e.preventDefault();
          void onCreate();
        }}
      >
        <SectionHeader title="新建模板" />
        <Field label="标题" required>
          <TextInput
            type="text"
            value={draft.title}
            onChange={(e) => setField("title", e.target.value)}
            aria-label="标题"
          />
        </Field>
        <Field label="正文" required help="一键填入生成器的 brief/原文。">
          <TextArea
            value={draft.body}
            onChange={(e) => setField("body", e.target.value)}
            rows={4}
            aria-label="正文"
          />
        </Field>
        <div className="flex flex-wrap gap-4">
          <Field label="分类（可选）" className="w-full sm:w-48">
            <TextInput
              type="text"
              value={draft.category}
              onChange={(e) => setField("category", e.target.value)}
              aria-label="分类"
            />
          </Field>
          <Field label="关联生成器 key（可选）" className="w-full sm:w-48">
            <TextInput
              type="text"
              value={draft.toolKey}
              onChange={(e) => setField("toolKey", e.target.value)}
              aria-label="关联生成器 key"
            />
          </Field>
        </div>
        <Button
          type="submit"
          disabled={creating || !isTemplateDraftValid(draft)}
          variant="primary"
          className="self-start"
        >
          {creating ? "新建中…" : "新建模板"}
        </Button>
      </form>

      <section className="flex flex-col gap-3" aria-label="模板列表">
        <h2 className="font-serif text-lg text-ink">已存模板（{templates.length}）</h2>
        {templates.length === 0 ? (
          <p className="text-sm text-ink-soft">（暂无模板，先新建一个吧。）</p>
        ) : (
          <ul className="flex flex-col gap-2">
            {templates.map((t) => (
              <li
                key={t.id}
                className="flex items-start justify-between gap-4 rounded border border-line bg-bg p-3 text-sm"
              >
                <div className="min-w-0 flex-1">
                  <p className="font-serif text-base text-ink">{t.title}</p>
                  {t.category || t.tool_key ? (
                    <p className="text-xs text-ink-soft">
                      {[t.category, t.tool_key].filter(Boolean).join(" · ")}
                    </p>
                  ) : null}
                  <p className="mt-1 whitespace-pre-wrap text-ink-soft">
                    {t.body}
                  </p>
                </div>
                <Button
                  type="button"
                  onClick={() => void onDelete(t.id)}
                  variant="danger"
                  size="sm"
                  className="shrink-0"
                  aria-label={`删除模板 ${t.title}`}
                >
                  删除
                </Button>
              </li>
            ))}
          </ul>
        )}
      </section>
    </div>
  );
}
