import React, { useState, useEffect } from 'react';
import Head from 'next/head';
import { useRouter } from 'next/router';
import { useSession } from 'next-auth/react';
import AdminLayout from '../../components/AdminLayout';

interface DailyData {
  date: string;
  count: number;
}

interface RevenueData {
  date: string;
  revenue: number;
}

interface SubscriptionBreakdown {
  plan: string;
  count: number;
}

interface Stats {
  totalUsers: number;
  activeUsers: number;
  disabledUsers: number;
  suspendedUsers: number;
  totalQueries: number;
  totalConversations: number;
  totalMessages: number;
  activeToday: number;
  newThisWeek: number;
  dailyRegistrations: DailyData[];
  dailyMessages: DailyData[];
  dailyConversations: DailyData[];
  // New financial and usage stats
  subscriptionBreakdown: SubscriptionBreakdown[];
  totalRevenue: number;
  monthlyRevenue: number;
  failedPayments: number;
  dailyRevenue: RevenueData[];
  todayMessages: number;
  todayFileUploads: number;
}

export default function AdminDashboard() {
  const { data: session, status } = useSession();
  const router = useRouter();
  const [stats, setStats] = useState<Stats | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [darkMode, setDarkMode] = useState(false);

  // Load theme preference from localStorage (synced with main chat)
  useEffect(() => {
    try {
      const savedTheme = localStorage.getItem('theme');
      if (savedTheme === 'dark') setDarkMode(true);
    } catch {}
  }, []);

  useEffect(() => {
    if (status === 'unauthenticated') {
      router.push('/auth/signin');
    }
  }, [status, router]);

  useEffect(() => {
    if (status === 'authenticated') {
      loadData();
    }
  }, [status]);

  async function loadData() {
    setLoading(true);
    setError(null);
    try {
      const statsRes = await fetch('/api/admin/stats');

      if (statsRes.status === 403) {
        setError('Admin access required');
        setLoading(false);
        return;
      }

      if (!statsRes.ok) {
        throw new Error('Failed to load data');
      }

      const statsData = await statsRes.json();
      setStats(statsData.stats || null);
    } catch (err) {
      setError('Failed to load admin data');
      console.error(err);
    } finally {
      setLoading(false);
    }
  }

  const formatDate = (dateStr: string | null) => {
    if (!dateStr) return 'Never';
    return new Date(dateStr).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  // Theme-aware styles
  const theme = darkMode ? {
    bg: '#1a1a2e',
    cardBg: '#252542',
    border: '#3d3d5c',
    text: '#e5e5e5',
    textSecondary: '#9ca3af',
    textMuted: '#6b7280',
    tableBg: '#1a1a2e',
    shadow: '0 4px 12px rgba(0,0,0,0.3)'
  } : {
    bg: 'linear-gradient(180deg, #f8fafc, #f1f5f9)',
    cardBg: '#fff',
    border: '#e5e7eb',
    text: '#0f172a',
    textSecondary: '#374151',
    textMuted: '#6b7280',
    tableBg: '#f9fafb',
    shadow: '0 4px 12px rgba(0,0,0,0.05)'
  };

  const S: Record<string, React.CSSProperties> = {
    page: {
      minHeight: '100vh',
      background: theme.bg,
      fontFamily: 'Inter, Helvetica, Arial, sans-serif',
      color: theme.text,
      padding: '24px'
    },
    header: {
      display: 'flex',
      justifyContent: 'space-between',
      alignItems: 'center',
      marginBottom: '32px',
      flexWrap: 'wrap' as const,
      gap: '12px'
    },
    title: {
      fontSize: '28px',
      fontWeight: 700,
      color: theme.text,
      margin: 0
    },
    headerButtons: {
      display: 'flex',
      gap: '12px',
      alignItems: 'center'
    },
    backBtn: {
      padding: '10px 20px',
      borderRadius: '10px',
      border: `1px solid ${theme.border}`,
      background: theme.cardBg,
      color: theme.textSecondary,
      cursor: 'pointer',
      fontSize: '14px',
      boxShadow: theme.shadow
    },
    themeBtn: {
      padding: '10px 16px',
      borderRadius: '10px',
      border: `1px solid ${theme.border}`,
      background: theme.cardBg,
      color: theme.text,
      cursor: 'pointer',
      fontSize: '14px',
      display: 'flex',
      alignItems: 'center',
      gap: '6px'
    },
    statsGrid: {
      display: 'grid',
      gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))',
      gap: '16px',
      marginBottom: '32px'
    },
    statCard: {
      background: theme.cardBg,
      border: `1px solid ${theme.border}`,
      borderRadius: '16px',
      padding: '20px',
      textAlign: 'center' as const,
      boxShadow: theme.shadow
    },
    statValue: {
      fontSize: '32px',
      fontWeight: 700,
      color: '#2563eb',
      marginBottom: '4px'
    },
    statLabel: {
      fontSize: '14px',
      color: theme.textMuted
    },
    chartSection: {
      display: 'grid',
      gridTemplateColumns: 'repeat(auto-fit, minmax(350px, 1fr))',
      gap: '24px',
      marginBottom: '32px'
    },
    chartCard: {
      background: theme.cardBg,
      border: `1px solid ${theme.border}`,
      borderRadius: '16px',
      padding: '24px',
      boxShadow: theme.shadow
    },
    chartTitle: {
      fontSize: '16px',
      fontWeight: 600,
      color: theme.textSecondary,
      marginBottom: '16px'
    },
    controls: {
      display: 'flex',
      gap: '16px',
      marginBottom: '24px',
      flexWrap: 'wrap' as const
    },
    searchInput: {
      flex: 1,
      minWidth: '200px',
      padding: '12px 16px',
      borderRadius: '10px',
      border: `1px solid ${theme.border}`,
      background: theme.cardBg,
      color: theme.text,
      fontSize: '14px',
      outline: 'none'
    },
    select: {
      padding: '12px 16px',
      borderRadius: '10px',
      border: `1px solid ${theme.border}`,
      background: theme.cardBg,
      color: theme.textSecondary,
      fontSize: '14px',
      cursor: 'pointer',
      outline: 'none'
    },
    tableContainer: {
      background: theme.cardBg,
      borderRadius: '16px',
      border: `1px solid ${theme.border}`,
      overflow: 'hidden',
      boxShadow: theme.shadow
    },
    table: {
      width: '100%',
      borderCollapse: 'collapse' as const
    },
    th: {
      padding: '16px',
      textAlign: 'left' as const,
      background: theme.tableBg,
      color: theme.textMuted,
      fontSize: '12px',
      fontWeight: 600,
      textTransform: 'uppercase' as const,
      letterSpacing: '0.5px',
      borderBottom: `1px solid ${theme.border}`
    },
    td: {
      padding: '16px',
      borderBottom: `1px solid ${darkMode ? '#2d2d44' : '#f3f4f6'}`,
      fontSize: '14px',
      color: theme.textSecondary
    },
    userInfo: {
      display: 'flex',
      alignItems: 'center',
      gap: '12px'
    },
    avatar: {
      width: '36px',
      height: '36px',
      borderRadius: '50%',
      background: 'linear-gradient(135deg, #2563eb, #7c3aed)',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      color: '#fff',
      fontWeight: 600,
      fontSize: '14px'
    },
    statusBadge: {
      padding: '4px 12px',
      borderRadius: '20px',
      fontSize: '12px',
      fontWeight: 500
    },
    actionBtn: {
      padding: '6px 12px',
      borderRadius: '6px',
      border: 'none',
      cursor: 'pointer',
      fontSize: '12px',
      marginRight: '8px'
    },
    loading: {
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      height: '400px',
      fontSize: '18px',
      color: theme.textMuted
    },
    error: {
      background: darkMode ? '#3d1f1f' : '#fef2f2',
      border: `1px solid ${darkMode ? '#ef4444' : '#fecaca'}`,
      borderRadius: '12px',
      padding: '20px',
      textAlign: 'center' as const,
      color: '#dc2626'
    }
  };

  const getStatusStyle = (status: string): React.CSSProperties => {
    switch (status) {
      case 'active':
        return { ...S.statusBadge, background: darkMode ? '#1f3d2a' : '#dcfce7', color: '#16a34a' };
      case 'disabled':
        return { ...S.statusBadge, background: darkMode ? '#3d3d1f' : '#fef9c3', color: '#ca8a04' };
      case 'suspended':
        return { ...S.statusBadge, background: darkMode ? '#3d1f1f' : '#fee2e2', color: '#dc2626' };
      default:
        return S.statusBadge;
    }
  };

  // Simple bar chart component
  const BarChart = ({ data, color, label }: { data: DailyData[], color: string, label: string }) => {
    const maxCount = Math.max(...data.map(d => d.count), 1);
    const last7Days = [];
    for (let i = 6; i >= 0; i--) {
      const date = new Date();
      date.setDate(date.getDate() - i);
      const dateStr = date.toISOString().split('T')[0];
      const found = data.find(d => d.date?.split('T')[0] === dateStr);
      last7Days.push({
        date: dateStr,
        count: found?.count || 0,
        dayName: date.toLocaleDateString('en-US', { weekday: 'short' })
      });
    }

    return (
      <div style={S.chartCard}>
        <div style={S.chartTitle}>{label}</div>
        <div style={{ display: 'flex', alignItems: 'flex-end', gap: '8px', height: '120px' }}>
          {last7Days.map((d, i) => (
            <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '4px' }}>
              <div style={{ fontSize: '11px', color: '#6b7280', fontWeight: 500 }}>{d.count}</div>
              <div
                style={{
                  width: '100%',
                  height: `${Math.max((d.count / maxCount) * 80, 4)}px`,
                  background: `linear-gradient(180deg, ${color}, ${color}99)`,
                  borderRadius: '4px 4px 0 0',
                  transition: 'height 0.3s ease'
                }}
              />
              <div style={{ fontSize: '10px', color: '#9ca3af' }}>{d.dayName}</div>
            </div>
          ))}
        </div>
      </div>
    );
  };

  if (status === 'loading' || loading) {
    return (
      <>
        <Head><title>Admin Dashboard - Gregory AI</title></Head>
        <style>{`
          body { margin: 0; padding: 0; background: ${darkMode ? '#1a1a2e' : 'linear-gradient(180deg, #f8fafc, #f1f5f9)'}; }
          html { background: ${darkMode ? '#1a1a2e' : 'linear-gradient(180deg, #f8fafc, #f1f5f9)'}; }
        `}</style>
        <div style={S.page}>
          <div style={S.loading}>Loading...</div>
        </div>
      </>
    );
  }

  if (error) {
    return (
      <AdminLayout darkMode={darkMode} setDarkMode={setDarkMode} currentPage="dashboard">
        <Head><title>Admin Dashboard - Gregory AI</title></Head>
        <div style={S.error}>
          <p style={{ fontSize: '18px', marginBottom: '8px' }}>{error}</p>
          <p style={{ fontSize: '14px', color: '#6b7280' }}>
            You need admin privileges to access this page.
          </p>
        </div>
      </AdminLayout>
    );
  }

  return (
    <AdminLayout darkMode={darkMode} setDarkMode={setDarkMode} currentPage="dashboard">
      <Head>
        <title>Admin Dashboard - Gregory AI</title>
      </Head>
      <div>
        {/* Stats Grid */}
        {stats && (
          <div style={S.statsGrid}>
            <div style={S.statCard}>
              <div style={S.statValue}>{stats.totalUsers}</div>
              <div style={S.statLabel}>Total Users</div>
            </div>
            <div style={S.statCard}>
              <div style={{ ...S.statValue, color: '#16a34a' }}>{stats.activeUsers}</div>
              <div style={S.statLabel}>Active Users</div>
            </div>
            <div style={S.statCard}>
              <div style={{ ...S.statValue, color: '#ca8a04' }}>{stats.disabledUsers}</div>
              <div style={S.statLabel}>Disabled</div>
            </div>
            <div style={S.statCard}>
              <div style={S.statValue}>{stats.totalConversations}</div>
              <div style={S.statLabel}>Conversations</div>
            </div>
            <div style={S.statCard}>
              <div style={S.statValue}>{stats.totalMessages}</div>
              <div style={S.statLabel}>Messages</div>
            </div>
            <div style={S.statCard}>
              <div style={{ ...S.statValue, color: '#16a34a' }}>{stats.newThisWeek}</div>
              <div style={S.statLabel}>New This Week</div>
            </div>
          </div>
        )}

        {/* Financial Stats */}
        {stats && (
          <div style={{ marginBottom: 32 }}>
            <h2 style={{ fontSize: 18, fontWeight: 600, color: theme.text, marginBottom: 16 }}>💰 Financial Overview</h2>
            <div style={S.statsGrid}>
              <div style={S.statCard}>
                <div style={{ ...S.statValue, color: '#10b981' }}>${((stats.totalRevenue || 0) / 100).toFixed(2)}</div>
                <div style={S.statLabel}>Total Revenue</div>
              </div>
              <div style={S.statCard}>
                <div style={{ ...S.statValue, color: '#3b82f6' }}>${((stats.monthlyRevenue || 0) / 100).toFixed(2)}</div>
                <div style={S.statLabel}>This Month</div>
              </div>
              <div style={S.statCard}>
                <div style={{ ...S.statValue, color: '#dc2626' }}>{stats.failedPayments || 0}</div>
                <div style={S.statLabel}>Failed Payments</div>
              </div>
              <div style={S.statCard}>
                <div style={S.statValue}>{stats.todayMessages || 0}</div>
                <div style={S.statLabel}>Messages Today</div>
              </div>
              <div style={S.statCard}>
                <div style={S.statValue}>{stats.todayFileUploads || 0}</div>
                <div style={S.statLabel}>Uploads Today</div>
              </div>
            </div>
          </div>
        )}

        {/* Subscription Breakdown */}
        {stats && stats.subscriptionBreakdown && stats.subscriptionBreakdown.length > 0 && (
          <div style={{ marginBottom: 32 }}>
            <h2 style={{ fontSize: 18, fontWeight: 600, color: theme.text, marginBottom: 16 }}>📊 Subscription Breakdown</h2>
            <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' as const }}>
              {stats.subscriptionBreakdown.map((item) => (
                <div key={item.plan} style={{
                  ...S.statCard,
                  minWidth: 120,
                  flex: '0 0 auto'
                }}>
                  <div style={{ ...S.statValue, fontSize: 24 }}>{item.count}</div>
                  <div style={S.statLabel}>{item.plan.charAt(0).toUpperCase() + item.plan.slice(1)}</div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Charts Section */}
        {stats && (
          <div style={S.chartSection}>
            <BarChart 
              data={stats.dailyRegistrations || []} 
              color="#2563eb" 
              label="📊 New Users (Last 7 Days)" 
            />
            <BarChart 
              data={stats.dailyMessages || []} 
              color="#16a34a" 
              label="💬 Messages (Last 7 Days)" 
            />
            <BarChart 
              data={stats.dailyConversations || []} 
              color="#7c3aed" 
              label="🗨️ Conversations (Last 7 Days)" 
            />
          </div>
        )}

        {/* Quick Actions */}
        <div style={{ marginTop: 32 }}>
          <h2 style={{ fontSize: 18, fontWeight: 600, color: theme.text, marginBottom: 16 }}>🚀 Quick Actions</h2>
          <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' as const }}>
            <button
              onClick={() => router.push('/admin/users')}
              style={{
                padding: '12px 24px',
                borderRadius: 8,
                border: `1px solid ${theme.border}`,
                background: theme.cardBg,
                color: theme.text,
                cursor: 'pointer',
                fontSize: 14,
                fontWeight: 500,
              }}
            >
              👥 Manage Users
            </button>
            <button
              onClick={() => router.push('/admin/packages')}
              style={{
                padding: '12px 24px',
                borderRadius: 8,
                border: `1px solid ${theme.border}`,
                background: theme.cardBg,
                color: theme.text,
                cursor: 'pointer',
                fontSize: 14,
                fontWeight: 500,
              }}
            >
              📦 Manage Packages
            </button>
            <button
              onClick={() => router.push('/admin/payments')}
              style={{
                padding: '12px 24px',
                borderRadius: 8,
                border: `1px solid ${theme.border}`,
                background: theme.cardBg,
                color: theme.text,
                cursor: 'pointer',
                fontSize: 14,
                fontWeight: 500,
              }}
            >
              💳 View Payments
            </button>
            <button
              onClick={loadData}
              style={{
                padding: '12px 24px',
                borderRadius: 8,
                border: 'none',
                background: 'linear-gradient(90deg, #2563eb, #7c3aed)',
                color: '#fff',
                cursor: 'pointer',
                fontSize: 14,
                fontWeight: 500,
              }}
            >
              🔄 Refresh Stats
            </button>
          </div>
        </div>
      </div>
    </AdminLayout>
  );
}
