import { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { characters, queue, system, analytics } from '../api/client';
import { motion } from 'framer-motion';
import {
  Users, MessageSquare, Zap, Star, RefreshCw, Plus, ArrowRight,
  ArrowUpRight, TrendingUp, Activity,
} from 'lucide-react';

interface Character {
  id: string;
  status: 'active' | 'inactive' | 'creating';
  identity: { name: string; personality?: string; occupation?: string; nationality?: string };
  dailyMessageCount?: number;
  starsEarned?: number;
}

const Dashboard: React.FC = () => {
  const navigate = useNavigate();
  const [chars, setChars] = useState<Character[]>([]);
  const [queueCount, setQueueCount] = useState(0);
  const [healthy, setHealthy] = useState(false);
  const [overview, setOverview] = useState<{ totalMessages?: number; totalStars?: number; activeConversations?: number }>({});
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const [c, q, h, a] = await Promise.allSettled([
        characters.list(), queue.getStatus(), system.health(), analytics.getOverview(),
      ]);
      if (c.status === 'fulfilled') setChars(c.value.data?.data ?? c.value.data ?? []);
      if (q.status === 'fulfilled') {
        const qd = q.value.data?.data ?? q.value.data;
        setQueueCount((qd?.pending ?? 0) + (qd?.processing ?? 0));
      }
      if (h.status === 'fulfilled') setHealthy((h.value.data?.data ?? h.value.data)?.status === 'ok');
      if (a.status === 'fulfilled') setOverview(a.value.data?.data ?? a.value.data ?? {});
    } catch {}
    setLoading(false);
  }, []);

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

  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>
  );

  const active = chars.filter(c => c.status === 'active').length;
  const totalMsg = overview.totalMessages ?? 0;
  const totalStars = overview.totalStars ?? 0;
  const activeConvos = overview.activeConversations ?? 0;

  const statCards = [
    {
      label: 'Toplam Karakter',
      value: chars.length,
      sub: `${active} aktif`,
      icon: Users,
      iconBg: 'bg-indigo-500',
      iconColor: 'text-white',
      trend: active > 0 ? `${active} aktif` : undefined,
      trendUp: active > 0,
    },
    {
      label: 'Toplam Mesaj',
      value: totalMsg,
      sub: 'tüm zamanlar',
      icon: MessageSquare,
      iconBg: 'bg-emerald-500',
      iconColor: 'text-white',
      trend: totalMsg > 0 ? '+%12' : undefined,
      trendUp: true,
    },
    {
      label: 'Aktif Sohbet',
      value: activeConvos,
      sub: 'şu an',
      icon: Activity,
      iconBg: 'bg-violet-500',
      iconColor: 'text-white',
      trend: activeConvos > 0 ? 'canlı' : undefined,
      trendUp: true,
    },
    {
      label: 'Stars Geliri',
      value: totalStars,
      sub: 'kazanılan',
      icon: Star,
      iconBg: 'bg-amber-500',
      iconColor: 'text-white',
      trend: totalStars > 0 ? '+%8' : undefined,
      trendUp: true,
    },
  ];

  const statusColor: Record<string, string> = {
    active: 'bg-emerald-500',
    inactive: 'bg-slate-500',
    creating: 'bg-amber-500',
  };
  const statusLabel: Record<string, string> = {
    active: 'Aktif',
    inactive: 'Pasif',
    creating: 'Oluşturuluyor',
  };

  return (
    <div className="max-w-[1200px] mx-auto">
      {/* Page header */}
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-2xl font-bold text-white tracking-tight">
            Dashboard
          </h1>
          <p className="text-sm text-slate-500 mt-1">AI Content Creator yönetim paneli</p>
        </div>
        <div className="flex items-center gap-3">
          <div className="flex items-center gap-2 px-3 py-1.5 rounded-lg bg-white/[0.03] border border-white/[0.06]">
            <div className={`h-2 w-2 rounded-full ${healthy ? 'bg-emerald-400 animate-pulse' : 'bg-red-400'}`} />
            <span className="text-[12px] text-slate-400">
              {healthy ? 'Sistem Aktif' : 'Bağlantı Sorunu'}
            </span>
          </div>
          <button
            onClick={() => load()}
            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>

      {/* Stat cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-5 mb-8">
        {statCards.map((card, i) => {
          const Icon = card.icon;
          return (
            <motion.div
              key={card.label}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: i * 0.08 }}
              className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-5 hover:border-white/[0.1] transition-all"
            >
              <div className="flex items-start justify-between mb-4">
                <div className={`w-11 h-11 rounded-xl ${card.iconBg} flex items-center justify-center shadow-lg`}>
                  <Icon className={`w-5 h-5 ${card.iconColor}`} />
                </div>
                {card.trend && (
                  <span className={`flex items-center gap-1 text-[11px] font-medium px-2 py-0.5 rounded-full ${
                    card.trendUp
                      ? 'text-emerald-400 bg-emerald-500/10'
                      : 'text-red-400 bg-red-500/10'
                  }`}>
                    {card.trendUp ? <TrendingUp className="w-3 h-3" /> : null}
                    {card.trend}
                  </span>
                )}
              </div>
              <div className="text-[28px] font-bold text-white leading-none tracking-tight tabular-nums">
                {card.value.toLocaleString('tr-TR')}
              </div>
              <div className="text-[13px] text-slate-500 mt-1">{card.label}</div>
            </motion.div>
          );
        })}
      </div>

      {/* Content grid */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
        {/* Characters list — 2 cols */}
        <div className="lg:col-span-2 rounded-2xl border border-white/[0.06] bg-white/[0.02] overflow-hidden">
          <div className="flex items-center justify-between px-6 py-4 border-b border-white/[0.06]">
            <h2 className="text-[15px] font-semibold text-white">Karakterler</h2>
            <button
              onClick={() => navigate('/characters/new')}
              className="flex items-center gap-1.5 text-[12px] text-indigo-400 hover:text-indigo-300 transition-colors cursor-pointer font-medium"
            >
              <Plus className="w-3.5 h-3.5" /> Yeni Karakter
            </button>
          </div>

          {chars.length === 0 ? (
            <div className="py-16 text-center">
              <p className="text-[13px] text-slate-500 mb-4">Henüz karakter oluşturulmadı</p>
              <button
                onClick={() => navigate('/characters/new')}
                className="text-[13px] text-indigo-400 hover:text-indigo-300 transition-colors cursor-pointer"
              >
                İlk karakterini oluştur →
              </button>
            </div>
          ) : (
            <div>
              {/* Table header */}
              <div className="grid grid-cols-[1fr_100px_80px_80px_40px] gap-4 px-6 py-3 text-[11px] font-semibold text-slate-500 uppercase tracking-wider border-b border-white/[0.04]">
                <span>Karakter</span>
                <span>Durum</span>
                <span className="text-right">Mesaj</span>
                <span className="text-right">Stars</span>
                <span />
              </div>
              {/* Rows */}
              {chars.map((c, i) => (
                <motion.button
                  key={c.id}
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  transition={{ delay: i * 0.05 }}
                  onClick={() => navigate(`/characters/${c.id}`)}
                  className="grid grid-cols-[1fr_100px_80px_80px_40px] gap-4 items-center w-full px-6 py-3.5 hover:bg-white/[0.02] transition-colors cursor-pointer text-left border-b border-white/[0.03] last:border-b-0"
                >
                  <div className="flex items-center gap-3 min-w-0">
                    <div className="w-9 h-9 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-[13px] font-semibold text-indigo-300">
                        {(c.identity?.name ?? '?')[0].toUpperCase()}
                      </span>
                    </div>
                    <div className="min-w-0">
                      <div className="text-[13px] font-medium text-slate-200 truncate">
                        {c.identity?.name ?? 'İsimsiz'}
                      </div>
                      <div className="text-[11px] text-slate-600 truncate">
                        {c.identity?.occupation ?? c.identity?.nationality ?? '—'}
                      </div>
                    </div>
                  </div>
                  <div>
                    <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-medium ${
                      c.status === 'active'
                        ? 'bg-emerald-500/10 text-emerald-400 ring-1 ring-emerald-500/20'
                        : c.status === 'creating'
                          ? 'bg-amber-500/10 text-amber-400 ring-1 ring-amber-500/20'
                          : 'bg-slate-500/10 text-slate-400 ring-1 ring-slate-500/20'
                    }`}>
                      <span className={`w-1.5 h-1.5 rounded-full ${statusColor[c.status]}`} />
                      {statusLabel[c.status] ?? c.status}
                    </span>
                  </div>
                  <div className="text-[13px] text-slate-400 tabular-nums text-right">
                    {(c.dailyMessageCount ?? 0).toLocaleString('tr-TR')}
                  </div>
                  <div className="text-[13px] text-slate-400 tabular-nums text-right">
                    {(c.starsEarned ?? 0).toLocaleString('tr-TR')}
                  </div>
                  <div className="flex justify-end">
                    <ArrowRight className="w-4 h-4 text-slate-700 group-hover:text-slate-400" />
                  </div>
                </motion.button>
              ))}
            </div>
          )}
        </div>

        {/* Right sidebar cards */}
        <div className="space-y-5">
          {/* Queue status */}
          <div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-5">
            <div className="flex items-center gap-2 mb-4">
              <Zap className="w-4 h-4 text-amber-400" />
              <h3 className="text-[14px] font-semibold text-white">İşlem Kuyruğu</h3>
            </div>
            <div className="flex items-end gap-2">
              <span className="text-[32px] font-bold text-white leading-none tabular-nums">{queueCount}</span>
              <span className="text-[12px] text-slate-500 mb-1">bekleyen görev</span>
            </div>
            {queueCount > 0 && (
              <div className="mt-3 h-1.5 rounded-full bg-white/[0.06] overflow-hidden">
                <motion.div
                  className="h-full rounded-full bg-gradient-to-r from-amber-500 to-orange-500"
                  initial={{ width: 0 }}
                  animate={{ width: '60%' }}
                  transition={{ duration: 1, ease: 'easeOut' }}
                />
              </div>
            )}
          </div>

          {/* Quick actions */}
          <div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-5">
            <h3 className="text-[14px] font-semibold text-white mb-4">Hızlı İşlemler</h3>
            <div className="space-y-2">
              {[
                { label: 'Yeni Karakter', path: '/characters/new', color: 'text-indigo-400' },
                { label: 'API Ayarları', path: '/settings/api', color: 'text-violet-400' },
                { label: 'Konuşma Tarzı', path: '/settings/persona', color: 'text-emerald-400' },
                { label: 'Şablonlar', path: '/templates', color: 'text-pink-400' },
              ].map((action) => (
                <button
                  key={action.path}
                  onClick={() => navigate(action.path)}
                  className="flex items-center justify-between w-full px-3 py-2.5 rounded-xl hover:bg-white/[0.04] transition-all cursor-pointer group"
                >
                  <span className={`text-[13px] font-medium ${action.color}`}>{action.label}</span>
                  <ArrowUpRight className="w-3.5 h-3.5 text-slate-600 group-hover:text-slate-400 transition-colors" />
                </button>
              ))}
            </div>
          </div>

          {/* System info */}
          <div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-5">
            <h3 className="text-[14px] font-semibold text-white mb-3">Sistem Bilgisi</h3>
            <div className="space-y-2.5">
              <div className="flex items-center justify-between">
                <span className="text-[12px] text-slate-500">Durum</span>
                <span className={`text-[12px] font-medium ${healthy ? 'text-emerald-400' : 'text-red-400'}`}>
                  {healthy ? 'Çalışıyor' : 'Sorun Var'}
                </span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-[12px] text-slate-500">Aktif Karakter</span>
                <span className="text-[12px] font-medium text-slate-300">{active}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-[12px] text-slate-500">Kuyruk</span>
                <span className="text-[12px] font-medium text-slate-300">{queueCount} görev</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Dashboard;
