'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  X,
  Search,
  Star,
  Plus,
  Sparkles,
  Filter,
  Heart,
  Copy,
  Check,
  ChevronDown
} from 'lucide-react';
import { cn } from '@/utils';

interface PromptTemplate {
  id: string;
  name: string;
  description?: string;
  content: string;
  category: string;
  tags?: string;
  target_type: string;
  is_public: boolean;
  usage_count: number;
  is_favorite: boolean;
  user_id?: string;
}

interface TemplateCategory {
  value: string;
  label: string;
  count: number;
}

interface PromptTemplateLibraryProps {
  isOpen: boolean;
  onClose: () => void;
  onSelectTemplate: (template: PromptTemplate) => void;
  targetType?: 'image' | 'video' | 'audio' | 'music';
}

// Mock data for now - replace with actual API calls
const MOCK_TEMPLATES: PromptTemplate[] = [
  {
    id: '1',
    name: '高清写实',
    description: '适用于需要高质量写实效果的场景',
    content: '{prompt}, highly detailed, photorealistic, 8k resolution, professional photography, sharp focus, masterpiece',
    category: 'quality',
    tags: '高清,写实,8k',
    target_type: 'image',
    is_public: true,
    usage_count: 128,
    is_favorite: false
  },
  {
    id: '2',
    name: '动漫风格',
    description: '日系动漫风格渲染',
    content: '{prompt}, anime style, manga illustration, vibrant colors, clean line art, studio ghibli inspired',
    category: 'style',
    tags: '动漫,日系,插画',
    target_type: 'image',
    is_public: true,
    usage_count: 96,
    is_favorite: true
  },
  {
    id: '3',
    name: '赛博朋克',
    description: '未来科幻赛博朋克风格',
    content: '{prompt}, cyberpunk style, neon lights, futuristic city, high tech low life, dystopian atmosphere',
    category: 'style',
    tags: '赛博朋克,科幻,霓虹',
    target_type: 'both',
    is_public: true,
    usage_count: 64,
    is_favorite: false
  },
  {
    id: '4',
    name: '电影镜头',
    description: '电影级镜头语言',
    content: '{prompt}, cinematic shot, film grain, dramatic lighting, anamorphic lens, bokeh background',
    category: 'camera',
    tags: '电影,镜头,cinematic',
    target_type: 'video',
    is_public: true,
    usage_count: 45,
    is_favorite: false
  },
  {
    id: '5',
    name: '角色白底',
    description: '适合角色设计的白底图',
    content: '{prompt}, character design, pure white background, professional studio lighting, clean edges',
    category: 'character',
    tags: '角色,白底,设计',
    target_type: 'image',
    is_public: true,
    usage_count: 82,
    is_favorite: true
  },
  {
    id: '6',
    name: '自然风景',
    description: '优美的自然风景场景',
    content: '{prompt}, natural landscape, breathtaking scenery, golden hour lighting, atmospheric perspective',
    category: 'scene',
    tags: '风景,自然,户外',
    target_type: 'both',
    is_public: true,
    usage_count: 73,
    is_favorite: false
  }
];

const MOCK_CATEGORIES: TemplateCategory[] = [
  { value: 'general', label: '通用', count: 12 },
  { value: 'character', label: '角色', count: 8 },
  { value: 'scene', label: '场景', count: 6 },
  { value: 'style', label: '风格', count: 15 },
  { value: 'camera', label: '镜头', count: 5 },
  { value: 'lighting', label: '光照', count: 4 },
  { value: 'quality', label: '画质', count: 7 },
];

export function PromptTemplateLibrary({
  isOpen,
  onClose,
  onSelectTemplate,
  targetType = 'image'
}: PromptTemplateLibraryProps) {
  const [templates, setTemplates] = useState<PromptTemplate[]>([]);
  const [categories, setCategories] = useState<TemplateCategory[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
  const [favoritesOnly, setFavoritesOnly] = useState(false);
  const [copiedId, setCopiedId] = useState<string | null>(null);

  useEffect(() => {
    if (isOpen) {
      // Simulate API call
      setLoading(true);
      setTimeout(() => {
        setTemplates(MOCK_TEMPLATES);
        setCategories(MOCK_CATEGORIES);
        setLoading(false);
      }, 300);
    }
  }, [isOpen]);

  const filteredTemplates = templates.filter(template => {
    // Search filter
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      const matchesSearch = 
        template.name.toLowerCase().includes(query) ||
        template.description?.toLowerCase().includes(query) ||
        template.tags?.toLowerCase().includes(query);
      if (!matchesSearch) return false;
    }
    
    // Category filter
    if (selectedCategory && template.category !== selectedCategory) {
      return false;
    }
    
    // Favorites filter
    if (favoritesOnly && !template.is_favorite) {
      return false;
    }
    
    // Target type filter
    if (targetType && template.target_type !== 'both' && template.target_type !== targetType) {
      return false;
    }
    
    return true;
  });

  const handleCopy = (template: PromptTemplate) => {
    navigator.clipboard.writeText(template.content);
    setCopiedId(template.id);
    setTimeout(() => setCopiedId(null), 2000);
  };

  const handleToggleFavorite = (templateId: string) => {
    setTemplates(prev => prev.map(t => 
      t.id === templateId ? { ...t, is_favorite: !t.is_favorite } : t
    ));
  };

  const getCategoryLabel = (value: string) => {
    return categories.find(c => c.value === value)?.label || value;
  };

  const getTargetTypeLabel = (type: string) => {
    const labels: Record<string, string> = {
      'image': '图片',
      'video': '视频',
      'audio': '音频',
      'music': '音乐',
      'both': '通用'
    };
    return labels[type] || type;
  };

  return (
    <AnimatePresence>
      {isOpen && (
        <>
          {/* Backdrop */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-[9998] bg-black/40 backdrop-blur-sm"
            onClick={onClose}
          />

          {/* Panel */}
          <motion.div
            initial={{ opacity: 0, x: 400 }}
            animate={{ opacity: 1, x: 0 }}
            exit={{ opacity: 0, x: 400 }}
            transition={{ type: 'spring', damping: 25, stiffness: 200 }}
            className="fixed right-0 top-0 bottom-0 w-[480px] z-[9999] bg-black/90 backdrop-blur-xl border-l border-white/10 shadow-2xl flex flex-col"
          >
            {/* Header */}
            <div className="flex items-center justify-between p-4 border-b border-white/10">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-amber-500 to-orange-500 flex items-center justify-center">
                  <Sparkles className="w-5 h-5 text-white" />
                </div>
                <div>
                  <h2 className="text-lg font-semibold text-white">提示词模板库</h2>
                  <p className="text-xs text-muted-foreground">
                    {filteredTemplates.length} 个模板
                  </p>
                </div>
              </div>
              <button
                onClick={onClose}
                className="p-2 text-muted-foreground hover:text-white hover:bg-white/10 rounded-lg transition-colors"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* Search & Filters */}
            <div className="p-4 space-y-3 border-b border-white/10">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                <input
                  type="text"
                  placeholder="搜索模板..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full pl-10 pr-4 py-2 bg-white/5 border border-white/10 rounded-xl text-sm text-white placeholder:text-muted-foreground focus:outline-none focus:border-white/20"
                />
              </div>

              <div className="flex items-center gap-2">
                <button
                  onClick={() => setFavoritesOnly(!favoritesOnly)}
                  className={cn(
                    "flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg transition-colors",
                    favoritesOnly
                      ? "bg-amber-500/20 text-amber-400 border border-amber-500/30"
                      : "bg-white/5 text-muted-foreground hover:text-white border border-white/10"
                  )}
                >
                  <Heart className={cn("w-3.5 h-3.5", favoritesOnly && "fill-current")} />
                  收藏
                </button>

                <div className="flex-1 overflow-x-auto scrollbar-hide">
                  <div className="flex items-center gap-1">
                    <button
                      onClick={() => setSelectedCategory(null)}
                      className={cn(
                        "px-3 py-1.5 text-xs rounded-lg transition-colors whitespace-nowrap",
                        !selectedCategory
                          ? "bg-white/10 text-white"
                          : "bg-white/5 text-muted-foreground hover:text-white"
                      )}
                    >
                      全部
                    </button>
                    {categories.map(cat => (
                      <button
                        key={cat.value}
                        onClick={() => setSelectedCategory(cat.value)}
                        className={cn(
                          "px-3 py-1.5 text-xs rounded-lg transition-colors whitespace-nowrap",
                          selectedCategory === cat.value
                            ? "bg-white/10 text-white"
                            : "bg-white/5 text-muted-foreground hover:text-white"
                        )}
                      >
                        {cat.label}
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            {/* Template List */}
            <div className="flex-1 overflow-y-auto p-4 space-y-3">
              {loading ? (
                <div className="flex items-center justify-center h-32">
                  <div className="w-8 h-8 border-2 border-white/10 border-t-white/50 rounded-full animate-spin" />
                </div>
              ) : filteredTemplates.length === 0 ? (
                <div className="flex flex-col items-center justify-center h-32 text-muted-foreground">
                  <Sparkles className="w-12 h-12 mb-3 opacity-20" />
                  <p className="text-sm">没有找到模板</p>
                </div>
              ) : (
                filteredTemplates.map((template) => (
                  <motion.div
                    key={template.id}
                    layout
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    className="group p-4 bg-white/5 border border-white/10 rounded-xl hover:border-white/20 transition-all cursor-pointer"
                    onClick={() => onSelectTemplate(template)}
                  >
                    <div className="flex items-start justify-between gap-3 mb-2">
                      <div className="flex-1 min-w-0">
                        <h3 className="text-sm font-medium text-white truncate">
                          {template.name}
                        </h3>
                        <p className="text-xs text-muted-foreground line-clamp-1">
                          {template.description}
                        </p>
                      </div>
                      <div className="flex items-center gap-1">
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            handleToggleFavorite(template.id);
                          }}
                          className={cn(
                            "p-1.5 rounded-lg transition-colors",
                            template.is_favorite
                              ? "text-amber-400"
                              : "text-muted-foreground hover:text-amber-400 opacity-0 group-hover:opacity-100"
                          )}
                        >
                          <Heart className={cn("w-4 h-4", template.is_favorite && "fill-current")} />
                        </button>
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            handleCopy(template);
                          }}
                          className="p-1.5 text-muted-foreground hover:text-white opacity-0 group-hover:opacity-100 transition-opacity"
                        >
                          {copiedId === template.id ? (
                            <Check className="w-4 h-4 text-green-400" />
                          ) : (
                            <Copy className="w-4 h-4" />
                          )}
                        </button>
                      </div>
                    </div>

                    <div className="flex items-center gap-2 mb-2">
                      <span className="px-2 py-0.5 text-[10px] bg-white/10 rounded text-white/70">
                        {getCategoryLabel(template.category)}
                      </span>
                      <span className={cn(
                        "px-2 py-0.5 text-[10px] rounded",
                        template.target_type === 'image' && "bg-blue-500/20 text-blue-400",
                        template.target_type === 'video' && "bg-purple-500/20 text-purple-400",
                        template.target_type === 'both' && "bg-green-500/20 text-green-400"
                      )}>
                        {getTargetTypeLabel(template.target_type)}
                      </span>
                      <span className="text-[10px] text-muted-foreground">
                        使用 {template.usage_count} 次
                      </span>
                    </div>

                    <div className="p-2 bg-black/30 rounded-lg">
                      <p className="text-xs text-white/60 line-clamp-2 font-mono">
                        {template.content}
                      </p>
                    </div>
                  </motion.div>
                ))
              )}
            </div>

            {/* Footer */}
            <div className="p-4 border-t border-white/10">
              <button
                onClick={() => {/* TODO: Open create template modal */}}
                className="w-full flex items-center justify-center gap-2 px-4 py-2 text-sm text-white bg-gradient-to-r from-amber-500 to-orange-500 rounded-xl hover:opacity-90 transition-opacity"
              >
                <Plus className="w-4 h-4" />
                创建新模板
              </button>
            </div>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
}