import { useState } from "react";
import { useParams, useNavigate } from "react-router";
import {
  Users as UsersIcon,
  MapPin,
  Box,
  Plus,
  Search,
  Star,
  Trash2,
  Filter,
  User,
  Loader2,
} from "lucide-react";
import { useGlobalAssets, useCreateAsset, useToggleFavorite, useDeleteAsset } from "../../hooks/useAssets";

type AssetTypeStr = "character" | "scene" | "prop";
type LibraryType = "personal" | "team";

const assetTypes = [
  { id: "character" as AssetTypeStr, label: "角色库", icon: UsersIcon },
  { id: "scene" as AssetTypeStr, label: "场景库", icon: MapPin },
  { id: "prop" as AssetTypeStr, label: "道具库", icon: Box },
];

export function AssetsManagement() {
  const navigate = useNavigate();
  const params = useParams();
  const activeType = ((params["*"]?.split("/")[0]) || "character") as AssetTypeStr;

  const [libraryType, setLibraryType] = useState<LibraryType>("personal");
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedTags, setSelectedTags] = useState<string[]>([]);
  const [showCreateModal, setShowCreateModal] = useState(false);

  // create form
  const [formName, setFormName] = useState("");
  const [formDesc, setFormDesc] = useState("");
  const [formTags, setFormTags] = useState("");
  const [formLibrary, setFormLibrary] = useState<LibraryType>("personal");

  const { data: assets = [], isLoading } = useGlobalAssets(activeType, libraryType);
  const createAsset = useCreateAsset(activeType, libraryType);
  const toggleFavorite = useToggleFavorite(activeType, libraryType);
  const deleteAsset = useDeleteAsset(activeType, libraryType);

  const filteredAssets = assets.filter((a) => {
    if (searchTerm && !a.name.toLowerCase().includes(searchTerm.toLowerCase())) return false;
    if (selectedTags.length > 0 && !selectedTags.some((t) => a.tags.includes(t))) return false;
    return true;
  });

  const allTags = Array.from(new Set(assets.flatMap((a) => a.tags)));

  const toggleTag = (tag: string) =>
    setSelectedTags((prev) => (prev.includes(tag) ? prev.filter((t) => t !== tag) : [...prev, tag]));

  const handleCreate = async () => {
    await createAsset.mutateAsync({
      name: formName,
      assetType: activeType,
      libraryType: formLibrary,
      tags: formTags,
      description: formDesc,
    });
    setFormName(""); setFormDesc(""); setFormTags(""); setFormLibrary("personal");
    setShowCreateModal(false);
  };

  return (
    <div className="h-full flex flex-col bg-background">
      {/* Sub Navigation */}
      <div className="border-b border-border bg-card px-6 py-4">
        <div className="flex items-center gap-4 mb-4">
          <div className="flex items-center gap-2 p-1 rounded-lg bg-muted">
            <button
              onClick={() => setLibraryType("personal")}
              className={`px-4 py-1.5 rounded-md text-sm transition-colors ${libraryType === "personal" ? "bg-card text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground"}`}
            >
              <div className="flex items-center gap-2"><User className="w-3 h-3" />个人库</div>
            </button>
            <button
              onClick={() => setLibraryType("team")}
              className={`px-4 py-1.5 rounded-md text-sm transition-colors ${libraryType === "team" ? "bg-card text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground"}`}
            >
              <div className="flex items-center gap-2"><UsersIcon className="w-3 h-3" />团队库</div>
            </button>
          </div>
        </div>

        <div className="flex items-center gap-1 mb-4">
          {assetTypes.map((type) => (
            <button
              key={type.id}
              onClick={() => navigate(`/assets/${type.id}`)}
              className={`px-4 py-2 rounded-lg text-sm flex items-center gap-2 transition-all ${
                activeType === type.id
                  ? "bg-accent text-accent-foreground font-medium"
                  : "text-muted-foreground hover:text-foreground hover:bg-muted"
              }`}
            >
              <type.icon className="w-4 h-4" />
              {type.label}
            </button>
          ))}
        </div>

        <div className="flex items-center gap-4">
          <div className="flex-1 max-w-md relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
            <input
              type="text"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              placeholder="搜索资源名称..."
              className="w-full pl-9 pr-4 py-2 rounded-lg border border-border bg-background text-sm text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/20"
            />
          </div>
          <button
            onClick={() => setShowCreateModal(true)}
            className="px-4 py-2 rounded-lg bg-gradient-to-r from-[#5b5ff9] to-[#8b5ff9] text-white hover:shadow-md transition-all text-sm flex items-center gap-2"
          >
            <Plus className="w-4 h-4" />
            新建{assetTypes.find((t) => t.id === activeType)?.label.replace("库", "")}
          </button>
        </div>
      </div>

      {/* Content */}
      <div className="flex-1 overflow-auto p-6">
        <div className="max-w-7xl mx-auto">
          {allTags.length > 0 && (
            <div className="mb-6 p-4 rounded-xl border border-border bg-card">
              <div className="flex items-center gap-2 mb-3">
                <Filter className="w-4 h-4 text-muted-foreground" />
                <span className="text-sm font-medium text-foreground">标签筛选</span>
              </div>
              <div className="flex flex-wrap gap-2">
                {allTags.map((tag) => (
                  <button key={tag} onClick={() => toggleTag(tag)}
                    className={`px-3 py-1.5 rounded-lg text-xs transition-colors ${selectedTags.includes(tag) ? "bg-primary text-white" : "bg-muted text-foreground hover:bg-muted-foreground/10"}`}>
                    {tag}
                  </button>
                ))}
                {selectedTags.length > 0 && (
                  <button onClick={() => setSelectedTags([])} className="px-3 py-1.5 rounded-lg text-xs text-destructive hover:bg-destructive/10">清除</button>
                )}
              </div>
            </div>
          )}

          {isLoading && (
            <div className="text-center py-16"><Loader2 className="w-8 h-8 animate-spin text-muted-foreground mx-auto" /></div>
          )}

          {!isLoading && filteredAssets.length > 0 ? (
            <div className={`grid gap-4 ${activeType === "character" ? "grid-cols-5" : "grid-cols-4"}`}>
              {filteredAssets.map((asset) => (
                <div key={asset.id} className="rounded-xl border border-border bg-card overflow-hidden hover:shadow-md transition-all group">
                  <div className={`${activeType === "character" ? "aspect-[3/4]" : "aspect-video"} bg-muted relative overflow-hidden`}>
                    {asset.imageUrl ? (
                      <img src={asset.imageUrl} alt={asset.name} className="w-full h-full object-cover group-hover:scale-105 transition-transform" />
                    ) : (
                      <div className="w-full h-full flex items-center justify-center text-muted-foreground">
                        {activeType === "character" ? <UsersIcon className="w-12 h-12" /> : activeType === "scene" ? <MapPin className="w-12 h-12" /> : <Box className="w-12 h-12" />}
                      </div>
                    )}
                    <button
                      onClick={() => toggleFavorite.mutate(asset.id)}
                      className="absolute top-2 right-2 w-7 h-7 rounded-full bg-card/80 backdrop-blur-sm flex items-center justify-center hover:bg-card transition-colors"
                    >
                      <Star className={`w-4 h-4 ${asset.favorite ? "fill-yellow-400 text-yellow-400" : "text-muted-foreground"}`} />
                    </button>
                  </div>

                  <div className="p-3">
                    <h3 className="font-medium text-foreground mb-2 line-clamp-1">{asset.name}</h3>
                    <div className="flex flex-wrap gap-1 mb-3">
                      {asset.tags.slice(0, 2).map((tag) => (
                        <span key={tag} className="px-2 py-0.5 rounded bg-muted text-xs text-foreground">{tag}</span>
                      ))}
                      {asset.tags.length > 2 && (
                        <span className="px-2 py-0.5 rounded bg-muted text-xs text-muted-foreground">+{asset.tags.length - 2}</span>
                      )}
                    </div>
                    {asset.description && <div className="text-xs text-muted-foreground mb-3 line-clamp-1">{asset.description}</div>}
                    <div className="flex gap-2">
                      <button
                        onClick={() => deleteAsset.mutate(asset.id)}
                        className="flex-1 px-3 py-1.5 rounded-lg border border-border bg-background text-destructive hover:bg-destructive/10 transition-colors text-xs flex items-center justify-center gap-1"
                      >
                        <Trash2 className="w-3 h-3" />
                        删除
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ) : !isLoading && (
            <div className="text-center py-16">
              {activeType === "character" && <UsersIcon className="w-16 h-16 text-muted-foreground mx-auto mb-4" />}
              {activeType === "scene" && <MapPin className="w-16 h-16 text-muted-foreground mx-auto mb-4" />}
              {activeType === "prop" && <Box className="w-16 h-16 text-muted-foreground mx-auto mb-4" />}
              <p className="text-muted-foreground mb-2">
                暂无{assetTypes.find((t) => t.id === activeType)?.label.replace("库", "")}
              </p>
              <button onClick={() => setShowCreateModal(true)} className="text-sm text-primary hover:underline">立即创建</button>
            </div>
          )}
        </div>
      </div>

      {/* Create Modal */}
      {showCreateModal && (
        <div className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center z-50 p-8">
          <div className="bg-card rounded-2xl border border-border p-6 max-w-lg w-full">
            <h2 className="text-xl font-semibold text-foreground mb-6">
              新建{assetTypes.find((t) => t.id === activeType)?.label.replace("库", "")}
            </h2>

            <div className="space-y-4 mb-6">
              <div>
                <label className="block text-sm font-medium text-foreground mb-2">名称</label>
                <input value={formName} onChange={(e) => setFormName(e.target.value)} type="text" placeholder="输入名称"
                  className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/20" />
              </div>
              <div>
                <label className="block text-sm font-medium text-foreground mb-2">标签（逗号分隔）</label>
                <input value={formTags} onChange={(e) => setFormTags(e.target.value)} type="text" placeholder="如：女主角,都市,现代"
                  className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/20" />
              </div>
              <div>
                <label className="block text-sm font-medium text-foreground mb-2">描述</label>
                <textarea value={formDesc} onChange={(e) => setFormDesc(e.target.value)} rows={3} placeholder="输入描述"
                  className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/20 resize-none" />
              </div>
              <div>
                <label className="block text-sm font-medium text-foreground mb-2">库类型</label>
                <select value={formLibrary} onChange={(e) => setFormLibrary(e.target.value as LibraryType)}
                  className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary/20">
                  <option value="personal">个人库</option>
                  <option value="team">团队库</option>
                </select>
              </div>
            </div>

            <div className="flex gap-3">
              <button onClick={() => setShowCreateModal(false)}
                className="flex-1 px-4 py-2 rounded-lg border border-border bg-card text-foreground hover:bg-muted transition-colors">
                取消
              </button>
              <button onClick={handleCreate} disabled={createAsset.isPending || !formName.trim()}
                className="flex-1 px-4 py-2 rounded-lg bg-gradient-to-r from-[#5b5ff9] to-[#8b5ff9] text-white hover:shadow-md transition-all disabled:opacity-50 flex items-center justify-center gap-2">
                {createAsset.isPending && <Loader2 className="w-4 h-4 animate-spin" />}
                创建
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
