import { useState, useEffect } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import {
  scanProjectEnv,
  getProjectEnvTools,
  saveProjectEnvTools,
  type Project,
  type EnvToolItem,
  type SaveEnvToolInput,
} from "../../lib/commands";
import { useUIStore } from "../../store/ui";

// ── 层元信息 ───────────────────────────────────────────────────────────────────

const LAYER_META: Record<number, { label: string; desc: string; color: string }> = {
  0: { label: "第 0 层", desc: "版本管理器",   color: "bg-purple-50 border-purple-200 text-purple-800" },
  1: { label: "第 1 层", desc: "语言运行时",   color: "bg-blue-50 border-blue-200 text-blue-800" },
  2: { label: "第 2 层", desc: "直接使用工具", color: "bg-green-50 border-green-200 text-green-800" },
  3: { label: "第 3 层", desc: "局部内置",     color: "bg-gray-50 border-gray-200 text-gray-700" },
};

// ── 主组件 ────────────────────────────────────────────────────────────────────

interface Props {
  project: Project;
  onClose: () => void;
}

export function ProjectEnvModal({ project, onClose }: Props) {
  const showToast = useUIStore((s) => s.showToast);
  const qc = useQueryClient();

  const [items, setItems] = useState<EnvToolItem[]>([]);
  const [scanning, setScanning] = useState(false);
  const [saving, setSaving] = useState(false);
  const [scanned, setScanned] = useState(false);

  // 加载已保存的数据
  const { data: savedItems = [], isLoading } = useQuery({
    queryKey: ["projectEnvTools", project.id],
    queryFn: () => getProjectEnvTools(project.id),
  });

  // 已保存数据加载后，若尚未扫描则显示已保存内容
  useEffect(() => {
    if (savedItems.length > 0 && !scanned) {
      setItems(savedItems);
    }
  }, [savedItems, scanned]);

  const handleScan = async (env: "win" | "wsl") => {
    setScanning(true);
    try {
      const result = await scanProjectEnv(project.id, env);
      setItems(result);
      setScanned(true);
      showToast(`扫描完成，发现 ${result.length} 项工具 ✓`);
    } catch (e) {
      showToast(`❌ ${e}`);
    } finally {
      setScanning(false);
    }
  };

  const handleRemove = (id: string) => {
    setItems((prev) => prev.filter((item) => item.id !== id));
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      const inputs: SaveEnvToolInput[] = items.map((item) => ({
        id: item.id,
        layer: item.layer,
        name: item.name,
        source: item.source,
        version: item.version,
        note: item.note,
      }));
      await saveProjectEnvTools(project.id, inputs);
      qc.invalidateQueries({ queryKey: ["projectEnvTools", project.id] });
      showToast("已保存 ✓");
      onClose();
    } catch (e) {
      showToast(`❌ ${e}`);
    } finally {
      setSaving(false);
    }
  };

  // 按层分组
  const grouped = [0, 1, 2, 3].reduce<Record<number, EnvToolItem[]>>((acc, layer) => {
    const layerItems = items.filter((item) => item.layer === layer);
    if (layerItems.length > 0) acc[layer] = layerItems;
    return acc;
  }, {});

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
      <div className="bg-white rounded-xl shadow-xl w-[560px] max-h-[80vh] flex flex-col overflow-hidden">
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-100">
          <div>
            <h2 className="font-semibold text-gray-800">环境工具</h2>
            <p className="text-xs text-gray-400 mt-0.5">{project.name}</p>
          </div>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-600 text-xl leading-none">×</button>
        </div>

        {/* Scan buttons */}
        <div className="flex gap-2 px-6 py-3 border-b border-gray-50 bg-gray-50">
          <span className="text-xs text-gray-500 self-center mr-1">扫描目录：</span>
          {project.win_path && (
            <button
              onClick={() => handleScan("win")}
              disabled={scanning}
              className="px-3 py-1.5 rounded-lg text-xs border border-blue-200 text-blue-700 hover:bg-blue-50 disabled:opacity-50 transition-colors"
            >
              {scanning ? "扫描中…" : "💻 WIN 环境"}
            </button>
          )}
          {project.wsl_path && (
            <button
              onClick={() => handleScan("wsl")}
              disabled={scanning}
              className="px-3 py-1.5 rounded-lg text-xs border border-green-200 text-green-700 hover:bg-green-50 disabled:opacity-50 transition-colors"
            >
              {scanning ? "扫描中…" : "🐧 WSL 环境"}
            </button>
          )}
          <span className="text-xs text-gray-400 self-center ml-auto">
            扫描后结果自动替换，确认后点保存
          </span>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto px-6 py-4">
          {isLoading && !scanned ? (
            <p className="text-sm text-gray-400 text-center py-8">加载中…</p>
          ) : items.length === 0 ? (
            <div className="text-center py-12 text-gray-400">
              <p className="text-3xl mb-3">🔍</p>
              <p className="text-sm">点击上方「扫描」按钮分析项目目录</p>
              <p className="text-xs mt-1 text-gray-300">会根据配置文件自动推断技术栈和工具链</p>
            </div>
          ) : (
            <div className="space-y-5">
              {/* 三层模型说明 */}
              <div className="flex flex-wrap gap-1.5 text-xs">
                {[0, 1, 2, 3].map((l) => (
                  <span key={l} className={`px-2 py-0.5 rounded border ${LAYER_META[l].color}`}>
                    {LAYER_META[l].label} {LAYER_META[l].desc}
                  </span>
                ))}
              </div>

              {/* 分层展示 */}
              {Object.entries(grouped).map(([layerStr, layerItems]) => {
                const layer = Number(layerStr);
                const meta = LAYER_META[layer];
                return (
                  <div key={layer}>
                    <div className="flex items-center gap-2 mb-2">
                      <span className={`text-xs font-semibold px-2 py-0.5 rounded border ${meta.color}`}>
                        {meta.label} {meta.desc}
                      </span>
                    </div>
                    <div className="space-y-1.5">
                      {layerItems.map((item) => (
                        <EnvToolRow
                          key={item.id}
                          item={item}
                          onRemove={() => handleRemove(item.id)}
                        />
                      ))}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-between px-6 py-4 border-t border-gray-100">
          <span className="text-xs text-gray-400">{items.length} 项工具</span>
          <div className="flex gap-3">
            <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={saving || items.length === 0}
              className="px-4 py-2 rounded-lg text-sm bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-50"
            >
              {saving ? "保存中…" : "保存"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── 工具行 ────────────────────────────────────────────────────────────────────

function EnvToolRow({ item, onRemove }: { item: EnvToolItem; onRemove: () => void }) {
  return (
    <div className="flex items-center gap-3 px-3 py-2 rounded-lg bg-white border border-gray-100 hover:border-gray-200 group transition-colors">
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2 flex-wrap">
          <span className="text-sm font-medium text-gray-800">{item.name}</span>
          {item.source && (
            <span className="text-xs px-1.5 py-0.5 rounded bg-slate-100 text-slate-500">
              via {item.source}
            </span>
          )}
          {item.version && (
            <span className="text-xs text-gray-400 font-mono">{item.version}</span>
          )}
        </div>
        {item.note && (
          <p className="text-xs text-gray-400 mt-0.5">{item.note}</p>
        )}
      </div>
      <button
        onClick={onRemove}
        className="opacity-0 group-hover:opacity-100 text-xs text-red-400 hover:text-red-600 transition-all shrink-0"
      >
        移除
      </button>
    </div>
  );
}
