import { useState } from "react";
import { useNavigate, useParams } from "react-router";
import {
  ArrowRight, Box, Sparkles, Users, MapPin, Plus,
  Edit2, Trash2, Upload, X, Check, RefreshCw, Loader2,
} from "lucide-react";
import { useGlobalAssets, useCreateAsset, useDeleteAsset } from "../../hooks/useAssets";
import type { GlobalAsset } from "../../lib/api/assets";

type SettingsTab = "characters" | "scenes" | "props";

interface EditForm {
  id?: string;
  name: string;
  category: string;
  description: string;
  imageUrl: string;
}

const CATEGORIES = ["首饰", "文件", "配饰", "文具", "饮品", "电子设备", "武器", "交通工具", "其他"];

export function PropsGeneration() {
  const navigate = useNavigate();
  const { projectId } = useParams();
  const numProjectId = projectId ?? "";

  const { data: props = [], isLoading } = useGlobalAssets("prop", "personal");
  const createAsset = useCreateAsset("prop", "personal");
  const deleteAsset = useDeleteAsset("prop", "personal");

  const [activeTab, setActiveTab] = useState<SettingsTab>("props");
  const [showModal, setShowModal] = useState(false);
  const [editForm, setEditForm] = useState<EditForm | null>(null);

  const settingsTabs = [
    { id: "characters" as SettingsTab, label: "角色", icon: Users, path: `/project/${projectId}/characters` },
    { id: "scenes" as SettingsTab, label: "场景", icon: MapPin, path: `/project/${projectId}/scenes` },
    { id: "props" as SettingsTab, label: "道具", icon: Box, path: `/project/${projectId}/props` },
  ];

  const openAdd = () => {
    setEditForm({ name: "", category: "配饰", description: "", imageUrl: "" });
    setShowModal(true);
  };

  const openEdit = (p: GlobalAsset) => {
    setEditForm({
      id: p.id,
      name: p.name,
      category: p.tags?.[0] ?? "其他",
      description: p.description ?? "",
      imageUrl: p.imageUrl ?? "",
    });
    setShowModal(true);
  };

  const closeModal = () => { setShowModal(false); setEditForm(null); };

  const handleSave = async () => {
    if (!editForm || !editForm.name.trim()) return;
    await createAsset.mutateAsync({
      assetType: "prop",
      libraryType: "personal",
      name: editForm.name,
      description: editForm.description,
      tags: editForm.category,
      imageUrl: editForm.imageUrl || undefined,
      sourceProjectId: numProjectId || undefined,
    });
    closeModal();
  };

  const handleDelete = async (id: string) => {
    if (!confirm("确定要删除这个道具吗？")) return;
    await deleteAsset.mutateAsync(id);
  };

  const withImage = props.filter((p) => p.imageUrl).length;

  return (
    <div className="h-full overflow-auto bg-background relative">
      <div className="p-6 pb-24">
        <div className="max-w-7xl mx-auto">
          <div className="mb-6">
            <div className="flex items-center gap-3 mb-2">
              <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-[#5b5ff9] to-[#8b5ff9] flex items-center justify-center">
                <Sparkles className="w-4 h-4 text-white" />
              </div>
              <h1 className="text-2xl font-semibold text-foreground">项目设定</h1>
            </div>
            <p className="text-sm text-muted-foreground">管理角色、场景和道具设定</p>
          </div>

          {/* Tabs */}
          <div className="flex items-center justify-between mb-6">
            <div className="flex items-center gap-2">
              {settingsTabs.map((tab) => {
                const Icon = tab.icon;
                return (
                  <button
                    key={tab.id}
                    onClick={() => { setActiveTab(tab.id); navigate(tab.path); }}
                    className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm transition-all ${
                      activeTab === tab.id
                        ? "bg-accent text-accent-foreground font-medium"
                        : "text-muted-foreground hover:text-foreground hover:bg-muted"
                    }`}
                  >
                    <Icon className="w-4 h-4" />
                    {tab.label}
                  </button>
                );
              })}
            </div>
            <button
              onClick={openAdd}
              className="px-4 py-2 rounded-lg bg-gradient-to-r from-[#5b5ff9] to-[#8b5ff9] text-white hover:shadow-md transition-all flex items-center gap-2 text-sm"
            >
              <Plus className="w-4 h-4" />
              新增道具
            </button>
          </div>

          {/* Stats bar */}
          <div className="flex items-center justify-between mb-6 rounded-lg border border-border bg-card p-4">
            <div className="flex items-center gap-6">
              <div className="flex items-center gap-2">
                <span className="text-sm text-muted-foreground">总计:</span>
                <span className="text-lg font-semibold text-foreground">{props.length}</span>
              </div>
              <div className="flex items-center gap-2">
                <span className="text-sm text-muted-foreground">有图片:</span>
                <span className="text-lg font-semibold text-green-600">{withImage}</span>
              </div>
              <div className="flex items-center gap-2">
                <span className="text-sm text-muted-foreground">无图片:</span>
                <span className="text-lg font-semibold text-muted-foreground">{props.length - withImage}</span>
              </div>
            </div>
            <button
              onClick={() => {}}
              className="p-2 rounded-lg border border-border bg-card text-foreground hover:bg-muted transition-colors"
            >
              <RefreshCw className="w-4 h-4" />
            </button>
          </div>

          {/* Grid */}
          {isLoading ? (
            <div className="flex items-center justify-center py-20">
              <Loader2 className="w-8 h-8 animate-spin text-primary" />
            </div>
          ) : props.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-20 text-center">
              <Box className="w-12 h-12 text-muted-foreground/30 mb-4" />
              <p className="text-muted-foreground mb-4">暂无道具，点击"新增道具"开始添加</p>
              <button onClick={openAdd} className="px-4 py-2 rounded-lg bg-gradient-to-r from-[#5b5ff9] to-[#8b5ff9] text-white text-sm flex items-center gap-2">
                <Plus className="w-4 h-4" />新增道具
              </button>
            </div>
          ) : (
            <div className="grid grid-cols-6 gap-4 mb-8">
              {props.map((prop) => (
                <div key={prop.id} className="rounded-xl border border-border bg-card overflow-hidden group">
                  <div className="aspect-square relative bg-muted">
                    {prop.imageUrl ? (
                      <img src={prop.imageUrl} alt={prop.name} className="w-full h-full object-cover" />
                    ) : (
                      <div className="w-full h-full flex items-center justify-center">
                        <Box className="w-10 h-10 text-muted-foreground/30" />
                      </div>
                    )}
                    <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-1">
                      <button
                        onClick={() => openEdit(prop)}
                        className="p-1.5 rounded-lg bg-white/20 backdrop-blur-sm hover:bg-white/30 transition-colors"
                      >
                        <Edit2 className="w-4 h-4 text-white" />
                      </button>
                    </div>
                  </div>
                  <div className="p-3">
                    <div className="flex items-center justify-between mb-1">
                      <h3 className="font-medium text-foreground text-sm truncate flex-1">{prop.name}</h3>
                      <button
                        onClick={() => handleDelete(prop.id)}
                        disabled={deleteAsset.isPending}
                        className="p-0.5 rounded hover:bg-destructive/10 transition-colors flex-shrink-0 disabled:opacity-50"
                      >
                        <Trash2 className="w-3 h-3 text-destructive" />
                      </button>
                    </div>
                    {prop.tags?.[0] && (
                      <div className="mb-2">
                        <span className="px-2 py-0.5 rounded-md bg-accent text-primary text-xs">{prop.tags[0]}</span>
                      </div>
                    )}
                    {prop.description && (
                      <p className="text-xs text-muted-foreground line-clamp-2 leading-relaxed">{prop.description}</p>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Floating bottom bar */}
      <div className="fixed bottom-0 left-0 right-0 border-t border-border bg-card/95 backdrop-blur-sm px-6 py-3 z-10">
        <div className="max-w-7xl mx-auto flex items-center justify-end gap-3">
          <button
            onClick={() => navigate(`/project/${projectId}/storyboard`)}
            className="px-6 py-2 rounded-lg bg-gradient-to-r from-green-500 to-emerald-500 text-white hover:shadow-md transition-all flex items-center gap-2 text-sm font-medium"
          >
            <ArrowRight className="w-4 h-4" />
            进入分镜
          </button>
        </div>
      </div>

      {/* Add / Edit Modal */}
      {showModal && editForm && (
        <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">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-xl font-semibold text-foreground">
                {editForm.id ? "编辑道具" : "新增道具"}
              </h2>
              <button onClick={closeModal} className="p-2 hover:bg-muted rounded-lg transition-colors">
                <X className="w-5 h-5 text-muted-foreground" />
              </button>
            </div>

            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-foreground mb-2">道具名称</label>
                  <input
                    type="text"
                    value={editForm.name}
                    onChange={(e) => setEditForm({ ...editForm, name: e.target.value })}
                    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>
                  <select
                    value={editForm.category}
                    onChange={(e) => setEditForm({ ...editForm, category: e.target.value })}
                    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 cursor-pointer"
                  >
                    {CATEGORIES.map((c) => <option key={c} value={c}>{c}</option>)}
                  </select>
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-foreground mb-2">道具描述</label>
                <textarea
                  value={editForm.description}
                  onChange={(e) => setEditForm({ ...editForm, description: e.target.value })}
                  placeholder="描述道具的外观、用途和重要性"
                  rows={3}
                  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">图片 URL（可选）</label>
                <input
                  type="text"
                  value={editForm.imageUrl}
                  onChange={(e) => setEditForm({ ...editForm, imageUrl: e.target.value })}
                  placeholder="https://example.com/prop.jpg"
                  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 font-mono text-sm"
                />
              </div>
            </div>

            <div className="flex gap-3 mt-6 pt-6 border-t border-border">
              <button onClick={closeModal} className="flex-1 px-4 py-2.5 rounded-lg border border-border bg-card text-foreground hover:bg-muted transition-colors">
                取消
              </button>
              <button
                onClick={handleSave}
                disabled={!editForm.name.trim() || createAsset.isPending}
                className="flex-1 px-4 py-2.5 rounded-lg bg-gradient-to-r from-[#5b5ff9] to-[#8b5ff9] text-white hover:shadow-md transition-all flex items-center justify-center gap-2 disabled:opacity-50"
              >
                {createAsset.isPending ? <Loader2 className="w-4 h-4 animate-spin" /> : <Check className="w-4 h-4" />}
                保存
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
