import React, { useState, useEffect, useRef } from 'react';
import { UploadCloud, Film, Settings2, MoreHorizontal, Plus, Loader2 } from 'lucide-react';
import { cn } from '../lib/utils';
import { useStore } from '../store/useStore';
import { getProjects, createProject, uploadMedia } from '../lib/api';
import type { Project } from '../store/useStore';

interface ProjectLibraryProps {
  onProjectSelect: () => void;
}

export function ProjectLibrary({ onProjectSelect }: ProjectLibraryProps) {
  const projects = useStore((state) => state.projects);
  const setProjects = useStore((state) => state.setProjects);
  const setCurrentProject = useStore((state) => state.setCurrentProject);
  const addProject = useStore((state) => state.addProject);
  const [isLoading, setIsLoading] = useState(false);
  const [isCreating, setIsCreating] = useState(false);
  const [showModal, setShowModal] = useState(false);
  const [newName, setNewName] = useState('');
  const [newDesc, setNewDesc] = useState('');
  const fileInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    setIsLoading(true);
    getProjects()
      .then((data) => setProjects(data))
      .catch(console.error)
      .finally(() => setIsLoading(false));
  }, [setProjects]);

  const handleCreate = async () => {
    if (!newName.trim()) return;
    setIsCreating(true);
    try {
      const project = await createProject({ name: newName.trim(), description: newDesc.trim() || undefined });
      addProject(project);
      setShowModal(false);
      setNewName('');
      setNewDesc('');
    } catch (err) {
      console.error('Failed to create project:', err);
    } finally {
      setIsCreating(false);
    }
  };

  const handleSelect = (project: Project) => {
    setCurrentProject(project);
    onProjectSelect();
  };

  const SkeletonCard = () => (
    <div className="group flex flex-col bg-[#111] border border-white/5 rounded-xl overflow-hidden animate-pulse">
      <div className="w-full aspect-[16/9] bg-[#1a1a1a]" />
      <div className="p-4 flex flex-col gap-2">
        <div className="h-4 bg-[#1a1a1a] rounded w-3/4" />
        <div className="h-3 bg-[#1a1a1a] rounded w-1/2 mt-2" />
      </div>
    </div>
  );

  return (
    <div className="p-8 w-full h-full overflow-y-auto bg-[#0a0a0a]">
      <div className="flex justify-between items-end mb-8 border-b border-white/5 pb-6">
        <div>
          <h1 className="text-3xl font-medium tracking-tight text-white mb-2">视频与连续帧项目库</h1>
          <p className="text-gray-400 text-sm">上传源文件、按帧解析配置，并结构化管理多媒体资产实体。</p>
        </div>
        <div className="flex items-center gap-3">
          <button
            onClick={() => setShowModal(true)}
            className="flex items-center gap-2 bg-white/5 hover:bg-white/10 border border-white/10 text-gray-200 px-5 py-2.5 rounded-lg font-medium text-sm transition-colors"
          >
            <Plus size={18} />
            <span>新建项目</span>
          </button>
          <button
            onClick={() => fileInputRef.current?.click()}
            className="flex items-center gap-2 bg-cyan-600 hover:bg-cyan-500 text-white px-5 py-2.5 rounded-lg font-medium text-sm transition-colors border border-cyan-500 shadow-lg shadow-cyan-900/20"
          >
            <UploadCloud size={18} />
            <span>导入多媒体资源</span>
          </button>
          <input
            type="file"
            ref={fileInputRef}
            className="hidden"
            accept="video/*,image/*,.dcm"
            onChange={async (e) => {
              const file = e.target.files?.[0];
              if (!file) return;
              try {
                setIsLoading(true);
                const result = await uploadMedia(file);
                alert(`上传成功: ${file.name}\n已保存至: ${result.file_url}`);
                // 上传成功后创建新项目
                const newProject = await createProject({
                  name: file.name,
                  description: `导入于 ${new Date().toLocaleString()}`,
                });
                addProject(newProject);
                // 刷新项目列表
                const data = await getProjects();
                setProjects(data);
              } catch (err) {
                console.error('Upload failed:', err);
                alert('上传失败，请检查后端服务');
              } finally {
                setIsLoading(false);
                if (fileInputRef.current) fileInputRef.current.value = '';
              }
            }}
          />
        </div>
      </div>

      {isLoading && projects.length === 0 ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
          {Array.from({ length: 8 }).map((_, i) => (
            <SkeletonCard key={i} />
          ))}
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
          {projects.map((proj) => (
            <div 
              key={proj.id} 
              className="group flex flex-col bg-[#111] border border-white/5 rounded-xl overflow-hidden cursor-pointer hover:border-cyan-500/50 transition-all hover:shadow-[0_0_20px_rgba(6,182,212,0.15)]"
              onClick={() => handleSelect(proj)}
            >
              <div className={cn("w-full aspect-[16/9] relative flex items-center justify-center overflow-hidden", proj.thumbnail || 'bg-[#0d0d0d]')}>
                 <Film className="w-12 h-12 text-[#2a2a2a] group-hover:text-[#333] transition-colors" />
                 <div className="absolute top-2 right-2 flex gap-2">
                   <span className="backdrop-blur-md bg-black/40 text-gray-200 text-[10px] font-mono px-2 py-1 rounded border border-white/10 uppercase tracking-widest">
                     {proj.fps || '30FPS'}
                   </span>
                   <span className="backdrop-blur-md bg-black/40 text-gray-200 text-[10px] px-2 py-1 rounded border border-white/10 flex items-center gap-1 uppercase tracking-widest">
                     {proj.status === 'Ready' || proj.status === 'ready' ? (
                       <><div className="w-1.5 h-1.5 bg-emerald-500 rounded-full" /> 已就绪</>
                     ) : proj.status === 'Parsing' || proj.status === 'parsing' ? (
                       <><div className="w-1.5 h-1.5 bg-amber-500 rounded-full animate-pulse" /> 解析拆帧中</>
                     ) : proj.status === 'pending' || proj.status === 'Pending' ? (
                       <><div className="w-1.5 h-1.5 bg-blue-500 rounded-full" /> 待处理</>
                     ) : (
                       <><div className="w-1.5 h-1.5 bg-red-500 rounded-full" /> 异常</>
                     )}
                   </span>
                 </div>
              </div>
              <div className="p-4 flex flex-col gap-1">
                <div className="flex justify-between items-start">
                  <h3 className="text-sm font-medium text-gray-200 truncate pr-4" title={proj.name}>{proj.name}</h3>
                  <button className="text-gray-500 hover:text-gray-300"><MoreHorizontal size={16} /></button>
                </div>
                <div className="flex items-center gap-4 text-xs text-gray-500 font-mono mt-2">
                   <span className="flex items-center gap-1.5"><Settings2 size={12} /> {proj.frames ?? 0} 帧节点</span>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {showModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm">
          <div className="bg-[#111] border border-white/10 rounded-2xl p-6 w-full max-w-md shadow-2xl">
            <h2 className="text-lg font-semibold text-white mb-4">新建项目</h2>
            <div className="space-y-4">
              <div>
                <label className="block text-xs font-medium text-gray-400 uppercase tracking-widest mb-2">项目名称</label>
                <input
                  type="text"
                  value={newName}
                  onChange={(e) => setNewName(e.target.value)}
                  className="w-full bg-[#1a1a1a] border border-white/10 rounded-lg px-4 py-3 text-sm focus:outline-none focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/50 transition-all"
                  placeholder="输入项目名称"
                />
              </div>
              <div>
                <label className="block text-xs font-medium text-gray-400 uppercase tracking-widest mb-2">描述（可选）</label>
                <input
                  type="text"
                  value={newDesc}
                  onChange={(e) => setNewDesc(e.target.value)}
                  className="w-full bg-[#1a1a1a] border border-white/10 rounded-lg px-4 py-3 text-sm focus:outline-none focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/50 transition-all"
                  placeholder="输入项目描述"
                />
              </div>
            </div>
            <div className="flex justify-end gap-3 mt-6">
              <button
                onClick={() => { setShowModal(false); setNewName(''); setNewDesc(''); }}
                className="px-4 py-2 rounded-lg text-sm text-gray-400 hover:text-white transition-colors"
              >
                取消
              </button>
              <button
                onClick={handleCreate}
                disabled={isCreating || !newName.trim()}
                className={cn(
                  "px-4 py-2 rounded-lg text-sm font-medium flex items-center gap-2 transition-all",
                  isCreating || !newName.trim()
                    ? "bg-cyan-500/50 text-black/70 cursor-not-allowed"
                    : "bg-cyan-500 hover:bg-cyan-400 text-black"
                )}
              >
                {isCreating && <Loader2 size={14} className="animate-spin" />}
                创建
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
