import { useState, useEffect, useCallback } from 'react';
import type { FC } from 'react';
import TelegramSubNav from '../../components/TelegramSubNav';
import { characters, stars } from '../../api/client';
import { filterTransactions, formatDateTR } from '../../types/telegram';
import type { CharacterSummary, StarsStats, StarsTransaction } from '../../types/telegram';
import { motion } from 'framer-motion';
import { Star, Receipt, PieChart } from 'lucide-react';

const selectClass = 'w-full rounded-xl border border-white/[0.06] bg-white/[0.03] px-4 py-2.5 text-sm text-slate-100 outline-none transition-all focus:border-indigo-500/50 focus:ring-2 focus:ring-indigo-500/20 backdrop-blur-xl';
const glassCard = 'rounded-2xl border border-white/[0.06] bg-white/[0.03] backdrop-blur-xl';

const StarsRevenue: FC = () => {
  const [charList, setCharList] = useState<CharacterSummary[]>([]); const [selectedCharId, setSelectedCharId] = useState<string | null>(null);
  const [stats, setStats] = useState<StarsStats | null>(null); const [transactions, setTransactions] = useState<StarsTransaction[]>([]);
  const [loading, setLoading] = useState(true); const [statsLoading, setStatsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null); const [period, setPeriod] = useState<string>('');
  const [activeTab, setActiveTab] = useState<'overview' | 'transactions'>('overview');
  const [typeFilter, setTypeFilter] = useState('all'); const [statusFilter, setStatusFilter] = useState('all');

  const fetchChars = useCallback(async () => { try { setLoading(true); const res = await characters.list(); const data = res.data?.data ?? res.data ?? []; setCharList(Array.isArray(data) ? data : []); } catch { setError('Karakter listesi yüklenemedi.'); } finally { setLoading(false); } }, []);
  useEffect(() => { fetchChars(); }, [fetchChars]);
  const fetchStats = useCallback(async (charId: string, p?: string) => { setStatsLoading(true); try { const [statsRes, txRes] = await Promise.all([stars.getStats(charId, p || undefined), stars.getTransactions(charId)]); setStats(statsRes.data?.data ?? statsRes.data?.stats ?? statsRes.data ?? null); const txData = txRes.data?.data ?? txRes.data?.transactions ?? txRes.data ?? []; setTransactions(Array.isArray(txData) ? txData : []); } catch { setStats(null); setTransactions([]); } setStatsLoading(false); }, []);
  useEffect(() => { if (selectedCharId) fetchStats(selectedCharId, period); }, [selectedCharId, period, fetchStats]);

  const filtered = filterTransactions(transactions, typeFilter, statusFilter);
  const statusLabels: Record<string, string> = { pending: 'Bekleyen', completed: 'Tamamlanan', refunded: 'İade' };
  const typeLabels: Record<string, string> = { payment: 'Ödeme', reaction: 'Reaksiyon' };

  return (
    <div>
      <TelegramSubNav />
      <motion.h1 initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} className="mb-6 text-2xl font-bold bg-gradient-to-r from-indigo-400 via-violet-400 to-purple-400 bg-clip-text text-transparent">⭐ Stars Gelir Takibi</motion.h1>
      {error && <div className="mb-4 rounded-xl border border-red-500/20 bg-red-500/5 p-4 text-sm text-red-400"><p>{error}</p><button onClick={() => setError(null)} className="mt-2 rounded-xl bg-gradient-to-r from-indigo-500 to-violet-500 px-4 py-2 text-sm font-semibold text-white shadow-lg shadow-indigo-500/25">Kapat</button></div>}
      {loading ? <div className="flex min-h-[30vh] items-center justify-center"><div className="h-8 w-8 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent" /></div> : (<>
        <div className="mb-6"><label className="mb-1.5 block text-sm font-medium text-slate-400">Karakter Seçin</label><select value={selectedCharId ?? ''} onChange={e => setSelectedCharId(e.target.value || null)} className={`max-w-md ${selectClass}`}><option value="">— Karakter seçin —</option>{charList.map(c => <option key={c.id} value={c.id}>{c.identity?.name ?? c.id}</option>)}</select></div>
        {selectedCharId && (<>
          <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="mb-4 flex gap-2">
            {[{ v: '', l: 'Tümü' }, { v: 'daily', l: 'Günlük' }, { v: 'weekly', l: 'Haftalık' }, { v: 'monthly', l: 'Aylık' }].map(p => (
              <motion.button key={p.v} whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }} onClick={() => setPeriod(p.v)}
                className={`rounded-xl px-4 py-2 text-sm font-medium transition-all ${period === p.v ? 'bg-gradient-to-r from-indigo-500/15 to-violet-500/15 text-indigo-400 ring-1 ring-indigo-500/30' : 'border border-white/[0.06] bg-white/[0.03] text-slate-400 hover:bg-white/[0.06] hover:text-slate-200'}`}>{p.l}</motion.button>
            ))}
          </motion.div>
          <div className="mb-5 flex gap-1 rounded-xl border border-white/[0.06] bg-white/[0.02] p-1">
            {[{ k: 'overview' as const, l: 'Genel Bakış' }, { k: 'transactions' as const, l: 'İşlem Geçmişi' }].map(t => (
              <button key={t.k} onClick={() => setActiveTab(t.k)}
                className={`relative rounded-lg px-5 py-2.5 text-sm font-medium transition-all ${activeTab === t.k ? 'text-white' : 'text-slate-400 hover:bg-white/[0.04] hover:text-slate-200'}`}>
                {activeTab === t.k && <motion.div layoutId="starsTab" className="absolute inset-0 rounded-lg bg-gradient-to-r from-indigo-500 to-violet-500 shadow-lg shadow-indigo-500/20" transition={{ type: 'spring', stiffness: 350, damping: 30 }} />}
                <span className="relative z-10">{t.l}</span>
              </button>
            ))}
          </div>
          {statsLoading ? <div className="flex min-h-[20vh] items-center justify-center"><div className="h-8 w-8 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent" /></div>
          : activeTab === 'overview' ? (
            <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="grid grid-cols-1 gap-4 sm:grid-cols-3">
              <motion.div whileHover={{ y: -2, scale: 1.03 }} className={`${glassCard} p-6 text-center`}><Star size={20} className="mx-auto mb-2 text-yellow-400" /><div className="text-xs text-slate-400">Toplam Kazanç</div><div className="mt-1 text-2xl font-bold text-slate-100">⭐ {stats?.totalEarned ?? 0}</div></motion.div>
              <motion.div whileHover={{ y: -2, scale: 1.03 }} className={`${glassCard} p-6 text-center`}><Receipt size={20} className="mx-auto mb-2 text-indigo-400" /><div className="text-xs text-slate-400">Toplam İşlem</div><div className="mt-1 text-2xl font-bold text-slate-100">{stats?.totalTransactions ?? 0}</div></motion.div>
              <motion.div whileHover={{ y: -2, scale: 1.03 }} className={`${glassCard} p-6 text-center`}><PieChart size={20} className="mx-auto mb-2 text-violet-400" /><div className="text-xs text-slate-400">Tür Dağılımı</div><div className="mt-1 text-sm text-slate-300">Ödeme: {stats?.byType?.payment ?? 0} | Reaksiyon: {stats?.byType?.reaction ?? 0}</div></motion.div>
            </motion.div>
          ) : (<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }}>
            <div className="mb-4 flex flex-wrap gap-3">
              <select value={typeFilter} onChange={e => setTypeFilter(e.target.value)} className="rounded-xl border border-white/[0.06] bg-white/[0.03] px-4 py-2 text-xs text-slate-100 outline-none transition-all focus:border-indigo-500/50"><option value="all">Tür: Tümü</option><option value="payment">Ödeme</option><option value="reaction">Reaksiyon</option></select>
              <select value={statusFilter} onChange={e => setStatusFilter(e.target.value)} className="rounded-xl border border-white/[0.06] bg-white/[0.03] px-4 py-2 text-xs text-slate-100 outline-none transition-all focus:border-indigo-500/50"><option value="all">Durum: Tümü</option><option value="pending">Bekleyen</option><option value="completed">Tamamlanan</option><option value="refunded">İade</option></select>
            </div>
            {filtered.length === 0 ? <div className={`${glassCard} p-12 text-center text-slate-400`}>Bu karakter için henüz Stars işlemi bulunmuyor.</div> : (
              <div className={`${glassCard} overflow-hidden`}>
                <table className="w-full border-collapse">
                  <thead><tr className="border-b border-white/[0.06]">{['ID', 'Tür', 'Miktar', 'Durum', 'Tarih'].map(h => <th key={h} className="px-5 py-4 text-left text-xs font-semibold uppercase tracking-wider text-slate-500">{h}</th>)}</tr></thead>
                  <tbody>{filtered.map((tx) => (
                    <tr key={tx.id} className="border-b border-white/[0.04] transition-colors hover:bg-white/[0.02]">
                      <td className="px-5 py-4 font-mono text-xs text-slate-500">{tx.id.slice(0, 8)}...</td>
                      <td className="px-5 py-4 text-sm text-slate-300">{typeLabels[tx.type] ?? tx.type}</td>
                      <td className="px-5 py-4 text-sm text-slate-300">⭐ {tx.starCount}</td>
                      <td className="px-5 py-4"><span className={tx.status === 'completed' ? 'rounded-full bg-emerald-500/10 px-3 py-1 text-xs font-semibold text-emerald-400 ring-1 ring-emerald-500/20' : tx.status === 'refunded' ? 'rounded-full bg-red-500/10 px-3 py-1 text-xs font-semibold text-red-400 ring-1 ring-red-500/20' : 'rounded-full bg-amber-500/10 px-3 py-1 text-xs font-semibold text-amber-400 ring-1 ring-amber-500/20'}>{statusLabels[tx.status] ?? tx.status}</span></td>
                      <td className="px-5 py-4 text-sm text-slate-400">{formatDateTR(tx.createdAt)}</td>
                    </tr>
                  ))}</tbody>
                </table>
              </div>
            )}
          </motion.div>)}
        </>)}
      </>)}
    </div>
  );
};

export default StarsRevenue;