'use client';

import { useState, useEffect } from 'react';
import { api } from '@/lib/api';

// ==========================================
// SVG Icons
// ==========================================
function IconUsers({ size = 18, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>;
}
function IconUserCheck({ size = 18, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="8.5" cy="7" r="4"/><polyline points="17 11 19 13 23 9"/></svg>;
}
function IconUserPlus({ size = 18, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="8.5" cy="7" r="4"/><line x1="20" x2="20" y1="8" y2="14"/><line x1="23" x2="17" y1="11" y2="11"/></svg>;
}
function IconMessageSquare({ size = 18, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>;
}
function IconFileText({ size = 18, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" x2="8" y1="13" y2="13"/><line x1="16" x2="8" y1="17" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>;
}
function IconShoppingBag({ size = 18, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M6 2 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z"/><line x1="3" x2="21" y1="6" y2="6"/><path d="M16 10a4 4 0 0 1-8 0"/></svg>;
}
function IconMail({ size = 18, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect width="20" height="16" x="2" y="4" rx="2"/><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/></svg>;
}
function IconDollarSign({ size = 18, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><line x1="12" x2="12" y1="2" y2="22"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>;
}
function IconTrendingUp({ size = 14, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/><polyline points="17 6 23 6 23 12"/></svg>;
}
function IconTrendingDown({ size = 14, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="23 18 13.5 8.5 8.5 13.5 1 6"/><polyline points="17 18 23 18 23 12"/></svg>;
}

// ==========================================
// Types
// ==========================================

interface StatCard {
  label: string;
  value: string;
  trend: string;
  trendUp: boolean;
  icon: React.ReactNode;
  color: string;
  chartData: number[];
}

interface ActivityItem {
  id: string;
  text: string;
  time: string;
  type: string;
}

interface AdminStats {
  totalPlayers: number;
  activePlayers24h: number;
  totalDiscussions: number;
  totalReplies: number;
  totalBlogPosts: number;
  totalListings: number;
  pendingModeration: number;
  newsletterSubscribers: number;
}

const activityColors: Record<string, string> = {
  forum: '#60a5fa',
  user: '#22c55e',
  blog: '#ec4899',
  moderation: 'var(--color-red-light)',
  marketplace: '#f59e0b',
  newsletter: '#14b8a6',
  shop: 'var(--color-gold)',
};

// ==========================================
// Helpers
// ==========================================

function formatNumber(n: number): string {
  return n.toLocaleString('fr-FR');
}

function buildStatsCards(stats: AdminStats): StatCard[] {
  return [
    {
      label: 'Total Joueurs',
      value: formatNumber(stats.totalPlayers),
      trend: '',
      trendUp: true,
      icon: <IconUsers size={20} />,
      color: 'var(--color-gold)',
      chartData: [30, 45, 38, 52, 60, 55, stats.totalPlayers % 100 || 72],
    },
    {
      label: 'Joueurs Actifs (24h)',
      value: formatNumber(stats.activePlayers24h),
      trend: '',
      trendUp: true,
      icon: <IconUserCheck size={20} />,
      color: '#22c55e',
      chartData: [20, 35, 28, 40, 32, 45, stats.activePlayers24h % 100 || 42],
    },
    {
      label: 'Discussions Forum',
      value: formatNumber(stats.totalDiscussions),
      trend: '',
      trendUp: true,
      icon: <IconMessageSquare size={20} />,
      color: '#a78bfa',
      chartData: [50, 62, 55, 70, 68, 75, stats.totalDiscussions % 100 || 80],
    },
    {
      label: 'Réponses Forum',
      value: formatNumber(stats.totalReplies),
      trend: '',
      trendUp: true,
      icon: <IconMessageSquare size={20} />,
      color: '#60a5fa',
      chartData: [40, 55, 48, 60, 58, 65, stats.totalReplies % 100 || 70],
    },
    {
      label: 'Articles Blog',
      value: formatNumber(stats.totalBlogPosts),
      trend: '',
      trendUp: true,
      icon: <IconFileText size={20} />,
      color: '#ec4899',
      chartData: [3, 5, 4, 6, 5, 7, stats.totalBlogPosts % 10 || 6],
    },
    {
      label: 'Annonces Marketplace',
      value: formatNumber(stats.totalListings),
      trend: '',
      trendUp: true,
      icon: <IconShoppingBag size={20} />,
      color: '#f59e0b',
      chartData: [80, 75, 82, 70, 65, 72, stats.totalListings % 100 || 68],
    },
    {
      label: 'Abonnés Newsletter',
      value: formatNumber(stats.newsletterSubscribers),
      trend: '',
      trendUp: true,
      icon: <IconMail size={20} />,
      color: '#14b8a6',
      chartData: [100, 110, 115, 125, 130, 140, stats.newsletterSubscribers % 200 || 150],
    },
    {
      label: 'Modération en attente',
      value: formatNumber(stats.pendingModeration),
      trend: '',
      trendUp: stats.pendingModeration === 0,
      icon: <IconDollarSign size={20} />,
      color: 'var(--color-red-light)',
      chartData: [5, 8, 3, 10, 7, 4, stats.pendingModeration % 20 || 6],
    },
  ];
}

// ==========================================
// Mini Chart Component
// ==========================================
function MiniChart({ data, color }: { data: number[]; color: string }) {
  const max = Math.max(...data);

  return (
    <div className="flex items-end gap-[2px] h-8 mt-2">
      {data.map((val, i) => (
        <div
          key={i}
          className="flex-1 rounded-sm transition-all"
          style={{
            height: `${(val / max) * 100}%`,
            background: i === data.length - 1
              ? color
              : `${color}40`,
            minWidth: '3px',
          }}
        />
      ))}
    </div>
  );
}

// ==========================================
// Loading Skeleton
// ==========================================
function StatCardSkeleton() {
  return (
    <div
      className="p-4 rounded-xl animate-pulse"
      style={{
        background: 'var(--bg-card)',
        border: '1px solid var(--border-dark)',
      }}
    >
      <div className="flex items-start justify-between mb-2">
        <div className="w-10 h-10 rounded-lg" style={{ background: 'rgba(255,255,255,0.05)' }} />
        <div className="w-12 h-4 rounded-full" style={{ background: 'rgba(255,255,255,0.05)' }} />
      </div>
      <div className="w-20 h-6 rounded mb-1" style={{ background: 'rgba(255,255,255,0.05)' }} />
      <div className="w-24 h-3 rounded" style={{ background: 'rgba(255,255,255,0.03)' }} />
      <div className="flex items-end gap-[2px] h-8 mt-2">
        {[...Array(7)].map((_, i) => (
          <div
            key={i}
            className="flex-1 rounded-sm"
            style={{
              height: `${30 + Math.random() * 50}%`,
              background: 'rgba(255,255,255,0.05)',
              minWidth: '3px',
            }}
          />
        ))}
      </div>
    </div>
  );
}

function ActivitySkeleton() {
  return (
    <div className="space-y-2">
      {[...Array(6)].map((_, i) => (
        <div
          key={i}
          className="flex items-start gap-3 p-3 rounded-lg animate-pulse"
          style={{ background: 'rgba(255,255,255,0.02)' }}
        >
          <span
            className="w-2 h-2 rounded-full mt-1.5 flex-shrink-0"
            style={{ background: 'rgba(255,255,255,0.1)' }}
          />
          <div className="flex-1 min-w-0">
            <div className="w-3/4 h-3 rounded mb-1.5" style={{ background: 'rgba(255,255,255,0.05)' }} />
            <div className="w-16 h-2 rounded" style={{ background: 'rgba(255,255,255,0.03)' }} />
          </div>
        </div>
      ))}
    </div>
  );
}

// ==========================================
// Component
// ==========================================
export default function AdminDashboard() {
  const [statsCards, setStatsCards] = useState<StatCard[]>([]);
  const [activity, setActivity] = useState<ActivityItem[]>([]);
  const [statsLoading, setStatsLoading] = useState(true);
  const [activityLoading, setActivityLoading] = useState(true);
  const [statsError, setStatsError] = useState(false);
  const [activityError, setActivityError] = useState(false);
  const [pendingModeration, setPendingModeration] = useState<number | null>(null);

  useEffect(() => {
    let cancelled = false;

    async function fetchStats() {
      try {
        setStatsLoading(true);
        setStatsError(false);
        const data = (await api.admin.getStats()) as AdminStats;
        if (cancelled) return;
        setStatsCards(buildStatsCards(data));
        setPendingModeration(data.pendingModeration);
      } catch {
        if (!cancelled) {
          setStatsError(true);
        }
      } finally {
        if (!cancelled) {
          setStatsLoading(false);
        }
      }
    }

    async function fetchActivity() {
      try {
        setActivityLoading(true);
        setActivityError(false);
        const data = (await api.admin.getActivity(10)) as ActivityItem[];
        if (cancelled) return;
        setActivity(data);
      } catch {
        if (!cancelled) {
          setActivityError(true);
        }
      } finally {
        if (!cancelled) {
          setActivityLoading(false);
        }
      }
    }

    fetchStats();
    fetchActivity();

    return () => {
      cancelled = true;
    };
  }, []);

  return (
    <div className="space-y-6">
      {/* Stats Grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {statsLoading ? (
          [...Array(8)].map((_, i) => <StatCardSkeleton key={i} />)
        ) : statsError ? (
          <div
            className="col-span-full p-6 rounded-xl text-center"
            style={{
              background: 'var(--bg-card)',
              border: '1px solid var(--border-dark)',
              color: 'var(--text-muted)',
            }}
          >
            Données indisponibles
          </div>
        ) : (
          statsCards.map((stat) => (
            <div
              key={stat.label}
              className="p-4 rounded-xl transition-all hover:translate-y-[-2px]"
              style={{
                background: 'var(--bg-card)',
                border: '1px solid var(--border-dark)',
              }}
            >
              <div className="flex items-start justify-between mb-2">
                <div
                  className="w-10 h-10 rounded-lg flex items-center justify-center"
                  style={{ background: `${stat.color}15`, color: stat.color }}
                >
                  {stat.icon}
                </div>
                {stat.trend && (
                  <div
                    className="flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold"
                    style={{
                      background: stat.trendUp ? 'rgba(34,197,94,0.1)' : 'rgba(239,68,68,0.1)',
                      color: stat.trendUp ? '#22c55e' : '#ef4444',
                    }}
                  >
                    {stat.trendUp ? <IconTrendingUp size={10} /> : <IconTrendingDown size={10} />}
                    {stat.trend}
                  </div>
                )}
              </div>
              <div className="text-xl font-bold font-mono" style={{ color: 'var(--text-primary)' }}>
                {stat.value}
              </div>
              <div className="text-[11px]" style={{ color: 'var(--text-muted)' }}>
                {stat.label}
              </div>
              <MiniChart data={stat.chartData} color={stat.color} />
            </div>
          ))
        )}
      </div>

      {/* Bottom section: Recent Activity + Quick Stats */}
      <div className="grid grid-cols-1 lg:grid-cols-[1fr_340px] gap-5">
        {/* Recent Activity */}
        <div
          className="rounded-xl p-5"
          style={{ background: 'var(--bg-card)', border: '1px solid var(--border-dark)' }}
        >
          <h3 className="font-impact text-sm mb-4" style={{ color: 'var(--color-gold)' }}>
            Activité Récente
          </h3>
          {activityLoading ? (
            <ActivitySkeleton />
          ) : activityError ? (
            <div className="p-4 text-center text-xs" style={{ color: 'var(--text-muted)' }}>
              Données indisponibles
            </div>
          ) : activity.length === 0 ? (
            <div className="p-4 text-center text-xs" style={{ color: 'var(--text-muted)' }}>
              Aucune activité récente
            </div>
          ) : (
            <div className="space-y-2">
              {activity.map((item) => (
                <div
                  key={item.id}
                  className="flex items-start gap-3 p-3 rounded-lg"
                  style={{ background: 'rgba(255,255,255,0.02)' }}
                >
                  <span
                    className="w-2 h-2 rounded-full mt-1.5 flex-shrink-0"
                    style={{ background: activityColors[item.type] || 'var(--text-muted)' }}
                  />
                  <div className="flex-1 min-w-0">
                    <p className="text-xs" style={{ color: 'var(--text-secondary)' }}>{item.text}</p>
                    <span className="text-[10px]" style={{ color: 'var(--text-muted)' }}>{item.time}</span>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Quick Server Stats */}
        <div className="space-y-4">
          <div
            className="rounded-xl p-5"
            style={{ background: 'var(--bg-card)', border: '1px solid var(--border-dark)' }}
          >
            <h3 className="font-impact text-sm mb-4" style={{ color: 'var(--color-gold)' }}>
              Serveur
            </h3>
            <div className="space-y-3">
              {[
                { label: 'CPU', value: 23, color: '#22c55e' },
                { label: 'RAM', value: 58, color: '#f59e0b' },
                { label: 'Disque', value: 34, color: '#60a5fa' },
                { label: 'Bande passante', value: 12, color: '#a78bfa' },
              ].map((metric) => (
                <div key={metric.label}>
                  <div className="flex justify-between items-center mb-1">
                    <span className="text-xs" style={{ color: 'var(--text-muted)' }}>{metric.label}</span>
                    <span className="text-[10px] font-mono font-bold" style={{ color: metric.color }}>{metric.value}%</span>
                  </div>
                  <div className="h-1.5 rounded-full overflow-hidden" style={{ background: 'rgba(255,255,255,0.05)' }}>
                    <div
                      className="h-full rounded-full transition-all duration-700"
                      style={{ width: `${metric.value}%`, background: metric.color }}
                    />
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div
            className="rounded-xl p-5"
            style={{ background: 'var(--bg-card)', border: '1px solid var(--border-dark)' }}
          >
            <h3 className="font-impact text-sm mb-4" style={{ color: 'var(--color-gold)' }}>
              En attente
            </h3>
            <div className="space-y-2">
              {[
                { label: 'Discussions à modérer', value: pendingModeration ?? 5, color: 'var(--color-red-light)', fromApi: pendingModeration !== null },
                { label: 'Signalements ouverts', value: 3, color: '#ef4444', fromApi: false },
                { label: 'Annonces à vérifier', value: 8, color: '#f59e0b', fromApi: false },
                { label: 'Commentaires en attente', value: 12, color: '#60a5fa', fromApi: false },
              ].map((item) => (
                <div key={item.label} className="flex justify-between items-center py-1.5" style={{ borderBottom: '1px solid var(--border-dark)' }}>
                  <span className="text-xs" style={{ color: 'var(--text-secondary)' }}>{item.label}</span>
                  <span
                    className="px-2 py-0.5 rounded-full text-[10px] font-bold"
                    style={{ background: `${item.color}15`, color: item.color }}
                  >
                    {item.value}
                  </span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
