import { useState, useEffect } from "react";
import Modal from "./Modal";
import { adminFetch } from "./adminApi";
import { useToast } from "./Toast";
import { Field, ErrorRow, FormFooter, HintRow, fieldCls } from "./FormPrimitives";

type Article = {
  id: string;
  title: string;
  subtitle: string | null;
  body: string;
  coverImage: string;
  caption: string | null;
  sortOrder: number;
  enabled: boolean;
};

type Props = {
  open: boolean;
  id: string | null;
  onClose: () => void;
  onSaved: () => void;
};

export default function ArticleForm({ open, id, onClose, onSaved }: Props) {
  const toast = useToast();
  const [currentId, setCurrentId] = useState<string | null>(null);
  const [title, setTitle] = useState("");
  const [subtitle, setSubtitle] = useState("");
  const [body, setBody] = useState("");
  const [caption, setCaption] = useState("");
  const [coverImage, setCoverImage] = useState("");
  const [sortOrder, setSortOrder] = useState(0);
  const [enabled, setEnabled] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");

  const isEdit = !!currentId;

  useEffect(() => {
    if (!open) return;
    setCurrentId(id);
    setError("");
    if (!id) {
      setTitle(""); setSubtitle(""); setBody(""); setCaption("");
      setCoverImage(""); setSortOrder(0); setEnabled(true);
      return;
    }
    adminFetch<Article[]>("/articles").then((articles) => {
      const article = articles.find((a) => a.id === id);
      if (article) {
        setTitle(article.title);
        setSubtitle(article.subtitle || "");
        setBody(article.body);
        setCaption(article.caption || "");
        setCoverImage(article.coverImage);
        setSortOrder(article.sortOrder);
        setEnabled(article.enabled);
      }
    });
  }, [open, id]);

  const handleUpload = async (file: File) => {
    if (!currentId) {
      setError("请先保存文章后再上传封面");
      return;
    }
    setError("");
    const formData = new FormData();
    formData.append("image", file);
    try {
      const data = await adminFetch<{ path: string }>(`/articles/${currentId}/upload`, {
        method: "POST",
        body: formData,
      });
      setCoverImage(data.path);
      toast.show("封面已上传");
      onSaved();
    } catch (e) {
      setError(e instanceof Error ? e.message : "上传失败");
    }
  };

  const handleSave = async () => {
    setError("");
    if (!title.trim()) return setError("请输入标题");
    if (!body.trim()) return setError("请输入正文");
    setSaving(true);
    try {
      const payload = {
        title: title.trim(),
        subtitle: subtitle.trim() || undefined,
        body: body.trim(),
        caption: caption.trim() || undefined,
        sortOrder,
        enabled,
      };
      if (isEdit) {
        await adminFetch(`/articles/${currentId}`, {
          method: "PUT",
          body: JSON.stringify(payload),
        });
        toast.show("已保存");
        onSaved();
        onClose();
      } else {
        const article = await adminFetch<Article>("/articles", {
          method: "POST",
          body: JSON.stringify(payload),
        });
        setCurrentId(article.id);
        toast.show("已创建，现在可以上传封面");
        onSaved();
      }
    } catch (e) {
      setError(e instanceof Error ? e.message : "保存失败");
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal
      open={open}
      onClose={onClose}
      size="lg"
      eyebrow={isEdit ? "Edit Article" : "New Article"}
      title={isEdit ? "编辑文章" : "添加文章"}
      subtitle={isEdit ? "调整内容与上传封面" : "先保存文章内容，再上传封面图"}
    >
      <div className="px-7 py-6 space-y-5">
        <Field label="标题" required>
          <input
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            placeholder="如：朝天宫"
            className={fieldCls}
          />
        </Field>

        <Field label="副标题">
          <input
            value={subtitle}
            onChange={(e) => setSubtitle(e.target.value)}
            placeholder="如：千年冶山，文脉绵延"
            className={fieldCls}
          />
        </Field>

        <Field label="正文" required hint="段落之间用空行分隔">
          <textarea
            value={body}
            onChange={(e) => setBody(e.target.value)}
            rows={14}
            placeholder="在这里撰写文章正文…"
            className={fieldCls + " font-mono text-[13px] leading-relaxed resize-y"}
          />
        </Field>

        <Field label="图片说明">
          <input
            value={caption}
            onChange={(e) => setCaption(e.target.value)}
            placeholder="如：1910 年的朝天宫大成殿旧影"
            className={fieldCls}
          />
        </Field>

        <div className="grid grid-cols-[auto_1fr] gap-5 items-end">
          <Field label="排序">
            <input
              type="number"
              value={sortOrder}
              onChange={(e) => setSortOrder(Number(e.target.value))}
              className={fieldCls + " w-28"}
            />
          </Field>
          <label className="flex items-center gap-2.5 cursor-pointer select-none pb-2.5">
            <input
              type="checkbox"
              checked={enabled}
              onChange={(e) => setEnabled(e.target.checked)}
              className="w-4 h-4 accent-[var(--jade)]"
            />
            <span className="text-sm text-[var(--text-secondary)]">启用（访客可访问）</span>
          </label>
        </div>

        {isEdit ? (
          <Field label="封面图片">
            <div className="rounded-xl border border-[var(--border-muted)] bg-white p-4">
              {coverImage && (
                <div className="w-full max-w-sm aspect-[4/3] rounded-lg bg-[var(--bg-paper)] overflow-hidden border border-[var(--border-muted)] mb-3">
                  <img src={coverImage} alt="封面" className="w-full h-full object-cover" />
                </div>
              )}
              <label className="cursor-pointer inline-flex items-center gap-2 text-[13px] text-[var(--text-secondary)] hover:text-[var(--terracotta)] transition-colors">
                <input
                  type="file"
                  accept="image/*"
                  onChange={(e) => e.target.files?.[0] && handleUpload(e.target.files[0])}
                  className="hidden"
                />
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M17 8l-5-5-5 5M12 3v12" />
                </svg>
                <span className="underline underline-offset-2 decoration-dotted">
                  {coverImage ? "更换封面" : "选择封面图片"}
                </span>
              </label>
            </div>
          </Field>
        ) : (
          <HintRow text="保存文章后，即可上传封面图片" />
        )}

        {error && <ErrorRow text={error} />}
      </div>

      <FormFooter onCancel={onClose} onSave={handleSave} saving={saving} primaryLabel={isEdit ? "保存" : "创建"} />
    </Modal>
  );
}
