import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import {
  getSourceProjects,
  getSourceCategories,
  deleteSourceProject,
  type SourceProject,
} from "../../lib/commands";
import { useUIStore } from "../../store/ui";
import { SourceProjectDetail } from "./SourceProjectDetail";
import { ProjectFormModal } from "./ProjectFormModal";
import { CategoryManager } from "./CategoryManager";

const LANG_COLORS: Record<string, string> = {
  Go: "#00ADD8",
  Rust: "#DEA584",
  TypeScript: "#3178C6",
  JavaScript: "#F1E05A",
  Python: "#3572A5",
  Java: "#B07219",
  "C++": "#F34B7D",
  C: "#555555",
  Ruby: "#701516",
  PHP: "#4F5D95",
  Swift: "#F05138",
  Kotlin: "#A97BFF",
  Dart: "#00B4AB",
  Zig: "#F7A41D",
  Elixir: "#6E4A7E",
};

function formatRelativeTime(dateStr?: string): string {
  if (!dateStr) return "";
  const now = new Date();
  const date = new Date(dateStr + "Z");
  const diff = now.getTime() - date.getTime();
  const minutes = Math.floor(diff / 60000);
  if (minutes < 1) return "刚刚";
  if (minutes < 60) return `${minutes} 分钟前`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return `${hours} 小时前`;
  const days = Math.floor(hours / 24);
  if (days < 30) return `${days} 天前`;
  const months = Math.floor(days / 30);
  if (months < 12) return `${months} 个月前`;
  return `${Math.floor(months / 12)} 年前`;
}

function formatSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
}

export { LANG_COLORS, formatRelativeTime, formatSize };

export function SourceLibraryPage() {
  const [selectedProject, setSelectedProject] = useState<SourceProject | null>(null);
  const [filterCategory, setFilterCategory] = useState<string>("");
  const [filterLanguage, setFilterLanguage] = useState<string>("");
  const [search, setSearch] = useState("");
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showCategoryManager, setShowCategoryManager] = useState(false);
  const [deleteTarget, setDeleteTarget] = useState<SourceProject | null>(null);

  const qc = useQueryClient();
  const showToast = useUIStore((s) => s.showToast);

  const { data: projects = [] } = useQuery({
    queryKey: ["source_projects", filterCategory, search],
    queryFn: () => getSourceProjects(filterCategory || undefined, search || undefined),
  });

  const { data: categories = [] } = useQuery({
    queryKey: ["source_categories"],
    queryFn: getSourceCategories,
  });

  // 提取所有语言供筛选
  const languages = [...new Set(projects.map((p) => p.language).filter(Boolean))] as string[];

  const filtered = filterLanguage
    ? projects.filter((p) => p.language === filterLanguage)
    : projects;

  const handleDelete = async () => {
    if (!deleteTarget) return;
    try {
      await deleteSourceProject(deleteTarget.id);
      qc.invalidateQueries({ queryKey: ["source_projects"] });
      showToast("已删除");
      setDeleteTarget(null);
      if (selectedProject?.id === deleteTarget.id) setSelectedProject(null);
    } catch (e) {
      showToast(`删除失败: ${e}`);
    }
  };

  // 详情视图
  if (selectedProject) {
    return (
      <SourceProjectDetail
        project={selectedProject}
        categories={categories}
        onBack={() => setSelectedProject(null)}
        onUpdated={() => {
          qc.invalidateQueries({ queryKey: ["source_projects"] });
        }}
      />
    );
  }

  return (
    <div className="h-full overflow-y-auto">
      <div className="max-w-5xl mx-auto px-6 py-6">
        {/* Header */}
        <div className="flex items-center justify-between mb-6">
          <div>
            <h1 className="text-xl font-bold text-gray-900">源码库</h1>
            <p className="text-sm text-gray-500 mt-1">收藏与管理优秀开源项目源码</p>
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={() => setShowCategoryManager(true)}
              className="px-3 py-1.5 text-sm border border-gray-300 rounded-lg text-gray-600 hover:bg-gray-50"
            >
              管理分类
            </button>
            <button
              onClick={() => setShowCreateModal(true)}
              className="px-4 py-1.5 text-sm bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 font-medium"
            >
              + 新建项目
            </button>
          </div>
        </div>

        {/* 搜索 + 筛选 */}
        <div className="flex items-center gap-3 mb-4">
          <div className="flex-1 relative">
            <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
            </svg>
            <input
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="搜索源码项目..."
              className="w-full pl-9 pr-3 py-2 border border-gray-300 rounded-lg text-sm outline-none focus:ring-2 focus:ring-emerald-200 focus:border-emerald-400"
            />
          </div>
          <select
            value={filterCategory}
            onChange={(e) => setFilterCategory(e.target.value)}
            className="px-3 py-2 border border-gray-300 rounded-lg text-sm text-gray-700 outline-none focus:ring-2 focus:ring-emerald-200"
          >
            <option value="">全部分类</option>
            {categories.map((c) => (
              <option key={c.id} value={c.id}>{c.icon} {c.name}</option>
            ))}
          </select>
          <select
            value={filterLanguage}
            onChange={(e) => setFilterLanguage(e.target.value)}
            className="px-3 py-2 border border-gray-300 rounded-lg text-sm text-gray-700 outline-none focus:ring-2 focus:ring-emerald-200"
          >
            <option value="">全部语言</option>
            {languages.map((l) => (
              <option key={l} value={l}>{l}</option>
            ))}
          </select>
        </div>

        {/* 项目数统计 */}
        <div className="text-xs text-gray-500 mb-3">
          共 <span className="font-semibold text-gray-700">{filtered.length}</span> 个源码项目
        </div>

        {/* 项目列表（GitHub 风格） */}
        <div className="border border-gray-200 rounded-lg divide-y divide-gray-200 bg-white">
          {filtered.length === 0 && (
            <div className="px-6 py-12 text-center text-gray-400 text-sm">
              {search || filterCategory || filterLanguage
                ? "没有匹配的项目"
                : "还没有源码项目，点击「+ 新建项目」开始收藏"}
            </div>
          )}
          {filtered.map((p) => (
            <div
              key={p.id}
              className="px-5 py-4 hover:bg-gray-50 transition-colors group"
            >
              <div className="flex items-start justify-between">
                <div className="flex-1 min-w-0">
                  {/* 项目名 + 描述 */}
                  <div className="flex items-center gap-2 mb-1">
                    <button
                      onClick={() => setSelectedProject(p)}
                      className="text-base font-semibold text-blue-600 hover:underline truncate"
                    >
                      {p.name}
                    </button>
                    {p.category_name && (
                      <span className="shrink-0 px-2 py-0.5 text-xs rounded-full border border-gray-200 text-gray-500">
                        {p.category_name}
                      </span>
                    )}
                  </div>
                  {p.description && (
                    <p className="text-sm text-gray-600 mb-2 line-clamp-1">{p.description}</p>
                  )}
                  {/* 元信息行 */}
                  <div className="flex items-center gap-4 text-xs text-gray-500">
                    {p.language && (
                      <span className="flex items-center gap-1">
                        <span
                          className="w-2.5 h-2.5 rounded-full inline-block"
                          style={{ backgroundColor: LANG_COLORS[p.language] || "#959DA5" }}
                        />
                        {p.language}
                      </span>
                    )}
                    {(p.version_count ?? 0) > 0 && (
                      <span>{p.version_count} 个版本</span>
                    )}
                    {p.updated_at && (
                      <span>{formatRelativeTime(p.updated_at)}</span>
                    )}
                  </div>
                </div>
                {/* 操作按钮 */}
                <button
                  onClick={(e) => { e.stopPropagation(); setDeleteTarget(p); }}
                  className="shrink-0 p-1.5 rounded-md text-gray-300 hover:text-red-500 hover:bg-red-50 opacity-0 group-hover:opacity-100 transition-all"
                  title="删除项目"
                >
                  <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 16 16">
                    <path d="M11 1.75V3h2.25a.75.75 0 010 1.5H2.75a.75.75 0 010-1.5H5V1.75C5 .784 5.784 0 6.75 0h2.5C10.216 0 11 .784 11 1.75zM4.496 6.675a.75.75 0 10-1.492.15l.66 6.6A1.75 1.75 0 005.405 15h5.19c.9 0 1.652-.681 1.741-1.576l.66-6.6a.75.75 0 10-1.492-.149l-.66 6.6a.25.25 0 01-.249.225h-5.19a.25.25 0 01-.249-.225l-.66-6.6z" />
                  </svg>
                </button>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* 新建项目弹窗 */}
      {showCreateModal && (
        <ProjectFormModal
          categories={categories}
          onClose={() => setShowCreateModal(false)}
          onSaved={() => {
            setShowCreateModal(false);
            qc.invalidateQueries({ queryKey: ["source_projects"] });
          }}
        />
      )}

      {/* 分类管理 */}
      {showCategoryManager && (
        <CategoryManager
          onClose={() => setShowCategoryManager(false)}
        />
      )}

      {/* 删除确认 */}
      {deleteTarget && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-2xl w-80 p-6 space-y-4">
            <h2 className="text-base font-semibold text-gray-800">删除源码项目</h2>
            <p className="text-sm text-gray-600">
              确定删除「<span className="font-medium">{deleteTarget.name}</span>」及其所有版本文件？此操作不可撤销。
            </p>
            <div className="flex justify-end gap-3">
              <button onClick={() => setDeleteTarget(null)} className="px-4 py-2 rounded-lg text-sm border border-gray-200 text-gray-600 hover:bg-gray-50">取消</button>
              <button onClick={handleDelete} className="px-4 py-2 rounded-lg text-sm bg-red-600 text-white hover:bg-red-700">删除</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
