import { useState } from "react";
import {
  createSourceProject,
  updateSourceProject,
  type SourceProject,
  type SourceCategory,
} from "../../lib/commands";
import { useUIStore } from "../../store/ui";

interface Props {
  categories: SourceCategory[];
  project?: SourceProject;
  onClose: () => void;
  onSaved: () => void;
}

export function ProjectFormModal({ categories, project, onClose, onSaved }: Props) {
  const [name, setName] = useState(project?.name ?? "");
  const [description, setDescription] = useState(project?.description ?? "");
  const [categoryId, setCategoryId] = useState(project?.category_id ?? "");
  const [language, setLanguage] = useState(project?.language ?? "");
  const [repoUrl, setRepoUrl] = useState(project?.repo_url ?? "");
  const [introduction, setIntroduction] = useState(project?.introduction ?? "");
  const [saving, setSaving] = useState(false);
  const showToast = useUIStore((s) => s.showToast);

  const isEdit = !!project;

  const handleSave = async () => {
    if (!name.trim()) return;
    setSaving(true);
    try {
      if (isEdit) {
        await updateSourceProject(
          project.id,
          name.trim(),
          description || undefined,
          categoryId || undefined,
          language || undefined,
          repoUrl || undefined,
          introduction || undefined,
          project.notes || undefined,
        );
      } else {
        await createSourceProject(
          name.trim(),
          description || undefined,
          categoryId || undefined,
          language || undefined,
          repoUrl || undefined,
          introduction || undefined,
        );
      }
      showToast(isEdit ? "已更新" : "已创建");
      onSaved();
    } catch (e) {
      showToast(`保存失败: ${e}`);
    } finally {
      setSaving(false);
    }
  };

  const inputCls = "w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-emerald-200";

  return (
    <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50">
      <div className="bg-white rounded-xl shadow-2xl w-[480px] max-h-[85vh] overflow-y-auto p-6 space-y-4">
        <div className="flex items-center justify-between">
          <h2 className="text-base font-semibold text-gray-800">{isEdit ? "编辑项目" : "新建源码项目"}</h2>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-600 text-xl leading-none">&times;</button>
        </div>

        <div className="space-y-3">
          <div>
            <label className="block text-xs font-medium text-gray-600 mb-1">项目名称 *</label>
            <input value={name} onChange={(e) => setName(e.target.value)} placeholder="如 gin、next.js" className={inputCls} autoFocus />
          </div>
          <div>
            <label className="block text-xs font-medium text-gray-600 mb-1">简要描述</label>
            <input value={description} onChange={(e) => setDescription(e.target.value)} placeholder="一句话描述项目" className={inputCls} />
          </div>
          <div className="flex gap-3">
            <div className="flex-1">
              <label className="block text-xs font-medium text-gray-600 mb-1">分类</label>
              <select value={categoryId} onChange={(e) => setCategoryId(e.target.value)} className={inputCls}>
                <option value="">未分类</option>
                {categories.map((c) => (
                  <option key={c.id} value={c.id}>{c.icon} {c.name}</option>
                ))}
              </select>
            </div>
            <div className="flex-1">
              <label className="block text-xs font-medium text-gray-600 mb-1">主语言</label>
              <input value={language} onChange={(e) => setLanguage(e.target.value)} placeholder="如 Go、Rust、TypeScript" className={inputCls} />
              <p className="text-xs text-gray-400 mt-0.5">导入版本时可自动检测</p>
            </div>
          </div>
          <div>
            <label className="block text-xs font-medium text-gray-600 mb-1">仓库地址</label>
            <input value={repoUrl} onChange={(e) => setRepoUrl(e.target.value)} placeholder="https://github.com/..." className={inputCls} />
          </div>
          <div>
            <label className="block text-xs font-medium text-gray-600 mb-1">项目介绍</label>
            <textarea
              value={introduction}
              onChange={(e) => setIntroduction(e.target.value)}
              rows={4}
              placeholder="手写项目介绍（留空则展示 README）"
              className={`${inputCls} resize-none`}
            />
          </div>
        </div>

        <div className="flex justify-end gap-3 pt-2">
          <button onClick={onClose} className="px-4 py-2 rounded-lg text-sm border border-gray-200 text-gray-600 hover:bg-gray-50">取消</button>
          <button
            onClick={handleSave}
            disabled={!name.trim() || saving}
            className="px-4 py-2 rounded-lg text-sm bg-emerald-600 text-white hover:bg-emerald-700 disabled:opacity-50"
          >
            {saving ? "保存中..." : isEdit ? "更新" : "创建"}
          </button>
        </div>
      </div>
    </div>
  );
}
