'use client';

import { useEffect, useState, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { adminService } from '@/services/admin.service';
import { verificationSettingsService } from '@/services/verification-settings.service';
import { emailConfigService } from '@/services/email-config.service';
import type { VerificationSettings } from '@/services/verification-settings.service';
import type { EmailConfig } from '@/services/email-config.service';
import type { DashboardStats } from '@/types/admin.types';
import { safeArray } from '@/lib/safe-array';
import { cn } from '@/lib/utils';
import { usePriorityData } from '@/hooks/usePriorityData';
import { PageSkeleton, CardSkeleton, TableSkeleton, ChartSkeleton } from '@/components/priority/skeletons';
import { SortableTable } from '@/components/tables/SortableTable';
import EmptyState from '@/components/EmptyState';
import { Badge } from '@/components/ui/badge';
import {
  Users, UserCheck, Activity, TrendingUp, ArrowUpRight, ArrowDownRight,
  Wallet, ShoppingCart, Ticket, Server, Database, Wifi, Globe,
  RefreshCw, Clock, DollarSign, CreditCard, ArrowLeftRight,
  Ban, Snowflake, Lock, Gavel, FileCheck, UserPlus, ShieldCheck, Mail,
  ToggleLeft, ToggleRight,
} from 'lucide-react';

export default function SuperAdminDashboardPage() {
  const router = useRouter();
  const [lastUpdated, setLastUpdated] = useState<Date | null>(null);
  const [verificationSettings, setVerificationSettings] = useState<VerificationSettings | null>(null);
  const [emailConfig, setEmailConfig] = useState<EmailConfig | null>(null);
  const [togglingVerification, setTogglingVerification] = useState(false);
  const [togglingEmail, setTogglingEmail] = useState(false);
  const [quickActionError, setQuickActionError] = useState<string | null>(null);

  const loadQuickSettings = useCallback(async () => {
    setQuickActionError(null);
    try {
      const [vs, ec] = await Promise.all([
        verificationSettingsService.getSettings().catch(() => null),
        emailConfigService.getActive().catch(() => null),
      ]);
      setVerificationSettings(vs);
      setEmailConfig(ec);
    } catch (err: any) {
      setQuickActionError(err?.message || 'Failed to load settings');
    }
  }, []);

  const toggleVerification = async () => {
    if (!verificationSettings) return;
    setTogglingVerification(true);
    try {
      const updated = await verificationSettingsService.toggleSettings(!verificationSettings.isEnabled);
      setVerificationSettings(updated);
    } catch (err: any) {
      setQuickActionError(err?.message || 'Failed to toggle verification');
    } finally {
      setTogglingVerification(false);
    }
  };

  const toggleEmailConfig = async () => {
    if (!emailConfig) return;
    setTogglingEmail(true);
    try {
      const updated = await emailConfigService.toggleActive(emailConfig.id, !emailConfig.isActive);
      setEmailConfig(updated);
    } catch (err: any) {
      setQuickActionError(err?.message || 'Failed to toggle payment wallet');
    } finally {
      setTogglingEmail(false);
    }
  };

  const { data: stats, loading, error, refetch } = usePriorityData<DashboardStats>({
    key: 'dashboard:stats',
    fetcher: () => adminService.getDashboard(),
    priority: 'high',
    ttl: 10_000,
    refetchInterval: 30_000,
  });

  useEffect(() => {
    if (stats) setLastUpdated(new Date());
  }, [stats]);

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

  const navigateTo = useCallback((href: string) => {
    router.push(href);
  }, [router]);

  if (error && !stats) {
    return (
      <div className="space-y-6">
        <div>
          <h1 className="text-2xl font-bold text-white">System Overview</h1>
          <p className="mt-1 text-sm text-slate-400">Real-time platform metrics and system health</p>
        </div>
        <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-400">
          {error.message}
          <button onClick={() => refetch()} className="ml-4 underline">Retry</button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-start justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-white">System Overview</h1>
          <p className="mt-1 text-sm text-slate-400">
            Real-time platform metrics and system health
            {lastUpdated && <span className="ml-2 text-xs">Updated: {lastUpdated.toLocaleTimeString()}</span>}
          </p>
        </div>
        <button
          onClick={() => refetch()}
          disabled={loading}
          className="flex items-center gap-2 rounded-lg border border-white/10 px-3 py-2 text-sm text-slate-400 hover:bg-white/5 disabled:opacity-50"
        >
          <RefreshCw className={`h-4 w-4 ${loading ? 'animate-spin' : ''}`} /> Refresh
        </button>
  </div>

       {quickActionError && (
        <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-400">
          {quickActionError}
        </div>
      )}

      <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
        <QuickToggleCard
          title="Registration Verification"
          description={
            verificationSettings?.isEnabled
              ? 'Verification is enabled. New signups must verify their email.'
              : 'Verification is disabled. Users can register without verification.'
          }
          isEnabled={verificationSettings?.isEnabled ?? true}
          isLoading={togglingVerification}
          icon={<ShieldCheck className="h-5 w-5 text-blue-400" />}
          onToggle={toggleVerification}
          onNavigate={() => navigateTo('/super-admin/verification-settings')}
        />
        <QuickToggleCard
          title="Payment Wallet / Gmail"
          description={
            emailConfig?.isActive
              ? `${emailConfig?.email} is active. Users can submit payment verification.`
              : emailConfig
                ? `${emailConfig?.email} is inactive.`
                : 'No payment wallet configured. Configure Gmail for payment verifications.'
          }
          isEnabled={emailConfig?.isActive ?? false}
          isLoading={togglingEmail}
          icon={<Mail className="h-5 w-5 text-emerald-400" />}
          onToggle={toggleEmailConfig}
          onNavigate={() => navigateTo('/super-admin/email-config')}
          disabled={!emailConfig}
        />
      </div>

      {error && (
        <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-400">
          {error.message}
        </div>
      )}

      {loading && !stats && (
        <>
          <div className="grid grid-cols-2 gap-4 md:grid-cols-4 xl:grid-cols-6">
            {Array.from({ length: 6 }).map((_, i) => <CardSkeleton key={i} />)}
          </div>
          <div className="grid grid-cols-2 gap-4 md:grid-cols-4 xl:grid-cols-6">
            {Array.from({ length: 6 }).map((_, i) => <CardSkeleton key={i} />)}
          </div>
          <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
            {Array.from({ length: 4 }).map((_, i) => <CardSkeleton key={i} />)}
          </div>
          <div className="grid grid-cols-2 gap-4 md:grid-cols-3 xl:grid-cols-6">
            {Array.from({ length: 6 }).map((_, i) => <CardSkeleton key={i} />)}
          </div>
          <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
            {Array.from({ length: 4 }).map((_, i) => <CardSkeleton key={i} />)}
          </div>
          <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
            <CardSkeleton />
            <CardSkeleton />
          </div>
          <TableSkeleton rows={8} />
        </>
      )}

      {stats && (
        <>
          <div className="grid grid-cols-2 gap-4 md:grid-cols-4 xl:grid-cols-6">
            <StatCard title="Total Users" value={fmt(stats.totalUsers)} icon={<Users className="h-5 w-5" />} color="text-blue-400" href="/super-admin/users" onNavigate={navigateTo} />
            <StatCard title="Verified Users" value={fmt(stats.verifiedUsers)} icon={<UserCheck className="h-5 w-5" />} color="text-emerald-400" />
            <StatCard title="Online Now" value={fmt(stats.onlineUsers)} icon={<Activity className="h-5 w-5" />} color="text-cyan-400" />
            <StatCard title="New Today" value={fmt(stats.newUsersToday)} icon={<ArrowUpRight className="h-5 w-5" />} color="text-violet-400" />
            <StatCard title="New 24h" value={fmt(stats.newUsers24h)} icon={<Clock className="h-5 w-5" />} color="text-amber-400" />
            <StatCard title="New 7d" value={fmt(stats.newUsers7d)} icon={<TrendingUp className="h-5 w-5" />} color="text-pink-400" />
          </div>

          <div className="grid grid-cols-2 gap-4 md:grid-cols-4 xl:grid-cols-6">
            <StatCard title="Total Orders" value={fmt(stats.totalOrders)} icon={<ShoppingCart className="h-5 w-5" />} color="text-indigo-400" />
            <StatCard title="Active Orders" value={fmt(stats.activeOrders)} icon={<Activity className="h-5 w-5" />} color="text-orange-400" />
            <StatCard title="Total Txns" value={fmt(stats.totalTransactions)} icon={<ArrowLeftRight className="h-5 w-5" />} color="text-teal-400" />
            <StatCard title="Deposits" value={fmt(stats.totalDeposits)} icon={<ArrowDownRight className="h-5 w-5" />} color="text-emerald-400" />
            <StatCard title="Withdrawals" value={fmt(stats.totalWithdrawals)} icon={<ArrowUpRight className="h-5 w-5" />} color="text-red-400" />
            <StatCard title="Today Trades" value={fmt(stats.todayTrades)} icon={<TrendingUp className="h-5 w-5" />} color="text-lime-400" />
          </div>

          <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
            <StatCard title="Vol (1h)" value={fmt(stats.tradingVolumeLastHour)} icon={<DollarSign className="h-5 w-5" />} color="text-green-400" />
            <StatCard title="Vol (24h)" value={fmt(stats.tradingVolume24h)} icon={<DollarSign className="h-5 w-5" />} color="text-blue-400" />
            <StatCard title="Vol (7d)" value={fmt(stats.tradingVolume7d)} icon={<DollarSign className="h-5 w-5" />} color="text-purple-400" />
            <StatCard title="Vol (30d)" value={fmt(stats.tradingVolume30d)} icon={<DollarSign className="h-5 w-5" />} color="text-amber-400" />
          </div>

          <div className="grid grid-cols-2 gap-4 md:grid-cols-3 xl:grid-cols-6">
            <StatCard title="Wallet Vol" value={fmt(stats.walletVolume)} icon={<Wallet className="h-5 w-5" />} color="text-cyan-400" />
            <StatCard title="Revenue" value={fmt(stats.revenue)} icon={<DollarSign className="h-5 w-5" />} color="text-emerald-400" />
            <StatCard title="Commission" value={fmt(stats.commission)} icon={<CreditCard className="h-5 w-5" />} color="text-violet-400" />
            <StatCard title="Pending Dep" value={fmt(stats.pendingDeposits)} icon={<ArrowDownRight className="h-5 w-5" />} color="text-amber-400" />
            <StatCard title="Pending Wd" value={fmt(stats.pendingWithdrawals)} icon={<ArrowUpRight className="h-5 w-5" />} color="text-red-400" />
            <StatCard title="Open Tickets" value={fmt(stats.supportTickets?.open ?? 0)} icon={<Ticket className="h-5 w-5" />} color="text-pink-400" />
          </div>

          <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
            <StatCard title="In Progress" value={fmt(stats.supportTickets?.inProgress ?? 0)} icon={<Ticket className="h-5 w-5" />} color="text-amber-400" />
            <StatCard title="Resolved" value={fmt(stats.supportTickets?.resolved ?? 0)} icon={<Ticket className="h-5 w-5" />} color="text-emerald-400" />
            <StatCard title="Closed" value={fmt(stats.supportTickets?.closed ?? 0)} icon={<Ticket className="h-5 w-5" />} color="text-slate-400" />
            <StatCard title="Today Orders" value={fmt(stats.todayOrders)} icon={<ShoppingCart className="h-5 w-5" />} color="text-indigo-400" />
          </div>

          <div className="grid grid-cols-2 gap-4 md:grid-cols-3 xl:grid-cols-6">
            <StatCard title="Total Referrals" value={fmt(stats.totalReferrals ?? 0)} icon={<UserPlus className="h-5 w-5" />} color="text-pink-400" href="/super-admin/trading-rules?tab=referral" onNavigate={navigateTo} />
            <StatCard title="Pending Fines" value={fmt(stats.pendingFinesCount ?? 0)} icon={<Gavel className="h-5 w-5" />} color="text-red-400" href="/super-admin/fines" onNavigate={navigateTo} />
            <StatCard title="Pending Subs" value={fmt(stats.pendingSubscriptionsCount ?? 0)} icon={<CreditCard className="h-5 w-5" />} color="text-violet-400" href="/super-admin/subscriptions" onNavigate={navigateTo} />
            <StatCard title="Pending Verifs" value={fmt(stats.pendingVerificationsCount ?? 0)} icon={<FileCheck className="h-5 w-5" />} color="text-amber-400" href="/super-admin/verifications" onNavigate={navigateTo} />
            <StatCard title="Banned Users" value={fmt(stats.bannedUsersCount ?? 0)} icon={<Ban className="h-5 w-5" />} color="text-red-400" href="/super-admin/users?filter=banned" onNavigate={navigateTo} />
            <StatCard title="Frozen Wallets" value={fmt(stats.frozenWalletsCount ?? 0)} icon={<Snowflake className="h-5 w-5" />} color="text-cyan-400" href="/super-admin/wallet-management" onNavigate={navigateTo} />
          </div>

          <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
            <StatCard title="Active Restrictions" value={fmt(stats.activeRestrictionsCount ?? 0)} icon={<Lock className="h-5 w-5" />} color="text-orange-400" href="/super-admin/security" onNavigate={navigateTo} />
            <StatCard title="Pending Fine Amt" value={fmt(stats.pendingFinesAmount ?? '0')} icon={<DollarSign className="h-5 w-5" />} color="text-amber-400" href="/super-admin/fines" onNavigate={navigateTo} />
          </div>

          <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
            <div className={`rounded-xl border p-5 ${healthBg(stats.serverStatus)}`}>
              <h3 className="text-sm font-semibold text-slate-200">System Health</h3>
              <div className="mt-3 grid grid-cols-2 gap-3">
                <HealthItem label="API" status={stats.apiStatus} icon={<Globe className="h-4 w-4" />} />
                <HealthItem label="Database" status={stats.databaseStatus} icon={<Database className="h-4 w-4" />} />
                <HealthItem label="Redis" status={stats.redis} icon={<Wifi className="h-4 w-4" />} />
                <HealthItem label="WebSocket" status={stats.websocket} icon={<Activity className="h-4 w-4" />} />
              </div>
            </div>
            <div className="rounded-xl border border-white/10 bg-white/5 p-5">
              <h3 className="text-sm font-semibold text-slate-200">Server Status</h3>
              <div className="mt-3 flex items-center gap-2">
                <Server className="h-5 w-5 text-slate-400" />
                <span className={`text-lg font-bold ${healthColor(stats.serverStatus)}`}>{stats.serverStatus.toUpperCase()}</span>
              </div>
              <p className="mt-1 text-xs text-slate-500">Last checked: {lastUpdated?.toLocaleTimeString()}</p>
            </div>
          </div>

          <QuickActions onNavigate={navigateTo} />

          <UserStatusBreakdown stats={stats} />

          <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
            <SortableTable
              title="Recent Orders"
              data={safeArray(stats.recentOrders)}
              columns={[
                { key: 'userEmail', label: 'User', sortable: true },
                { key: 'status', label: 'Status', sortable: true },
                { key: 'side', label: 'Side', sortable: true, align: 'center' },
                { key: 'currency', label: 'Currency', sortable: true },
                { key: 'price', label: 'Price', sortable: true, align: 'right' },
              ]}
              onRowClick={(row) => console.log('Order clicked:', row)}
              emptyMessage="No recent orders"
              emptyDescription="Recent orders will appear here."
            />
            <SortableTable
              title="Recent Trades"
              data={safeArray(stats.recentTrades)}
              columns={[
                { key: 'buyerEmail', label: 'Buyer', sortable: true },
                { key: 'sellerEmail', label: 'Seller', sortable: true },
                { key: 'status', label: 'Status', sortable: true },
                { key: 'quantity', label: 'Qty', sortable: true, align: 'right' },
              ]}
              onRowClick={(row) => console.log('Trade clicked:', row)}
              emptyMessage="No recent trades"
              emptyDescription="Recent trades will appear here."
            />
            <SortableTable
              title="Recent Wallet Activity"
              data={safeArray(stats.recentWalletActivity)}
              columns={[
                { key: 'userEmail', label: 'User', sortable: true },
                { key: 'type', label: 'Type', sortable: true },
                { key: 'amount', label: 'Amount', sortable: true, align: 'right' },
              ]}
              onRowClick={(row) => console.log('Wallet activity clicked:', row)}
              emptyMessage="No recent activity"
              emptyDescription="Wallet activity will appear here."
            />
          </div>
        </>
      )}
    </div>
  );
}

function StatCard({ title, value, icon, color, href, onNavigate }: { title: string; value: string; icon: React.ReactNode; color: string; href?: string; onNavigate?: (href: string) => void }) {
  const handleClick = () => {
    if (href && onNavigate) {
      onNavigate(href);
    }
  };

  return (
    <div
      className={`rounded-xl border border-white/10 bg-white/[0.02] p-4 transition-all ${href ? 'cursor-pointer hover:border-white/20 hover:bg-white/[0.04]' : ''}`}
      onClick={handleClick}
      role={href ? 'button' : undefined}
      tabIndex={href ? 0 : undefined}
      onKeyDown={href ? (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); handleClick(); } } : undefined}
    >
      <div className="flex items-center justify-between">
        <div className="text-xs font-medium text-slate-400">{title}</div>
        <div className={`${color}`}>{icon}</div>
      </div>
      <div className="mt-2 text-xl font-bold text-white">{value}</div>
    </div>
  );
}

function QuickActions({ onNavigate }: { onNavigate: (href: string) => void }) {
  const actions = [
    { label: 'All Users', icon: Users, href: '/super-admin/users' },
    { label: 'Fines', icon: Gavel, href: '/super-admin/fines' },
    { label: 'Subscriptions', icon: CreditCard, href: '/super-admin/subscriptions' },
    { label: 'Verifications', icon: FileCheck, href: '/super-admin/verifications' },
    { label: 'Security', icon: Activity, href: '/super-admin/security' },
    { label: 'Referrals', icon: UserPlus, href: '/super-admin/trading-rules?tab=referral' },
  ];

  return (
    <div className="rounded-xl border border-white/10 bg-white/5 p-5">
      <h3 className="mb-3 text-sm font-semibold text-slate-200">Quick Actions</h3>
      <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-6">
        {actions.map((action) => (
          <button
            key={action.label}
            onClick={() => onNavigate(action.href)}
            className="flex flex-col items-center gap-2 rounded-lg border border-white/10 p-3 text-xs text-slate-300 hover:border-white/20 hover:bg-white/5 hover:text-white transition-all"
          >
            <action.icon className="h-5 w-5" />
            {action.label}
          </button>
        ))}
      </div>
    </div>
  );
}

function QuickToggleCard({ title, description, isEnabled, isLoading, icon, onToggle, onNavigate, disabled }: {
  title: string;
  description: string;
  isEnabled: boolean;
  isLoading: boolean;
  icon: React.ReactNode;
  onToggle: () => void;
  onNavigate: () => void;
  disabled?: boolean;
}) {
  return (
    <div className="rounded-xl border border-white/10 bg-slate-900/50 p-5 flex items-center justify-between gap-4">
      <div className="flex items-center gap-3">
        {icon}
        <div>
          <p className="text-sm font-medium text-white">{title}</p>
          <p className="text-xs text-slate-400">{description}</p>
        </div>
      </div>
      <div className="flex items-center gap-2">
        <button
          onClick={onNavigate}
          className="rounded-lg border border-white/10 px-3 py-1.5 text-xs text-slate-300 hover:bg-white/5"
        >
          Configure
        </button>
        <button
          onClick={onToggle}
          disabled={isLoading || disabled}
          className={cn(
            'relative inline-flex h-6 w-12 items-center rounded-full transition-colors',
            disabled ? 'bg-slate-700 cursor-not-allowed' : isEnabled ? 'bg-emerald-500 hover:bg-emerald-600' : 'bg-slate-600 hover:bg-slate-500',
            'disabled:opacity-50',
          )}
        >
          <span className="sr-only">Toggle</span>
          <span
            className={cn(
              'inline-block h-5 w-5 transform rounded-full bg-white shadow transition-transform',
              isEnabled ? 'translate-x-6' : 'translate-x-1',
            )}
          />
        </button>
      </div>
    </div>
  );
}

function UserStatusBreakdown({ stats }: { stats: DashboardStats }) {
  const items = [
    { label: 'Active', count: stats.userStatusBreakdown?.active ?? 0, color: 'bg-emerald-500', textColor: 'text-emerald-400' },
    { label: 'Banned', count: stats.userStatusBreakdown?.banned ?? 0, color: 'bg-red-500', textColor: 'text-red-400' },
    { label: 'Frozen', count: stats.userStatusBreakdown?.frozen ?? 0, color: 'bg-cyan-500', textColor: 'text-cyan-400' },
    { label: 'Pending Verification', count: stats.userStatusBreakdown?.pendingVerification ?? 0, color: 'bg-amber-500', textColor: 'text-amber-400' },
  ];

  const total = items.reduce((sum, item) => sum + item.count, 0);

  return (
    <div className="rounded-xl border border-white/10 bg-white/5 p-5">
      <h3 className="mb-4 text-sm font-semibold text-slate-200">User Status Breakdown</h3>
      <div className="space-y-3">
        {items.map((item) => (
          <div key={item.label} className="flex items-center gap-3">
            <div className="w-28 shrink-0 text-xs text-slate-400">{item.label}</div>
            <div className="flex-1 h-2.5 rounded-full bg-white/5 overflow-hidden">
              <div
                className={`h-full rounded-full ${item.color} transition-all duration-500`}
                style={{ width: total > 0 ? `${Math.max((item.count / total) * 100, 2)}%` : '0%' }}
              />
            </div>
            <div className={`w-14 text-right text-xs font-medium ${item.textColor}`}>
              {item.count.toLocaleString()}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function HealthItem({ label, status, icon }: { label: string; status: string; icon: React.ReactNode }) {
  const color = status === 'healthy' ? 'text-emerald-400' : status === 'degraded' ? 'text-amber-400' : 'text-red-400';
  return (
    <div className="flex items-center gap-2 rounded-lg border border-white/5 bg-white/5 p-2">
      <div className={color}>{icon}</div>
      <div>
        <div className="text-xs text-slate-400">{label}</div>
        <div className={`text-sm font-semibold ${color}`}>{(status || 'unknown').toUpperCase()}</div>
      </div>
    </div>
  );
}

function fmt(val: number | string, decimals = 2) {
  const n = typeof val === 'string' ? parseFloat(val) : val;
  if (isNaN(n)) return '0.00';
  return n.toLocaleString('en-US', { minimumFractionDigits: decimals, maximumFractionDigits: decimals });
}

function healthColor(status: string) {
  switch (status) {
    case 'healthy': return 'text-emerald-400';
    case 'degraded': return 'text-amber-400';
    case 'down': return 'text-red-400';
    default: return 'text-slate-400';
  }
}

function healthBg(status: string) {
  switch (status) {
    case 'healthy': return 'bg-emerald-500/10 border-emerald-500/20';
    case 'degraded': return 'bg-amber-500/10 border-amber-500/20';
    case 'down': return 'bg-red-500/10 border-red-500/20';
    default: return 'bg-white/5 border-white/10';
  }
}
