import { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { characters } from '../api/client';
import { motion, AnimatePresence } from 'framer-motion';
import {
  UserPlus, Globe, Briefcase, AlertTriangle, Search,
  ArrowRight, Users,
} from 'lucide-react';

interface Character {
  id: string;
  status: 'active' | 'inactive' | 'creating';
  identity: { name: string; nationality: string; occupation: string };
}

const statusConfig: Record<string, { label: string; dot: string; bg: string; text: string; ring: string }> = {
  active: { label: 'Aktif', dot: 'bg-emerald-500', bg: 'bg-emerald-500/10', text: 'text-emerald-400', ring: 'ring-emerald-500/20' },
  inactive: { label: 'Pasif', dot: 'bg-slate-500', bg: 'bg-slate-500/10', text: 'text-slate-400', ring: 'ring-slate-500/20' },
  creating: { label: 'Oluşturuluyor', dot: 'bg-amber-500', bg: 'bg-amber-500/10', text: 'text-amber-400', ring: 'ring-amber-500/20' },
};

type StatusFilter = 'all' | 'active' | 'inactive' | 'creating';

const CharacterList: React.FC = () => {
  const navigate = useNavigate();
  const [characterList, setCharacterList] = useState<Character[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState<StatusFilter>('all');
  const [imgErrors, setImgErrors] = useState<Set<string>>(new Set());
  const [imgLoaded, setImgLoaded] = useState<Set<string>>(new Set());

  const fetchCharacters = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const res = await characters.list();
      const list = res.data?.data ?? res.data?.characters ?? res.data;
      setCharacterList(Array.isArray(list) ? list : []);
    } catch {
      setError('Karakterler yüklenirken hata oluştu.');
    } finally {
      setLoading(false);
    }
  }, []);

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

  const filtered = characterList.filter((c) => {
    const matchesSearch = c.identity?.name?.toLowerCase().includes(search.toLowerCase());
    const matchesStatus = statusFilter === 'all' || c.status === statusFilter;
    return matchesSearch && matchesStatus;
  });

  const filterButtons: { value: StatusFilter; label: string }[] = [
    { value: 'all', label: `Tümü (${characterList.length})` },
    { value: 'active', label: 'Aktif' },
    { value: 'inactive', label: 'Pasif' },
    { value: 'creating', label: 'Oluşturuluyor' },
  ];

  if (loading) {
    return (
      <div className="flex min-h-[60vh] items-center justify-center">
        <div className="h-6 w-6 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="max-w-[1200px] mx-auto">
        <motion.div initial={{ opacity: 0, scale: 0.98 }} animate={{ opacity: 1, scale: 1 }}
          className="rounded-2xl border border-red-500/20 bg-red-500/[0.05] p-6">
          <div className="flex items-center gap-3 mb-3">
            <AlertTriangle className="w-5 h-5 text-red-400" />
            <span className="text-[14px] font-semibold text-red-300">Hata</span>
          </div>
          <p className="text-[13px] text-red-400/80 mb-4">{error}</p>
          <button onClick={fetchCharacters}
            className="px-5 py-2.5 rounded-xl bg-gradient-to-r from-indigo-600 to-violet-600 text-[13px] font-semibold text-white shadow-lg shadow-indigo-500/20 cursor-pointer">
            Tekrar Dene
          </button>
        </motion.div>
      </div>
    );
  }

  return (
    <div className="max-w-[1200px] mx-auto">
      {/* Header */}
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-2xl font-bold text-white tracking-tight">Karakterler</h1>
          <p className="text-sm text-slate-500 mt-1">AI karakterlerinizi oluşturun ve yönetin</p>
        </div>
        <motion.button
          whileHover={{ scale: 1.02 }}
          whileTap={{ scale: 0.98 }}
          onClick={() => navigate('/characters/new')}
          className="flex items-center gap-2 px-5 py-2.5 rounded-xl bg-gradient-to-r from-indigo-600 to-violet-600 text-[13px] font-semibold text-white shadow-lg shadow-indigo-500/20 cursor-pointer"
        >
          <UserPlus className="w-4 h-4" /> Yeni Karakter
        </motion.button>
      </div>

      {/* Filters */}
      <div className="flex flex-wrap items-center gap-3 mb-6">
        <div className="relative flex-1 max-w-sm">
          <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-500" />
          <input
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="İsme göre ara..."
            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>
        <div className="flex gap-2">
          {filterButtons.map((fb) => (
            <button
              key={fb.value}
              onClick={() => setStatusFilter(fb.value)}
              className={`px-4 py-2.5 rounded-xl text-[12px] font-medium transition-all cursor-pointer ${
                statusFilter === fb.value
                  ? 'bg-indigo-500/[0.12] text-indigo-400 ring-1 ring-indigo-500/30'
                  : 'bg-white/[0.03] border border-white/[0.06] text-slate-500 hover:text-slate-300 hover:bg-white/[0.06]'
              }`}
            >
              {fb.label}
            </button>
          ))}
        </div>
      </div>

      {/* Content */}
      <AnimatePresence mode="wait">
        {filtered.length === 0 ? (
          <motion.div key="empty" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
            className="rounded-2xl border border-white/[0.06] bg-white/[0.02] py-16 text-center">
            <Users className="w-8 h-8 text-slate-700 mx-auto mb-3" />
            <p className="text-[13px] text-slate-500">
              {characterList.length === 0 ? 'Henüz karakter oluşturulmamış.' : 'Filtreye uygun karakter bulunamadı.'}
            </p>
            {characterList.length === 0 && (
              <button onClick={() => navigate('/characters/new')}
                className="mt-4 text-[13px] text-indigo-400 hover:text-indigo-300 transition-colors cursor-pointer">
                İlk karakterinizi oluşturun →
              </button>
            )}
          </motion.div>
        ) : (
          <motion.div key="grid" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
            className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
            {filtered.map((c, i) => {
              const st = statusConfig[c.status] ?? statusConfig.inactive;
              return (
                <motion.button
                  key={c.id}
                  initial={{ opacity: 0, y: 16 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: i * 0.05 }}
                  whileHover={{ y: -2 }}
                  onClick={() => navigate(`/characters/${c.id}`)}
                  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-4">
                    <div className="flex items-center gap-3">
                      {imgErrors.has(c.id) ? (
                        <div className="w-[44px] h-[44px] rounded-full bg-gradient-to-br from-indigo-500/20 to-violet-500/20 border border-indigo-500/20 flex items-center justify-center shrink-0">
                          <span className="text-[15px] font-bold text-indigo-300">{(c.identity?.name ?? '?')[0].toUpperCase()}</span>
                        </div>
                      ) : (
                        <div className="relative w-[44px] h-[44px] shrink-0">
                          {!imgLoaded.has(c.id) && (
                            <div className="absolute inset-0 rounded-full bg-white/[0.06] animate-pulse" />
                          )}
                          <img
                            src={`/static/characters/${c.id}/reference-images/master.jpg`}
                            alt={c.identity?.name ?? ''}
                            className={`w-[44px] h-[44px] rounded-full object-cover border border-white/[0.06] ${!imgLoaded.has(c.id) ? 'opacity-0' : 'opacity-100'} transition-opacity duration-200`}
                            onLoad={() => setImgLoaded(prev => new Set(prev).add(c.id))}
                            onError={() => setImgErrors(prev => new Set(prev).add(c.id))}
                          />
                        </div>
                      )}
                      <div>
                        <h3 className="text-[15px] font-semibold text-white">{c.identity?.name ?? 'İsimsiz'}</h3>
                        <span className={`inline-flex items-center gap-1.5 mt-1 text-[11px] font-medium ${st.text}`}>
                          <span className={`w-1.5 h-1.5 rounded-full ${st.dot}`} />
                          {st.label}
                        </span>
                      </div>
                    </div>
                    <ArrowRight className="w-4 h-4 text-slate-700 group-hover:text-slate-400 transition-colors shrink-0 mt-1" />
                  </div>
                  <div className="space-y-2">
                    <div className="flex items-center gap-2 text-[12px] text-slate-500">
                      <Globe className="w-3.5 h-3.5 text-slate-600" />
                      <span>{c.identity?.nationality ?? '—'}</span>
                    </div>
                    <div className="flex items-center gap-2 text-[12px] text-slate-500">
                      <Briefcase className="w-3.5 h-3.5 text-slate-600" />
                      <span>{c.identity?.occupation ?? '—'}</span>
                    </div>
                  </div>
                </motion.button>
              );
            })}
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
};

export default CharacterList;
