import { useState, useEffect, useCallback } from 'react';
import { motion } from 'framer-motion';
import { Loader2, ChevronDown, Trash2, Download, X } from 'lucide-react';
import { AnimatePresence } from 'framer-motion';
import { characters, images } from '../api/client';

interface CharacterItem { id: string; identity: { name: string } }
interface GeneratedImage { imageId: string; filename: string; url: string; createdAt?: string }

const ASPECT_RATIOS = ['9:16', '1:1', '16:9', '4:3', '3:4'];

export default function ImageGenerate() {
  const [charList, setCharList] = useState<CharacterItem[]>([]);
  const [selectedCharId, setSelectedCharId] = useState<string | null>(null);
  const [charDropdownOpen, setCharDropdownOpen] = useState(false);
  const [loadingChars, setLoadingChars] = useState(true);

  const [prompt, setPrompt] = useState('');
  const [aspectRatio, setAspectRatio] = useState('9:16');
  const [generating, setGenerating] = useState(false);
  const [genMessage, setGenMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  const [imageList, setImageList] = useState<GeneratedImage[]>([]);
  const [imagesLoading, setImagesLoading] = useState(false);
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const [previewImage, setPreviewImage] = useState<GeneratedImage | null>(null);

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

  async function loadCharacters() {
    setLoadingChars(true);
    try {
      const res = await characters.list();
      const data = res.data;
      const list: CharacterItem[] = (Array.isArray(data) ? data : []).map((c: any) => ({
        id: c.id,
        identity: c.identity ?? { name: c.id },
      }));
      setCharList(list);
      if (list.length > 0 && !selectedCharId) {
        setSelectedCharId(list[0].id);
      }
    } catch {
      setCharList([]);
    } finally {
      setLoadingChars(false);
    }
  }

  const loadImages = useCallback(async () => {
    if (!selectedCharId) return;
    setImagesLoading(true);
    try {
      const res = await images.list(selectedCharId);
      const raw = res.data;
      const iData = Array.isArray(raw) ? raw : (raw?.data ?? raw?.images ?? []);
      setImageList(Array.isArray(iData) ? iData : []);
    } catch {
      setImageList([]);
    }
    setImagesLoading(false);
  }, [selectedCharId]);

  useEffect(() => { if (selectedCharId) loadImages(); }, [selectedCharId, loadImages]);

  async function handleGenerate() {
    if (!selectedCharId || !prompt.trim()) return;
    setGenerating(true);
    setGenMessage(null);
    try {
      await images.generate(selectedCharId, { prompt: prompt.trim(), aspectRatio });
      setGenMessage({ type: 'success', text: 'Görsel başarıyla üretildi!' });
      setPrompt('');
      await loadImages();
    } catch (err: any) {
      setGenMessage({ type: 'error', text: err?.response?.data?.error || err?.message || 'Görsel üretilirken hata oluştu.' });
    }
    setGenerating(false);
  }

  async function handleDelete(imageId: string) {
    if (!selectedCharId) return;
    setDeletingId(imageId);
    try {
      await images.delete(selectedCharId, imageId);
      await loadImages();
    } catch {}
    setDeletingId(null);
  }

  const selectedChar = charList.find(c => c.id === selectedCharId);
  const selectedCharName = selectedChar?.identity?.name ?? 'Seçiniz';

  return (
    <div className="max-w-4xl">
      <div className="mb-8">
        <h1 className="text-xl font-bold text-white mb-1">Görsel Üret</h1>
        <p className="text-[13px] text-slate-500">Gemini Nano Banana 2 ile görsel üretin. Referans görseller otomatik eklenir.</p>
      </div>

      {/* Character Selector */}
      {loadingChars ? (
        <div className="flex items-center justify-center py-8"><Loader2 className="w-5 h-5 animate-spin text-indigo-400" /></div>
      ) : charList.length === 0 ? (
        <div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-8 text-center">
          <p className="text-[13px] text-slate-500">Henüz karakter oluşturulmamış. Önce bir karakter oluşturun.</p>
        </div>
      ) : (
        <>
          <div className="relative mb-6">
            <button
              onClick={() => setCharDropdownOpen(!charDropdownOpen)}
              className="flex items-center gap-3 px-4 py-3 rounded-xl bg-white/[0.03] border border-white/[0.08] hover:border-white/[0.12] transition-all cursor-pointer w-full max-w-md"
            >
              <div className="w-8 h-8 rounded-lg bg-violet-500/20 flex items-center justify-center shrink-0">
                <span className="text-[11px] font-semibold text-violet-300">{selectedCharName[0]?.toUpperCase()}</span>
              </div>
              <div className="flex-1 text-left">
                <div className="text-[11px] text-slate-500 leading-none">Karakter</div>
                <div className="text-[13px] font-medium text-slate-200 mt-0.5">{selectedCharName}</div>
              </div>
              <ChevronDown className={`w-4 h-4 text-slate-500 transition-transform ${charDropdownOpen ? 'rotate-180' : ''}`} />
            </button>
            {charDropdownOpen && (
              <div className="absolute top-full left-0 mt-2 w-full max-w-md rounded-xl bg-[#16162a] border border-white/[0.08] shadow-2xl shadow-black/40 z-50 overflow-hidden">
                {charList.map(c => (
                  <button
                    key={c.id}
                    onClick={() => { setSelectedCharId(c.id); setCharDropdownOpen(false); }}
                    className={`w-full flex items-center gap-3 px-4 py-3 text-left transition-colors cursor-pointer ${
                      selectedCharId === c.id ? 'bg-indigo-500/[0.1] text-white' : 'text-slate-400 hover:bg-white/[0.04] hover:text-slate-200'
                    }`}
                  >
                    <div className="w-7 h-7 rounded-full bg-gradient-to-br from-violet-500/20 to-pink-500/20 flex items-center justify-center shrink-0">
                      <span className="text-[11px] font-semibold text-violet-300">{(c.identity?.name ?? '?')[0].toUpperCase()}</span>
                    </div>
                    <span className="text-[13px] font-medium">{c.identity?.name ?? c.id.slice(0, 8)}</span>
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* Generation Form */}
          <div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-5 mb-6">
            <div className="flex flex-col gap-3 mb-4">
              <div className="flex flex-col gap-1.5">
                <label className="text-xs text-slate-400">Prompt</label>
                <textarea
                  value={prompt}
                  onChange={(e) => setPrompt(e.target.value)}
                  placeholder="Üretmek istediğiniz görseli tanımlayın... Örn: casual selfie at a cafe, smiling, natural lighting"
                  rows={3}
                  className="w-full px-3 py-2 rounded-lg bg-white/[0.03] border border-white/[0.06] text-slate-100 text-sm focus:outline-none focus:border-indigo-500 placeholder-slate-600 resize-y"
                />
              </div>
              <div className="flex items-center gap-3">
                <div className="flex flex-col gap-1.5">
                  <label className="text-xs text-slate-400">En-Boy Oranı</label>
                  <select
                    value={aspectRatio}
                    onChange={(e) => setAspectRatio(e.target.value)}
                    className="px-3 py-2 rounded-lg bg-white/[0.03] border border-white/[0.06] text-slate-100 text-sm focus:outline-none focus:border-indigo-500"
                  >
                    {ASPECT_RATIOS.map(r => <option key={r} value={r}>{r}</option>)}
                  </select>
                </div>
              </div>
            </div>
            <div className="flex items-center gap-3">
              <motion.button
                whileHover={{ scale: 1.03 }}
                whileTap={{ scale: 0.97 }}
                onClick={handleGenerate}
                disabled={generating || !prompt.trim()}
                className="px-5 py-2.5 rounded-xl bg-gradient-to-r from-indigo-600 to-violet-600 text-white text-sm font-semibold shadow-lg shadow-indigo-500/20 disabled:opacity-50 cursor-pointer transition-all border-none"
              >
                {generating ? (
                  <span className="flex items-center gap-2"><Loader2 className="w-4 h-4 animate-spin" /> Üretiliyor...</span>
                ) : 'Görsel Üret'}
              </motion.button>
              {genMessage && (
                <span className={`text-sm ${genMessage.type === 'success' ? 'text-emerald-400' : 'text-red-400'}`}>
                  {genMessage.text}
                </span>
              )}
            </div>
          </div>

          {/* Generated Images Grid */}
          <div>
            <h2 className="text-[15px] font-semibold text-white mb-4">Üretilen Görseller</h2>
            {imagesLoading ? (
              <div className="flex items-center justify-center py-8"><Loader2 className="w-5 h-5 animate-spin text-indigo-400" /></div>
            ) : imageList.length === 0 ? (
              <div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-8 text-center">
                <p className="text-[13px] text-slate-500">Henüz görsel üretilmemiş.</p>
              </div>
            ) : (
              <div className="grid grid-cols-[repeat(auto-fill,minmax(200px,1fr))] gap-4">
                {imageList.map((img) => (
                  <motion.div
                    key={img.imageId}
                    initial={{ opacity: 0, scale: 0.95 }}
                    animate={{ opacity: 1, scale: 1 }}
                    whileHover={{ y: -2, scale: 1.02 }}
                    className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-2 group relative cursor-pointer"
                    title="Önizleme için çift tıklayın"
                  >
                    <img
                      src={img.url}
                      alt="Üretilen görsel"
                      className="w-full rounded-xl aspect-square object-cover"
                      loading="lazy"
                      onDoubleClick={() => setPreviewImage(img)}
                    />
                    <div className="flex items-center justify-between px-1 mt-2">
                      <span className="text-[10px] text-slate-500">{img.createdAt ? new Date(Number(img.createdAt)).toLocaleString('tr-TR') : img.filename}</span>
                      <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                        <a href={img.url} download className="p-1 rounded-lg hover:bg-white/[0.06] text-slate-500 hover:text-slate-300 transition-colors">
                          <Download className="w-3.5 h-3.5" />
                        </a>
                        <button
                          onClick={() => handleDelete(img.imageId)}
                          disabled={deletingId === img.imageId}
                          className="p-1 rounded-lg hover:bg-red-500/10 text-slate-500 hover:text-red-400 transition-colors cursor-pointer border-none bg-transparent"
                        >
                          {deletingId === img.imageId ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Trash2 className="w-3.5 h-3.5" />}
                        </button>
                      </div>
                    </div>
                  </motion.div>
                ))}
              </div>
            )}
          </div>
        </>
      )}

      {/* Preview Modal */}
      <AnimatePresence>
        {previewImage && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-[100] flex items-center justify-center bg-black/80 backdrop-blur-sm"
            onClick={() => setPreviewImage(null)}
          >
            <motion.div
              initial={{ scale: 0.9, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.9, opacity: 0 }}
              transition={{ type: 'spring', stiffness: 300, damping: 25 }}
              className="relative max-w-[90vw] max-h-[90vh] flex flex-col items-center"
              onClick={(e) => e.stopPropagation()}
            >
              <img
                src={previewImage.url}
                alt="Önizleme"
                className="max-w-full max-h-[80vh] rounded-2xl shadow-2xl object-contain"
              />
              <div className="flex items-center gap-3 mt-4">
                <a
                  href={previewImage.url}
                  download={previewImage.filename || 'image.jpg'}
                  className="flex items-center gap-2 px-5 py-2.5 rounded-xl bg-gradient-to-r from-indigo-600 to-violet-600 text-white text-sm font-semibold shadow-lg shadow-indigo-500/20 no-underline transition-all hover:scale-105"
                >
                  <Download className="w-4 h-4" /> İndir
                </a>
                <button
                  onClick={() => setPreviewImage(null)}
                  className="flex items-center gap-2 px-5 py-2.5 rounded-xl bg-white/[0.08] border border-white/[0.1] text-slate-300 text-sm font-medium cursor-pointer transition-all hover:bg-white/[0.12]"
                >
                  <X className="w-4 h-4" /> Kapat
                </button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
