'use client';

import { useState, useEffect } from 'react';
import { apiClient } from '@/lib/apiClient';
import Card from '@/components/ui/Card';
import { AdminViewModelPresenter } from '@/lib/view-models/AdminViewModelPresenter';
import { DashboardStatsViewModel } from '@/lib/view-models/AdminUserViewModel';
import { 
  Users, 
  Shield, 
  Activity, 
  Clock, 
  AlertTriangle,
  RefreshCw
} from 'lucide-react';

export function AdminDashboardPage() {
  const [stats, setStats] = useState<DashboardStatsViewModel | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

  const loadStats = async () => {
    try {
      setLoading(true);
      setError(null);
      
      const response = await apiClient.admin.getDashboardStats();
      
      // Map DTO to View Model
      const viewModel = AdminViewModelPresenter.mapDashboardStats(response);
      setStats(viewModel);
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Failed to load stats';
      if (message.includes('403') || message.includes('401')) {
        setError('Access denied - You must be logged in as an Owner or Admin');
      } else {
        setError(message);
      }
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="flex flex-col items-center justify-center py-20 space-y-3">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-blue"></div>
        <div className="text-gray-400">Loading dashboard...</div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="container mx-auto p-6">
        <div className="bg-racing-red/10 border border-racing-red text-racing-red px-4 py-3 rounded-lg flex items-start gap-3">
          <AlertTriangle className="w-5 h-5 mt-0.5 flex-shrink-0" />
          <div className="flex-1">
            <div className="font-medium">Error</div>
            <div className="text-sm opacity-90">{error}</div>
          </div>
          <button 
            onClick={loadStats}
            className="px-3 py-1 text-xs bg-racing-red/20 hover:bg-racing-red/30 rounded"
          >
            Retry
          </button>
        </div>
      </div>
    );
  }

  if (!stats) {
    return null;
  }

  // Temporary UI fields (not yet provided by API/ViewModel)
  const adminCount = stats.systemAdmins;
  const recentActivity: Array<{ description: string; timestamp: string; type: string }> = [];
  const systemHealth = 'Healthy';
  const totalSessions = 0;
  const activeSessions = 0;
  const avgSessionDuration = '—';

  return (
    <div className="container mx-auto p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Admin Dashboard</h1>
          <p className="text-gray-400 mt-1">System overview and statistics</p>
        </div>
        <button 
          onClick={loadStats} 
          disabled={loading}
          className="px-4 py-2 bg-iron-gray border border-charcoal-outline rounded-lg text-white hover:bg-iron-gray/80 transition-colors flex items-center gap-2 disabled:opacity-50"
        >
          <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
          Refresh
        </button>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <Card className="bg-gradient-to-br from-blue-900/20 to-blue-700/10">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-sm text-gray-400 mb-1">Total Users</div>
              <div className="text-3xl font-bold text-white">{stats.totalUsers}</div>
            </div>
            <Users className="w-8 h-8 text-blue-400" />
          </div>
        </Card>

        <Card className="bg-gradient-to-br from-purple-900/20 to-purple-700/10">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-sm text-gray-400 mb-1">Admins</div>
              <div className="text-3xl font-bold text-white">{adminCount}</div>
            </div>
            <Shield className="w-8 h-8 text-purple-400" />
          </div>
        </Card>

        <Card className="bg-gradient-to-br from-green-900/20 to-green-700/10">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-sm text-gray-400 mb-1">Active Users</div>
              <div className="text-3xl font-bold text-white">{stats.activeUsers}</div>
            </div>
            <Activity className="w-8 h-8 text-green-400" />
          </div>
        </Card>

        <Card className="bg-gradient-to-br from-orange-900/20 to-orange-700/10">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-sm text-gray-400 mb-1">Recent Logins</div>
              <div className="text-3xl font-bold text-white">{stats.recentLogins}</div>
            </div>
            <Clock className="w-8 h-8 text-orange-400" />
          </div>
        </Card>
      </div>

      {/* Activity Overview */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Recent Activity */}
        <Card>
          <h3 className="text-lg font-semibold text-white mb-4">Recent Activity</h3>
          <div className="space-y-3">
            {recentActivity.length > 0 ? (
              recentActivity.map((activity, index: number) => (
                <div 
                  key={index} 
                  className="flex items-center justify-between p-3 bg-iron-gray/30 rounded-lg border border-charcoal-outline/50"
                >
                  <div className="flex-1">
                    <div className="text-sm text-white">{activity.description}</div>
                    <div className="text-xs text-gray-500">{activity.timestamp}</div>
                  </div>
                  <span className={`px-2 py-1 text-xs rounded-full ${
                    activity.type === 'user_created' ? 'bg-blue-500/20 text-blue-300' :
                    activity.type === 'user_suspended' ? 'bg-yellow-500/20 text-yellow-300' :
                    activity.type === 'user_deleted' ? 'bg-red-500/20 text-red-300' :
                    'bg-gray-500/20 text-gray-300'
                  }`}>
                    {activity.type.replace('_', ' ')}
                  </span>
                </div>
              ))
            ) : (
              <div className="text-center py-8 text-gray-500">No recent activity</div>
            )}
          </div>
        </Card>

        {/* System Status */}
        <Card>
          <h3 className="text-lg font-semibold text-white mb-4">System Status</h3>
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <span className="text-sm text-gray-400">System Health</span>
              <span className="px-2 py-1 text-xs rounded-full bg-performance-green/20 text-performance-green">
                {systemHealth}
              </span>
            </div>
            <div className="flex items-center justify-between">
              <span className="text-sm text-gray-400">Total Sessions</span>
              <span className="text-white font-medium">{totalSessions}</span>
            </div>
            <div className="flex items-center justify-between">
              <span className="text-sm text-gray-400">Active Sessions</span>
              <span className="text-white font-medium">{activeSessions}</span>
            </div>
            <div className="flex items-center justify-between">
              <span className="text-sm text-gray-400">Avg Session Duration</span>
              <span className="text-white font-medium">{avgSessionDuration}</span>
            </div>
          </div>
        </Card>
      </div>

      {/* Quick Actions */}
      <Card>
        <h3 className="text-lg font-semibold text-white mb-4">Quick Actions</h3>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
          <button className="px-4 py-3 bg-primary-blue/20 border border-primary-blue/30 text-primary-blue rounded-lg hover:bg-primary-blue/30 transition-colors text-sm font-medium">
            View All Users
          </button>
          <button className="px-4 py-3 bg-purple-500/20 border border-purple-500/30 text-purple-300 rounded-lg hover:bg-purple-500/30 transition-colors text-sm font-medium">
            Manage Admins
          </button>
          <button className="px-4 py-3 bg-orange-500/20 border border-orange-500/30 text-orange-300 rounded-lg hover:bg-orange-500/30 transition-colors text-sm font-medium">
            View Audit Log
          </button>
        </div>
      </Card>
    </div>
  );
}