import { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { adminFetch } from "./adminApi";

type Stamp = {
  id: string;
  name: string;
  note: string | null;
  imageColor: string;
  imageGrey: string;
  sortOrder: number;
  enabled: boolean;
};

export default function StampForm() {
  const { id } = useParams();
  const navigate = useNavigate();
  const isEdit = !!id;

  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("");

  useEffect(() => {
    if (!id) 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);
      }
    });
  }, [id]);

  const handleUpload = async (file: File, field: "imageColor" | "imageGrey") => {
    if (!id) {
      setError("请先保存图章后再上传图片");
      return;
    }
    const formData = new FormData();
    formData.append("image", file);
    formData.append("field", field);
    const data = await adminFetch<{ path: string }>(`/stamps/${id}/upload`, {
      method: "POST",
      body: formData,
    });
    if (field === "imageColor") setImageColor(data.path);
    else setImageGrey(data.path);
  };

  const handleSave = async () => {
    setError("");
    if (!name.trim()) {
      setError("请输入图章名称");
      return;
    }
    setSaving(true);
    try {
      if (isEdit) {
        await adminFetch(`/stamps/${id}`, {
          method: "PUT",
          body: JSON.stringify({ name: name.trim(), note: note.trim() || undefined, sortOrder }),
        });
      } else {
        const stamp = await adminFetch<Stamp>("/stamps", {
          method: "POST",
          body: JSON.stringify({ name: name.trim(), note: note.trim() || undefined, sortOrder }),
        });
        navigate(`/admin/stamps/${stamp.id}/edit`, { replace: true });
        return;
      }
      navigate("/admin/stamps");
    } catch (e) {
      setError(e instanceof Error ? e.message : "保存失败");
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="max-w-xl">
      <h2 className="text-lg font-semibold text-gray-800 mb-4">
        {isEdit ? "编辑图章" : "添加图章"}
      </h2>

      <div className="bg-white rounded-lg border border-gray-200 p-5 space-y-4">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">名称</label>
          <input
            value={name}
            onChange={(e) => setName(e.target.value)}
            className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm
              focus:outline-none focus:ring-1 focus:ring-blue-500"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">备注</label>
          <textarea
            value={note}
            onChange={(e) => setNote(e.target.value)}
            rows={2}
            className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm
              focus:outline-none focus:ring-1 focus:ring-blue-500"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">排序</label>
          <input
            type="number"
            value={sortOrder}
            onChange={(e) => setSortOrder(Number(e.target.value))}
            className="w-24 px-3 py-2 border border-gray-300 rounded-md text-sm
              focus:outline-none focus:ring-1 focus:ring-blue-500"
          />
        </div>

        {/* Image uploads - only available after saving */}
        {isEdit && (
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">彩色图章</label>
              {imageColor && (
                <img src={imageColor} alt="彩色" className="w-20 h-20 object-contain bg-gray-50 rounded mb-2" />
              )}
              <input
                type="file"
                accept="image/*"
                onChange={(e) => e.target.files?.[0] && handleUpload(e.target.files[0], "imageColor")}
                className="text-xs text-gray-500"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">灰色图章</label>
              {imageGrey && (
                <img src={imageGrey} alt="灰色" className="w-20 h-20 object-contain bg-gray-50 rounded mb-2" />
              )}
              <input
                type="file"
                accept="image/*"
                onChange={(e) => e.target.files?.[0] && handleUpload(e.target.files[0], "imageGrey")}
                className="text-xs text-gray-500"
              />
            </div>
          </div>
        )}

        {!isEdit && (
          <p className="text-xs text-gray-400">保存后可上传图章图片</p>
        )}

        {error && <p className="text-sm text-red-500">{error}</p>}

        <div className="flex gap-3 pt-2">
          <button
            onClick={handleSave}
            disabled={saving}
            className="px-4 py-2 bg-blue-600 text-white text-sm rounded-md
              hover:bg-blue-700 disabled:opacity-50"
          >
            {saving ? "保存中..." : "保存"}
          </button>
          <button
            onClick={() => navigate("/admin/stamps")}
            className="px-4 py-2 border border-gray-300 text-gray-600 text-sm rounded-md hover:bg-gray-50"
          >
            取消
          </button>
        </div>
      </div>
    </div>
  );
}
