import React, { useState, useEffect, useCallback } from 'react';
import { analytics, characters } from '../api/client';
import { motion } from 'framer-motion';
import { RefreshCw, MessageSquare, Users, Clock, TrendingUp, Star, ShoppingCart, Percent, UserCheck } from 'lucide-react';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';

interface Character { id: string; identity: { name: string }; status: string; }
interface CharacterAnalytics { characterId: string; period: 'daily' | 'weekly' | 'monthly'; date: string; conversations: { totalMessages: number; uniqueUsers: number; averageConversationDuration: number; averageMessagesPerConversation: number }; sales: { totalStarsEarned: number; totalTransactions: number; conversionRate: number; averageStarsPerUser: number; topSellingHours: number[] }; activity: { hourlyMessageCount: Record<number, number>; hourlyStarsCount: Record<number, number>; peakHour: number; quietHour: number }; }
interface ComparisonItem { characterId: string; characterName?: string; totalMessages: number; uniqueUsers: number; totalStarsEarned: number; conversionRate: number; peakHour: number; }
type Period = 'daily' | 'weekly' | 'monthly';

const StatCard: React.FC<{ label: string; value: number; icon: React.ElementType; color: string; gradient: string }> = ({ label, value, icon: Icon, color, gradient }) => (
  <motion.div whileHover={{ y: -2, scale: 1.03 }} className={`overflow-hidden rounded-2xl border border-white/[0.06] bg-gradient-to-br ${gradient} p-5 backdrop-blur-xl`}>
    <div className="mb-2 flex items-center gap-2"><div className={`flex h-7 w-7 items-center justify-center rounded-lg bg-white/[0.06] ${color}`}><Icon size={14} /></div><span className="text-xs text-slate-400">{label}</span></div>
    <div className={`text-3xl font-bold ${color}`}>{value}</div>
  </motion.div>
);

const Analytics: React.FC = () => {
  const [characterList, setCharacterList] = useState<Character[]>([]);
  const [selectedCharacterId, setSelectedCharacterId] = useState<string>('');
  const [period, setPeriod] = useState<Period>('daily');
  const [charAnalytics, setCharAnalytics] = useState<CharacterAnalytics | null>(null);
  const [comparison, setComparison] = useState<ComparisonItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => { (async () => { try { const res = await characters.list(); const list: Character[] = res.data?.data ?? res.data ?? []; setCharacterList(list); if (list.length > 0) setSelectedCharacterId(list[0].id); } catch { setError('Karakter listesi yüklenemedi.'); } finally { setLoading(false); } })(); }, []);

  const fetchAnalytics = useCallback(async () => {
    if (!selectedCharacterId) return; setError(null);
    try {
      const [analyticsRes, compRes] = await Promise.allSettled([analytics.getCharacterAnalytics(selectedCharacterId, { period }), analytics.getComparison()]);
      if (analyticsRes.status === 'fulfilled') setCharAnalytics(analyticsRes.value.data?.data ?? analyticsRes.value.data ?? null);
      if (compRes.status === 'fulfilled') { const compData = compRes.value.data?.data ?? compRes.value.data; setComparison(Array.isArray(compData) ? compData : []); }
      if (analyticsRes.status === 'rejected' && compRes.status === 'rejected') setError('Analitik verileri yüklenemedi.');
    } catch { setError('Analitik verileri yüklenirken bir hata oluştu.'); }
  }, [selectedCharacterId, period]);

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

  const hourlyData = React.useMemo(() => { const data: { hour: string; mesaj: number; stars: number }[] = []; for (let h = 0; h < 24; h++) { data.push({ hour: String(h).padStart(2, '0'), mesaj: charAnalytics?.activity?.hourlyMessageCount?.[h] ?? 0, stars: charAnalytics?.activity?.hourlyStarsCount?.[h] ?? 0 }); } return data; }, [charAnalytics]);
  const getCharacterName = (id: string) => characterList.find((c) => c.id === id)?.identity?.name ?? id;
  const periodLabels: Record<Period, string> = { daily: 'Günlük', weekly: 'Haftalık', monthly: 'Aylık' };

  if (loading) 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>;
  if (error && !charAnalytics && comparison.length === 0) return <div className="p-8"><div className="rounded-2xl border border-red-500/20 bg-red-500/5 p-6 backdrop-blur-xl"><p className="text-sm text-red-400/80 mb-4">{error}</p><motion.button whileHover={{ scale: 1.02 }} whileTap={{ scale: 0.98 }} onClick={fetchAnalytics} className="rounded-xl bg-gradient-to-r from-indigo-500 to-violet-500 px-5 py-2.5 text-sm font-semibold text-white shadow-lg shadow-indigo-500/25">Tekrar Dene</motion.button></div></div>;

  return (
    <div>
      <motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} className="mb-6 flex items-center justify-between">
        <h1 className="text-2xl font-bold bg-gradient-to-r from-indigo-400 via-violet-400 to-purple-400 bg-clip-text text-transparent">Analitik Paneli</h1>
        <motion.button whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} onClick={fetchAnalytics} className="flex items-center gap-2 rounded-xl bg-gradient-to-r from-indigo-500 to-violet-500 px-5 py-2.5 text-sm font-semibold text-white shadow-lg shadow-indigo-500/25"><RefreshCw size={16} /> Yenile</motion.button>
      </motion.div>
      {error && <div className="mb-4 rounded-xl border border-red-500/20 bg-red-500/5 p-3 text-sm text-red-300">{error}</div>}

      <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ delay: 0.1 }} className="mb-6 flex flex-wrap items-end gap-4">
        <div><label className="mb-1.5 block text-sm font-medium text-slate-400">Karakter</label>
          <select value={selectedCharacterId} onChange={(e) => setSelectedCharacterId(e.target.value)} className="min-w-[220px] 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">
            {characterList.length === 0 && <option value="">Karakter yok</option>}
            {characterList.map((c) => <option key={c.id} value={c.id}>{c.identity?.name ?? c.id}</option>)}
          </select></div>
        <div><label className="mb-1.5 block text-sm font-medium text-slate-400">Dönem</label>
          <div className="flex overflow-hidden rounded-xl border border-white/[0.06]">
            {(['daily', 'weekly', 'monthly'] as Period[]).map((p) => (
              <button key={p} onClick={() => setPeriod(p)} className={`px-5 py-2.5 text-sm font-medium transition-all ${period === p ? 'bg-gradient-to-r from-indigo-500 to-violet-500 text-white' : 'bg-white/[0.03] text-slate-400 hover:bg-white/[0.06] hover:text-slate-200'}`}>{periodLabels[p]}</button>
            ))}
          </div></div>
      </motion.div>

      <h2 className="text-lg font-semibold text-slate-100 mb-4">Konuşma İstatistikleri</h2>
      <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="mb-8 grid grid-cols-[repeat(auto-fit,minmax(200px,1fr))] gap-4">
        <StatCard label="Toplam Mesaj" value={charAnalytics?.conversations?.totalMessages ?? 0} icon={MessageSquare} color="text-blue-400" gradient="from-blue-500/10 to-blue-500/5" />
        <StatCard label="Benzersiz Kullanıcı" value={charAnalytics?.conversations?.uniqueUsers ?? 0} icon={Users} color="text-violet-400" gradient="from-violet-500/10 to-violet-500/5" />
        <StatCard label="Ort. Konuşma Süresi (dk)" value={charAnalytics?.conversations?.averageConversationDuration ?? 0} icon={Clock} color="text-cyan-400" gradient="from-cyan-500/10 to-cyan-500/5" />
        <StatCard label="Ort. Mesaj/Konuşma" value={charAnalytics?.conversations?.averageMessagesPerConversation ?? 0} icon={TrendingUp} color="text-teal-400" gradient="from-teal-500/10 to-teal-500/5" />
      </motion.div>

      <h2 className="text-lg font-semibold text-slate-100 mb-4">Satış İstatistikleri</h2>
      <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.1 }} className="mb-8 grid grid-cols-[repeat(auto-fit,minmax(200px,1fr))] gap-4">
        <StatCard label="Toplam Stars" value={charAnalytics?.sales?.totalStarsEarned ?? 0} icon={Star} color="text-yellow-400" gradient="from-yellow-500/10 to-yellow-500/5" />
        <StatCard label="İşlem Sayısı" value={charAnalytics?.sales?.totalTransactions ?? 0} icon={ShoppingCart} color="text-amber-400" gradient="from-amber-500/10 to-amber-500/5" />
        <StatCard label="Dönüşüm Oranı (%)" value={Number((charAnalytics?.sales?.conversionRate ?? 0).toFixed(1))} icon={Percent} color="text-emerald-400" gradient="from-emerald-500/10 to-emerald-500/5" />
        <StatCard label="Ort. Stars/Kullanıcı" value={Number((charAnalytics?.sales?.averageStarsPerUser ?? 0).toFixed(1))} icon={UserCheck} color="text-red-400" gradient="from-red-500/10 to-red-500/5" />
      </motion.div>

      <h2 className="text-lg font-semibold text-slate-100 mb-4">Saatlik Aktivite Haritası</h2>
      <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ delay: 0.2 }} className="mb-8 rounded-2xl border border-white/[0.06] bg-white/[0.03] p-5 backdrop-blur-xl">
        {charAnalytics ? (
          <ResponsiveContainer width="100%" height={320}>
            <BarChart data={hourlyData} margin={{ top: 8, right: 16, left: 0, bottom: 0 }}>
              <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.04)" />
              <XAxis dataKey="hour" tick={{ fontSize: 12, fill: '#64748b' }} label={{ value: 'Saat', position: 'insideBottomRight', offset: -4, fontSize: 12, fill: '#64748b' }} />
              <YAxis tick={{ fontSize: 12, fill: '#64748b' }} />
              <Tooltip contentStyle={{ background: '#12121a', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 12, fontSize: 13, color: '#e2e8f0' }} labelFormatter={(v) => `Saat: ${v}:00`} />
              <Legend wrapperStyle={{ fontSize: 13 }} />
              <Bar dataKey="mesaj" name="Mesaj Sayısı" fill="#6366f1" radius={[6, 6, 0, 0]} />
              <Bar dataKey="stars" name="Stars Kazancı" fill="#eab308" radius={[6, 6, 0, 0]} />
            </BarChart>
          </ResponsiveContainer>
        ) : <p className="m-0 p-8 text-center text-slate-400">Veri bulunamadı.</p>}
        {charAnalytics?.activity && (
          <div className="mt-4 flex flex-wrap gap-6 text-sm text-slate-400">
            <span>🔥 En Yoğun Saat: <strong className="text-slate-100">{String(charAnalytics.activity.peakHour).padStart(2, '0')}:00</strong></span>
            <span>😴 En Sakin Saat: <strong className="text-slate-100">{String(charAnalytics.activity.quietHour).padStart(2, '0')}:00</strong></span>
            {charAnalytics.sales?.topSellingHours?.length > 0 && <span>⭐ En Çok Satış: <strong className="text-slate-100">{charAnalytics.sales.topSellingHours.map((h) => `${String(h).padStart(2, '0')}:00`).join(', ')}</strong></span>}
          </div>
        )}
      </motion.div>

      <h2 className="text-lg font-semibold text-slate-100 mb-4">Karakter Karşılaştırması</h2>
      <div className="overflow-hidden rounded-2xl border border-white/[0.06] bg-white/[0.03] backdrop-blur-xl">
        {comparison.length === 0 ? <p className="m-0 p-8 text-center text-slate-400">Karşılaştırma verisi bulunamadı.</p> : (
          <div className="overflow-x-auto">
            <table className="w-full border-collapse text-sm">
              <thead><tr className="border-b border-white/[0.06]">{['Karakter', 'Toplam Mesaj', 'Benzersiz Kullanıcı', 'Toplam Stars', 'Dönüşüm (%)', 'En Yoğun Saat'].map((h) => <th key={h} className="whitespace-nowrap px-5 py-4 text-left text-xs font-semibold uppercase tracking-wider text-slate-500">{h}</th>)}</tr></thead>
              <tbody>{comparison.map((i) => (
                <tr key={i.characterId} className="border-b border-white/[0.04] transition-colors hover:bg-white/[0.02]">
                  <td className="whitespace-nowrap px-5 py-4 font-semibold text-slate-200">{i.characterName ?? getCharacterName(i.characterId)}</td>
                  <td className="whitespace-nowrap px-5 py-4 text-slate-300">{i.totalMessages}</td>
                  <td className="whitespace-nowrap px-5 py-4 text-slate-300">{i.uniqueUsers}</td>
                  <td className="whitespace-nowrap px-5 py-4 text-slate-300">⭐ {i.totalStarsEarned}</td>
                  <td className="whitespace-nowrap px-5 py-4 text-slate-300">{(i.conversionRate ?? 0).toFixed(1)}%</td>
                  <td className="whitespace-nowrap px-5 py-4 text-slate-300">{String(i.peakHour ?? 0).padStart(2, '0')}:00</td>
                </tr>
              ))}</tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
};

export default Analytics;