import React, { useState, useEffect, useCallback } from 'react';
import { templates, characters as charactersApi } from '../api/client';
import { motion, AnimatePresence } from 'framer-motion';
import { RefreshCw, Search, Layers, ChevronRight, Copy, CheckCircle, BookOpen, Sparkles, User, Wand2 } from 'lucide-react';

interface PromptTemplate {
  id: string;
  category: string;
  name: string;
  description: string;
  promptText: string;
  aspectRatio: string;
  tags: string[];
}

interface CharacterOption {
  id: string;
  name: string;
}

type ViewMode = 'categories' | 'prompts' | 'detail';

const CATEGORY_ICONS: Record<string, string> = {
  'beach': '🏖️', 'pool': '🏊', 'gym': '💪', 'cafe': '☕', 'bedroom': '🛏️',
  'bathroom': '🛁', 'outdoor': '🌿', 'indoor': '🏠', 'nightlife-party': '🎉',
  'fashion-editorial': '👗', 'selfie': '🤳', 'car': '🚗', 'yacht': '🛥️',
  'hotel': '🏨', 'rooftop': '🌆', 'street': '🏙️', 'garden': '🌸',
  'rain': '🌧️', 'snow': '❄️', 'sunset': '🌅', 'morning': '🌅',
  'mirror': '🪞', 'balcony': '🏗️', 'restaurant': '🍽️', 'club': '🎵',
  'sporty': '🏃', 'lingerie': '👙', 'casual': '👕', 'outdoor-adventure': '🏔️',
};

const Templates: React.FC = () => {
  const [categories, setCategories] = useState<string[]>([]);
  const [prompts, setPrompts] = useState<PromptTemplate[]>([]);
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
  const [selectedPrompt, setSelectedPrompt] = useState<PromptTemplate | null>(null);
  const [viewMode, setViewMode] = useState<ViewMode>('categories');
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [searching, setSearching] = useState(false);
  const [copied, setCopied] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [characterList, setCharacterList] = useState<CharacterOption[]>([]);
  const [selectedCharacterId, setSelectedCharacterId] = useState<string>('');
  const [personalizing, setPersonalizing] = useState(false);
  const [personalizedPrompt, setPersonalizedPrompt] = useState<string | null>(null);

  const fetchCategories = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await templates.getCategories();
      const data = res.data?.data ?? res.data ?? [];
      setCategories(Array.isArray(data) ? data : []);
    } catch {
      setError('Kategoriler yüklenirken hata oluştu.');
    }
    setLoading(false);
  }, []);

  useEffect(() => { fetchCategories(); }, [fetchCategories]);

  useEffect(() => {
    const fetchCharacters = async () => {
      try {
        const res = await charactersApi.list();
        const data = res.data?.data ?? res.data ?? [];
        const list = Array.isArray(data) ? data : [];
        setCharacterList(list.map((c: any) => ({ id: c.id, name: c.identity?.name || c.name || c.id })));
      } catch {
        // Karakter listesi yüklenemezse sessizce devam et
      }
    };
    fetchCharacters();
  }, []);

  const handleCategoryClick = async (category: string) => {
    setSelectedCategory(category);
    setViewMode('prompts');
    setLoading(true);
    try {
      const res = await templates.list({ category });
      const data = res.data?.data ?? res.data ?? [];
      setPrompts(Array.isArray(data) ? data : []);
    } catch {
      setError('Şablonlar yüklenirken hata oluştu.');
    }
    setLoading(false);
  };

  const handlePromptClick = async (prompt: PromptTemplate) => {
    setSelectedPrompt(prompt);
    setViewMode('detail');
  };

  const handleSearch = async () => {
    if (!searchQuery.trim()) return;
    setSearching(true);
    setViewMode('prompts');
    setSelectedCategory(null);
    try {
      const res = await templates.list({ q: searchQuery.trim() });
      const data = res.data?.data ?? res.data ?? [];
      setPrompts(Array.isArray(data) ? data : []);
    } catch {
      setError('Arama sırasında hata oluştu.');
    }
    setSearching(false);
  };

  const handleBack = () => {
    if (viewMode === 'detail') {
      setViewMode('prompts');
      setSelectedPrompt(null);
      setPersonalizedPrompt(null);
      setSelectedCharacterId('');
    } else {
      setViewMode('categories');
      setSelectedCategory(null);
      setPrompts([]);
      setSearchQuery('');
    }
  };

  const handleCopy = (text: string) => {
    navigator.clipboard.writeText(text);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  const handlePersonalize = async () => {
    if (!selectedPrompt || !selectedCharacterId) return;
    setPersonalizing(true);
    setPersonalizedPrompt(null);
    try {
      const res = await templates.personalize(selectedPrompt.id, selectedCharacterId);
      const data = res.data?.data ?? res.data;
      const promptText = typeof data === 'string' ? data : data?.personalizedPrompt ?? data?.promptText ?? data?.prompt ?? '';
      setPersonalizedPrompt(promptText);
    } catch {
      setError('Kişiselleştirme sırasında bir hata oluştu.');
    }
    setPersonalizing(false);
  };

  const getCategoryIcon = (cat: string) => {
    const lower = cat.toLowerCase();
    for (const [key, icon] of Object.entries(CATEGORY_ICONS)) {
      if (lower.includes(key)) return icon;
    }
    return '📋';
  };

  if (loading && viewMode === 'categories') {
    return (
      <div className="flex min-h-[60vh] items-center justify-center">
        <div className="flex flex-col items-center gap-3">
          <div className="h-8 w-8 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent" />
          <p className="text-sm text-slate-400">Yükleniyor...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-[1200px] mx-auto">
      {/* Header */}
      <div className="flex items-center justify-between mb-8">
        <div className="flex items-center gap-3">
          {viewMode !== 'categories' && (
            <button onClick={handleBack}
              className="flex items-center gap-2 px-3 py-2 rounded-xl bg-white/[0.03] border border-white/[0.06] text-[13px] text-slate-400 hover:text-white hover:bg-white/[0.06] transition-all cursor-pointer">
              ← Geri
            </button>
          )}
          <div>
            <h1 className="text-2xl font-bold text-white tracking-tight flex items-center gap-2">
              <BookOpen className="w-6 h-6 text-indigo-400" />
              Şablon Kütüphanesi
            </h1>
            <p className="text-sm text-slate-500 mt-1">
              {viewMode === 'categories' && `${categories.length} kategori · Prompt şablonları`}
              {viewMode === 'prompts' && (selectedCategory ? `${selectedCategory} · ${prompts.length} şablon` : `Arama: "${searchQuery}" · ${prompts.length} sonuç`)}
              {viewMode === 'detail' && selectedPrompt?.name}
            </p>
          </div>
        </div>
        <div className="flex items-center gap-3">
          <button onClick={fetchCategories}
            className="p-2 rounded-lg text-slate-500 hover:text-slate-300 hover:bg-white/[0.04] transition-all cursor-pointer">
            <RefreshCw className="w-4 h-4" />
          </button>
        </div>
      </div>

      {error && (
        <motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }}
          className="mb-6 p-4 rounded-xl border border-red-500/20 bg-red-500/[0.05] flex items-center justify-between">
          <span className="text-[13px] text-red-400">{error}</span>
          <button onClick={() => setError(null)} className="text-[12px] text-red-400 hover:text-red-300 cursor-pointer">Kapat</button>
        </motion.div>
      )}

      {/* Search bar */}
      <div className="flex items-center gap-3 mb-6">
        <div className="relative flex-1 max-w-md">
          <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-500" />
          <input
            value={searchQuery}
            onChange={e => setSearchQuery(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && handleSearch()}
            placeholder="Şablon ara... (beach, selfie, cafe, vb.)"
            className="w-full pl-10 pr-4 py-3 rounded-xl bg-white/[0.03] border border-white/[0.08] text-sm text-slate-300 placeholder-slate-600 focus:outline-none focus:border-indigo-500/50 focus:ring-2 focus:ring-indigo-500/10 transition-all"
          />
        </div>
        <button onClick={handleSearch} disabled={searching || !searchQuery.trim()}
          className="px-5 py-3 rounded-xl bg-gradient-to-r from-indigo-600 to-violet-600 text-[13px] font-semibold text-white shadow-lg shadow-indigo-500/20 disabled:opacity-40 cursor-pointer">
          {searching ? 'Aranıyor...' : 'Ara'}
        </button>
      </div>

      {/* Categories view */}
      <AnimatePresence mode="wait">
        {viewMode === 'categories' && (
          <motion.div key="cats" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
            className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
            {categories.length === 0 ? (
              <div className="col-span-full rounded-2xl border border-white/[0.06] bg-white/[0.02] py-16 text-center">
                <Layers className="w-8 h-8 text-slate-700 mx-auto mb-3" />
                <p className="text-[13px] text-slate-500">Henüz prompt şablonu yüklenmemiş.</p>
                <p className="text-[12px] text-slate-600 mt-1">data/prompt-library/base-prompts.json dosyasını kontrol edin.</p>
              </div>
            ) : (
              categories.map((cat, i) => (
                <motion.button
                  key={cat}
                  initial={{ opacity: 0, y: 16 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: i * 0.04 }}
                  whileHover={{ y: -2, scale: 1.02 }}
                  onClick={() => handleCategoryClick(cat)}
                  className="text-left rounded-2xl border border-white/[0.06] bg-white/[0.02] p-5 hover:border-indigo-500/30 hover:bg-white/[0.04] transition-all cursor-pointer group"
                >
                  <div className="flex items-center justify-between mb-3">
                    <span className="text-2xl">{getCategoryIcon(cat)}</span>
                    <ChevronRight className="w-4 h-4 text-slate-700 group-hover:text-indigo-400 transition-colors" />
                  </div>
                  <h3 className="text-[14px] font-semibold text-white capitalize">{cat.replace(/-/g, ' ')}</h3>
                  <p className="text-[11px] text-slate-500 mt-1">Şablonları görüntüle →</p>
                </motion.button>
              ))
            )}
          </motion.div>
        )}

        {/* Prompts list view */}
        {viewMode === 'prompts' && (
          <motion.div key="prompts" initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }} exit={{ opacity: 0, x: -20 }}>
            {loading ? (
              <div className="flex min-h-[300px] items-center justify-center">
                <div className="h-6 w-6 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent" />
              </div>
            ) : prompts.length === 0 ? (
              <div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] py-16 text-center">
                <Sparkles className="w-8 h-8 text-slate-700 mx-auto mb-3" />
                <p className="text-[13px] text-slate-500">Bu kategoride şablon bulunamadı.</p>
              </div>
            ) : (
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                {prompts.map((p, i) => (
                  <motion.button
                    key={p.id}
                    initial={{ opacity: 0, y: 12 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: i * 0.03 }}
                    whileHover={{ y: -2 }}
                    onClick={() => handlePromptClick(p)}
                    className="text-left rounded-2xl border border-white/[0.06] bg-white/[0.02] p-5 hover:border-white/[0.12] hover:bg-white/[0.04] transition-all cursor-pointer group"
                  >
                    <div className="flex items-start justify-between mb-3">
                      <span className="inline-block rounded-lg bg-indigo-500/15 px-2.5 py-1 text-[11px] font-semibold text-indigo-300 capitalize">
                        {p.category.replace(/-/g, ' ')}
                      </span>
                      <span className="text-[11px] text-slate-600 bg-white/[0.04] px-2 py-0.5 rounded">{p.aspectRatio}</span>
                    </div>
                    <h3 className="text-[13px] font-medium text-slate-200 mb-2 line-clamp-2">{p.name}</h3>
                    <p className="text-[12px] text-slate-500 line-clamp-2">{p.description}</p>
                    {p.tags.length > 0 && (
                      <div className="flex flex-wrap gap-1 mt-3">
                        {p.tags.slice(0, 4).map(tag => (
                          <span key={tag} className="text-[10px] text-slate-600 bg-white/[0.04] px-1.5 py-0.5 rounded">{tag}</span>
                        ))}
                        {p.tags.length > 4 && <span className="text-[10px] text-slate-600">+{p.tags.length - 4}</span>}
                      </div>
                    )}
                  </motion.button>
                ))}
              </div>
            )}
          </motion.div>
        )}

        {/* Detail view */}
        {viewMode === 'detail' && selectedPrompt && (
          <motion.div key="detail" initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }} exit={{ opacity: 0, x: -20 }}>
            <div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] overflow-hidden">
              <div className="p-6 border-b border-white/[0.06]">
                <div className="flex items-start justify-between mb-4">
                  <div>
                    <span className="inline-block rounded-lg bg-indigo-500/15 px-2.5 py-1 text-[11px] font-semibold text-indigo-300 capitalize mb-2">
                      {selectedPrompt.category.replace(/-/g, ' ')}
                    </span>
                    <h2 className="text-[18px] font-bold text-white">{selectedPrompt.name}</h2>
                    <p className="text-[13px] text-slate-400 mt-1">{selectedPrompt.description}</p>
                  </div>
                  <span className="text-[12px] text-slate-500 bg-white/[0.04] px-3 py-1 rounded-lg">{selectedPrompt.aspectRatio}</span>
                </div>
                {selectedPrompt.tags.length > 0 && (
                  <div className="flex flex-wrap gap-1.5">
                    {selectedPrompt.tags.map(tag => (
                      <span key={tag} className="text-[11px] text-slate-500 bg-white/[0.04] px-2 py-0.5 rounded-lg">{tag}</span>
                    ))}
                  </div>
                )}
              </div>
              <div className="p-6">
                <div className="flex items-center justify-between mb-3">
                  <span className="text-[12px] font-semibold text-slate-400 uppercase tracking-wider">Prompt İçeriği</span>
                  <button onClick={() => handleCopy(selectedPrompt.promptText)}
                    className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[12px] text-slate-400 hover:text-white hover:bg-white/[0.06] transition-all cursor-pointer">
                    {copied ? <><CheckCircle className="w-3.5 h-3.5 text-emerald-400" /> Kopyalandı</> : <><Copy className="w-3.5 h-3.5" /> Kopyala</>}
                  </button>
                </div>
                <pre className="rounded-xl bg-black/30 border border-white/[0.06] p-4 text-[12px] text-slate-300 font-mono whitespace-pre-wrap overflow-x-auto max-h-[400px] overflow-y-auto leading-relaxed">
                  {selectedPrompt.promptText}
                </pre>
              </div>

              {/* Kişiselleştirme bölümü */}
              <div className="p-6 border-t border-white/[0.06]">
                <div className="flex items-center gap-2 mb-4">
                  <Wand2 className="w-4 h-4 text-violet-400" />
                  <span className="text-[12px] font-semibold text-slate-400 uppercase tracking-wider">Kişiselleştirme</span>
                </div>
                <div className="flex items-center gap-3">
                  <div className="relative flex-1 max-w-xs">
                    <User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-500" />
                    <select
                      value={selectedCharacterId}
                      onChange={e => { setSelectedCharacterId(e.target.value); setPersonalizedPrompt(null); }}
                      className="w-full pl-9 pr-4 py-2.5 rounded-xl bg-white/[0.03] border border-white/[0.08] text-[13px] text-slate-300 focus:outline-none focus:border-violet-500/50 focus:ring-2 focus:ring-violet-500/10 transition-all appearance-none cursor-pointer"
                    >
                      <option value="">Karakter seçin...</option>
                      {characterList.map(c => (
                        <option key={c.id} value={c.id}>{c.name}</option>
                      ))}
                    </select>
                  </div>
                  <button
                    onClick={handlePersonalize}
                    disabled={!selectedCharacterId || personalizing}
                    className="flex items-center gap-2 px-5 py-2.5 rounded-xl bg-gradient-to-r from-violet-600 to-purple-600 text-[13px] font-semibold text-white shadow-lg shadow-violet-500/20 disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer transition-all hover:shadow-violet-500/30"
                  >
                    {personalizing ? (
                      <>
                        <div className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-white border-t-transparent" />
                        Kişiselleştiriliyor...
                      </>
                    ) : (
                      <>
                        <Wand2 className="w-3.5 h-3.5" />
                        Kişiselleştir
                      </>
                    )}
                  </button>
                </div>

                {personalizedPrompt && (
                  <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="mt-4">
                    <div className="flex items-center justify-between mb-3">
                      <span className="text-[12px] font-semibold text-violet-400 uppercase tracking-wider">Kişiselleştirilmiş Prompt</span>
                      <button onClick={() => handleCopy(personalizedPrompt)}
                        className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[12px] text-slate-400 hover:text-white hover:bg-white/[0.06] transition-all cursor-pointer">
                        {copied ? <><CheckCircle className="w-3.5 h-3.5 text-emerald-400" /> Kopyalandı</> : <><Copy className="w-3.5 h-3.5" /> Kopyala</>}
                      </button>
                    </div>
                    <pre className="rounded-xl bg-violet-500/[0.05] border border-violet-500/20 p-4 text-[12px] text-slate-300 font-mono whitespace-pre-wrap overflow-x-auto max-h-[400px] overflow-y-auto leading-relaxed">
                      {personalizedPrompt}
                    </pre>
                  </motion.div>
                )}
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
};

export default Templates;
