/**
 * Admin System Dashboard
 * Overview page with stats, alerts, revenue, active accounts, pending approvals
 */

import { useState, useEffect } from 'react';
import {
  Users,
  CheckCircle,
  DollarSign,
  Clock,
  AlertCircle,
  Activity,
  Loader2,
  ExternalLink,
  Globe,
  Database,
  Folder,
  Server,
  GitBranch,
  FileText,
} from 'lucide-react';
import { Card } from '../../components/ui/card';
import Badge from '../../components/ui/badge/Badge';
import { getAdminBillingStats } from '../../services/billing.api';

export default function AdminSystemDashboard() {
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState<any>(null);
  const [error, setError] = useState<string>('');

  const totalUsers = Number(stats?.total_users ?? 0);
  const activeUsers = Number(stats?.active_users ?? 0);
  const issuedCredits = Number(stats?.total_credits_issued ?? stats?.credits_issued_30d ?? 0);
  const usedCredits = Number(stats?.total_credits_used ?? stats?.credits_used_30d ?? 0);
  const creditScale = Math.max(issuedCredits, usedCredits, 1);
  const issuedPct = Math.min(100, Math.round((issuedCredits / creditScale) * 100));
  const usedPct = Math.min(100, Math.round((usedCredits / creditScale) * 100));

  const adminLinks = [
    { label: 'Marketing Site', url: 'https://igny8.com', icon: <Globe className="w-5 h-5 text-blue-600" />, note: 'Public marketing site' },
    { label: 'IGNY8 App', url: 'https://app.igny8.com', icon: <Globe className="w-5 h-5 text-green-600" />, note: 'Main SaaS UI' },
    { label: 'Django Admin', url: 'https://api.igny8.com/admin', icon: <Server className="w-5 h-5 text-indigo-600" />, note: 'Backend admin UI' },
    { label: 'PgAdmin', url: 'http://31.97.144.105:5050/', icon: <Database className="w-5 h-5 text-amber-600" />, note: 'Postgres console' },
    { label: 'File Manager', url: 'https://files.igny8.com', icon: <Folder className="w-5 h-5 text-teal-600" />, note: 'File manager UI' },
    { label: 'Portainer', url: 'http://31.97.144.105:9443', icon: <Server className="w-5 h-5 text-purple-600" />, note: 'Container management' },
    { label: 'API Docs (Swagger)', url: 'https://api.igny8.com/api/docs/', icon: <FileText className="w-5 h-5 text-orange-600" />, note: 'Swagger UI' },
    { label: 'API Docs (ReDoc)', url: 'https://api.igny8.com/api/redoc/', icon: <FileText className="w-5 h-5 text-rose-600" />, note: 'ReDoc docs' },
    { label: 'Gitea Repo', url: 'https://git.igny8.com/salman/igny8', icon: <GitBranch className="w-5 h-5 text-gray-700" />, note: 'Source control' },
  ];

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

  const loadStats = async () => {
    try {
      setLoading(true);
      const data = await getAdminBillingStats();
      setStats(data);
    } catch (err: any) {
      setError(err.message || 'Failed to load system stats');
      console.error('Admin stats load error:', err);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Loader2 className="w-8 h-8 animate-spin text-blue-600" />
      </div>
    );
  }

  return (
    <div className="p-6">
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900 dark:text-white">System Dashboard</h1>
        <p className="text-gray-600 dark:text-gray-400 mt-1">
          Overview of system health and billing activity
        </p>
      </div>

      {error && (
        <div className="mb-6 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg flex items-center gap-3">
          <AlertCircle className="w-5 h-5 text-red-600" />
          <p className="text-red-800 dark:text-red-200">{error}</p>
        </div>
      )}

      {/* Quick Stats */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-sm text-gray-600 dark:text-gray-400 mb-1">Total Users</div>
              <div className="text-3xl font-bold text-gray-900 dark:text-white">
                {totalUsers.toLocaleString()}
              </div>
            </div>
            <Users className="w-12 h-12 text-blue-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-sm text-gray-600 dark:text-gray-400 mb-1">Active Users</div>
              <div className="text-3xl font-bold text-gray-900 dark:text-white">
                {activeUsers.toLocaleString()}
              </div>
            </div>
            <CheckCircle className="w-12 h-12 text-green-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-sm text-gray-600 dark:text-gray-400 mb-1">Credits Issued</div>
              <div className="text-3xl font-bold text-gray-900 dark:text-white">
                {issuedCredits.toLocaleString()}
              </div>
              <div className="text-sm text-gray-500 mt-1">lifetime total</div>
            </div>
            <DollarSign className="w-12 h-12 text-green-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-sm text-gray-600 dark:text-gray-400 mb-1">Credits Used</div>
              <div className="text-3xl font-bold text-gray-900 dark:text-white">
                {usedCredits.toLocaleString()}
              </div>
              <div className="text-sm text-gray-500 mt-1">lifetime total</div>
            </div>
            <Clock className="w-12 h-12 text-yellow-600 opacity-50" />
          </div>
        </Card>
      </div>

      {/* System Health */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        <Card className="p-6">
          <h2 className="text-lg font-semibold mb-4 flex items-center gap-2">
            <Activity className="w-5 h-5" />
            System Health
          </h2>
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <span className="text-gray-700 dark:text-gray-300">API Status</span>
              <Badge variant="light" color="success">Operational</Badge>
            </div>
            <div className="flex items-center justify-between">
              <span className="text-gray-700 dark:text-gray-300">Database</span>
              <Badge variant="light" color="success">Healthy</Badge>
            </div>
            <div className="flex items-center justify-between">
              <span className="text-gray-700 dark:text-gray-300">Background Jobs</span>
              <Badge variant="light" color="success">Running</Badge>
            </div>
            <div className="flex items-center justify-between">
              <span className="text-gray-700 dark:text-gray-300">Last Check</span>
              <span className="text-sm text-gray-600 dark:text-gray-400">
                {stats?.system_health?.last_check || 'Just now'}
              </span>
            </div>
          </div>
        </Card>

        <Card className="p-6">
          <h2 className="text-lg font-semibold mb-4">Credit Usage</h2>
          <div className="space-y-4">
            <div>
              <div className="flex justify-between items-center mb-1">
                <span className="text-sm text-gray-600 dark:text-gray-400">Issued (30 days)</span>
                <span className="font-semibold">{issuedCredits.toLocaleString()}</span>
              </div>
              <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
                <div className="bg-blue-600 h-2 rounded-full" style={{ width: `${issuedPct}%` }}></div>
              </div>
            </div>
            <div>
              <div className="flex justify-between items-center mb-1">
                <span className="text-sm text-gray-600 dark:text-gray-400">Used (30 days)</span>
                <span className="font-semibold">{usedCredits.toLocaleString()}</span>
              </div>
              <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
                <div className="bg-green-600 h-2 rounded-full" style={{ width: `${usedPct}%` }}></div>
              </div>
            </div>
          </div>
        </Card>
      </div>

      {/* Admin Quick Access */}
      <Card className="p-6 mb-6">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h2 className="text-lg font-semibold">Admin Quick Access</h2>
            <p className="text-sm text-gray-500 dark:text-gray-400">Open common admin tools directly</p>
          </div>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
          {adminLinks.map((link) => (
            <a
              key={link.url}
              href={link.url}
              target="_blank"
              rel="noopener noreferrer"
              className="flex items-start justify-between rounded-lg border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-4 hover:shadow-md transition-shadow"
            >
              <div className="flex items-start gap-3">
                <div className="mt-0.5">{link.icon}</div>
                <div>
                  <p className="text-sm font-semibold text-gray-900 dark:text-white">{link.label}</p>
                  <p className="text-xs text-gray-500 dark:text-gray-400">{link.note}</p>
                </div>
              </div>
              <ExternalLink className="w-4 h-4 text-gray-400" />
            </a>
          ))}
        </div>
      </Card>

    </div>
  );
}
