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 Stamp = {
  id: string;
  name: string;
  note: string | null;
  imageColor: string;
  imageGrey: string;
  sortOrder: number;
  enabled: boolean;
};

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

export default function StampForm({ open, id, onClose, onSaved }: Props) {
  const toast = useToast();
  const [currentId, setCurrentId] = useState<string | null>(null);
  const [name, setName] = useState("");
  const [note, setNote] = useState("");
  const [sortOrder, setSortOrder] = useState(0);
  const [imageColor, setImageColor] = useState("");
  const [imageGrey, setImageGrey] = useState("");
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");

  const isEdit = !!currentId;

  useEffect(() => {
    if (!open) return;
    setCurrentId(id);
    setError("");
    if (!id) {
      setName("");
      setNote("");
      setSortOrder(0);
      setImageColor("");
      setImageGrey("");
      return;
    }
    adminFetch<Stamp[]>("/stamps").then((stamps) => {
      const stamp = stamps.find((s) => s.id === id);
      if (stamp) {
        setName(stamp.name);
        setNote(stamp.note || "");
        setSortOrder(stamp.sortOrder);
        setImageColor(stamp.imageColor);
        setImageGrey(stamp.imageGrey);
      }
    });
  }, [open, id]);

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

  const handleSave = async () => {
    setError("");
    if (!name.trim()) {
      setError("请输入图章名称");
      return;
    }
    setSaving(true);
    try {
      const payload = { name: name.trim(), note: note.trim() || undefined, sortOrder };
      if (isEdit) {
        await adminFetch(`/stamps/${currentId}`, {
          method: "PUT",
          body: JSON.stringify(payload),
        });
        toast.show("已保存");
        onSaved();
        onClose();
      } else {
        const stamp = await adminFetch<Stamp>("/stamps", {
          method: "POST",
          body: JSON.stringify(payload),
        });
        setCurrentId(stamp.id);
        toast.show("已创建，现在可以上传图片");
        onSaved();
      }
    } catch (e) {
      setError(e instanceof Error ? e.message : "保存失败");
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal
      open={open}
      onClose={onClose}
      size="md"
      eyebrow={isEdit ? "Edit Stamp" : "New Stamp"}
      title={isEdit ? "编辑图章" : "添加图章"}
      subtitle={isEdit ? "调整信息与上传图片" : "先保存基础信息，再上传图章图片"}
    >
      <div className="px-7 py-6 space-y-5">
        <Field label="名称" required>
          <input
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="如：朝天宫"
            className={fieldCls}
          />
        </Field>

        <Field label="备注">
          <textarea
            value={note}
            onChange={(e) => setNote(e.target.value)}
            rows={2}
            placeholder="选填"
            className={fieldCls + " resize-none"}
          />
        </Field>

        <Field label="排序" hint="数字小的在前">
          <input
            type="number"
            value={sortOrder}
            onChange={(e) => setSortOrder(Number(e.target.value))}
            className={fieldCls + " w-28"}
          />
        </Field>

        {isEdit ? (
          <div className="grid grid-cols-2 gap-5">
            <ImageSlot
              label="彩色图章"
              kind="color"
              image={imageColor}
              onUpload={(f) => handleUpload(f, "imageColor")}
            />
            <ImageSlot
              label="灰色图章"
              kind="grey"
              image={imageGrey}
              onUpload={(f) => handleUpload(f, "imageGrey")}
            />
          </div>
        ) : (
          <HintRow text="保存基础信息后，即可上传图章图片" />
        )}

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

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

function ImageSlot({
  label,
  kind,
  image,
  onUpload,
}: {
  label: string;
  kind: "color" | "grey";
  image: string;
  onUpload: (f: File) => void;
}) {
  return (
    <div>
      <label className="flex items-baseline justify-between mb-1.5">
        <span className="text-[13px] font-medium text-[var(--text-secondary)]">{label}</span>
        <span
          className="text-[9px] tracking-[0.3em] uppercase text-[var(--gold)]"
          style={{ fontFamily: "'Playfair Display', serif" }}
        >
          {kind === "color" ? "Color" : "Grey"}
        </span>
      </label>
      <div className="rounded-xl border border-[var(--border-muted)] bg-white p-4 flex flex-col items-center gap-3">
        <div className="w-20 h-20 rounded-full bg-[var(--bg-paper)] overflow-hidden flex items-center justify-center border border-[var(--border-muted)]">
          {image ? (
            <img src={image} alt="" className="w-[92%] h-[92%] object-contain" />
          ) : (
            <span className="text-[10px] tracking-[0.2em] uppercase text-[var(--text-muted)]/60">
              No image
            </span>
          )}
        </div>
        <label className="cursor-pointer text-[12px] text-[var(--text-secondary)] hover:text-[var(--terracotta)] transition-colors">
          <input
            type="file"
            accept="image/*"
            onChange={(e) => e.target.files?.[0] && onUpload(e.target.files[0])}
            className="hidden"
          />
          <span className="underline underline-offset-2 decoration-dotted">
            {image ? "更换图片" : "选择图片"}
          </span>
        </label>
      </div>
    </div>
  );
}
