import { useEffect, useState } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Copy, User, Smartphone, Mail, MapPin, CreditCard, Calendar, Building, Phone, FileText, BarChart3, Radio, Loader2, Clock, TrendingUp, AlertTriangle } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import type { Client } from "@shared/schema";

interface ClientViewModalProps {
  client: Client | null;
  isOpen: boolean;
  onClose: () => void;
}

interface MonthlyUsageData {
  year: number;
  month: number;
  monthName: string;
  data: any[];
  success: boolean;
  error?: string;
}

interface SessionData {
  username?: string;
  session_id?: string;
  ip_address?: string;
  start_time?: string;
  connect_time?: string;
  subscriber_ip?: string;
  UserName?: string;
  MSISDSN?: string;
}

interface DailyUsageEntry {
  day: number;
  date: string;
  usageBytes: number;
  usageGB: string;
  entries: number;
  success: boolean;
  note?: string;
  error?: string;
}

interface DailyUsageData {
  username: string;
  year: number;
  month: number;
  currentDay: number;
  dailyUsage: DailyUsageEntry[];
  summary: {
    totalUsageBytes: number;
    totalUsageGB: string;
    todayUsageBytes: number;
    todayUsageGB: string;
    daysWithData: number;
    totalDays: number;
    errorCount: number;
  };
}

export default function ClientViewModal({ client, isOpen, onClose }: ClientViewModalProps) {
  const { toast } = useToast();
  const [usageHistory, setUsageHistory] = useState<MonthlyUsageData[]>([]);
  const [mtnFixedUsageHistory, setMtnFixedUsageHistory] = useState<MonthlyUsageData[]>([]);
  const [currentSessions, setCurrentSessions] = useState<SessionData[]>([]);
  const [dailyUsage, setDailyUsage] = useState<DailyUsageData | null>(null);
  const [mtnFixedDailyUsage, setMtnFixedDailyUsage] = useState<DailyUsageData | null>(null);
  const [loadingUsage, setLoadingUsage] = useState(false);
  const [loadingMtnFixedUsage, setLoadingMtnFixedUsage] = useState(false);
  const [loadingSessions, setLoadingSessions] = useState(false);
  const [loadingDailyUsage, setLoadingDailyUsage] = useState(false);
  const [loadingMtnFixedDailyUsage, setLoadingMtnFixedDailyUsage] = useState(false);
  const [syncInProgress, setSyncInProgress] = useState(false);
  const [mtnFixedSyncInProgress, setMtnFixedSyncInProgress] = useState(false);
  const [syncProgress, setSyncProgress] = useState<any>(null);
  const [mtnFixedSyncProgress, setMtnFixedSyncProgress] = useState<any>(null);
  const [syncSessionId, setSyncSessionId] = useState<string | null>(null);
  const [mtnFixedSyncSessionId, setMtnFixedSyncSessionId] = useState<string | null>(null);
  const [syncDebugInfo, setSyncDebugInfo] = useState<any>(null);
  const [mtnFixedSyncDebugInfo, setMtnFixedSyncDebugInfo] = useState<any>(null);

  // Fetch MTN Mobile usage data
  const fetchUsageHistory = async () => {
    if (!client?.accountNumber) return;
    
    setLoadingUsage(true);
    try {
      const response = await fetch(`/api/mtn-mobile-usage/${encodeURIComponent(client.accountNumber)}`, {
        credentials: 'include',
      });
      
      if (response.ok) {
        const data = await response.json();
        setUsageHistory(data.data || []);
      } else {
        console.error('Failed to fetch usage history');
        setUsageHistory([]);
      }
    } catch (error) {
      console.error('Error fetching usage history:', error);
      setUsageHistory([]);
    }
    setLoadingUsage(false);
  };

  // Fetch MTN Fixed usage data using the same API
  const fetchMtnFixedUsageHistory = async () => {
    if (!client?.accountNumber) return;
    
    setLoadingMtnFixedUsage(true);
    try {
      const response = await fetch(`/api/mtn-mobile-usage/${encodeURIComponent(client.accountNumber)}`, {
        credentials: 'include',
      });
      
      if (response.ok) {
        const data = await response.json();
        setMtnFixedUsageHistory(data.data || []);
      } else {
        console.error('Failed to fetch MTN Fixed usage history');
        setMtnFixedUsageHistory([]);
      }
    } catch (error) {
      console.error('Error fetching MTN Fixed usage history:', error);
      setMtnFixedUsageHistory([]);
    }
    setLoadingMtnFixedUsage(false);
  };

  // Fetch MTN Mobile current sessions
  const fetchCurrentSessions = async () => {
    if (!client?.accountNumber) return;
    
    setLoadingSessions(true);
    try {
      const response = await fetch(`/api/mtn-mobile-sessions/${encodeURIComponent(client.accountNumber)}`, {
        credentials: 'include',
      });
      
      if (response.ok) {
        const data = await response.json();
        setCurrentSessions(data.data || []);
      } else {
        console.error('Failed to fetch current sessions');
        setCurrentSessions([]);
      }
    } catch (error) {
      console.error('Error fetching current sessions:', error);
      setCurrentSessions([]);
    }
    setLoadingSessions(false);
  };

  // Fetch MTN Fixed daily usage data from database
  const fetchMtnFixedDailyUsage = async () => {
    if (!client?.accountNumber) return;
    
    setLoadingMtnFixedDailyUsage(true);
    try {
      const response = await fetch(`/api/mtn-mobile-daily-usage-db/${encodeURIComponent(client.accountNumber)}`, {
        credentials: 'include',
      });
      
      if (response.ok) {
        const result = await response.json();
        if (result.ok && result.data) {
          // Calculate summary statistics from daily usage data
          const dailyData = result.data.dailyUsage || [];
          const today = result.data.currentDay;
          
          // Calculate totals
          const totalUsageBytes = dailyData.reduce((sum, day) => sum + (day.usageBytes || 0), 0);
          const totalUsageGB = (totalUsageBytes / (1024 * 1024 * 1024)).toFixed(3);
          
          // Get today's usage
          const todayData = dailyData.find(day => day.day === today);
          const todayUsageBytes = todayData?.usageBytes || 0;
          const todayUsageGB = (todayUsageBytes / (1024 * 1024 * 1024)).toFixed(3);
          
          // Count days with data
          const daysWithData = dailyData.filter(day => day.usageBytes > 0).length;
          
          // Add summary to the data
          const enhancedData = {
            ...result.data,
            summary: {
              todayUsageGB,
              totalUsageGB,
              daysWithData,
              totalUsageBytes,
              todayUsageBytes
            }
          };
          
          setMtnFixedDailyUsage(enhancedData);
        } else {
          console.error('Failed to fetch MTN Fixed daily usage: Invalid response format');
          setMtnFixedDailyUsage(null);
        }
      } else {
        console.error('Failed to fetch MTN Fixed daily usage');
        setMtnFixedDailyUsage(null);
      }
    } catch (error) {
      console.error('Error fetching MTN Fixed daily usage:', error);
      setMtnFixedDailyUsage(null);
    }
    setLoadingMtnFixedDailyUsage(false);
  };

  // Fetch MTN Mobile daily usage data from database
  const fetchDailyUsage = async () => {
    if (!client?.accountNumber) return;
    
    setLoadingDailyUsage(true);
    try {
      console.log('Fetching daily usage for account:', client.accountNumber);
      const response = await fetch(`/api/mtn-mobile-daily-usage-db/${encodeURIComponent(client.accountNumber)}`, {
        credentials: 'include',
      });
      
      if (response.ok) {
        const result = await response.json();
        console.log('Daily usage response:', result);
        if (result.ok && result.data) {
          // Calculate summary statistics from daily usage data
          const dailyData = result.data.dailyUsage || [];
          const today = result.data.currentDay;
          
          // Calculate totals
          const totalUsageBytes = dailyData.reduce((sum, day) => sum + (day.usageBytes || 0), 0);
          const totalUsageGB = (totalUsageBytes / (1024 * 1024 * 1024)).toFixed(3);
          
          // Get today's usage
          const todayData = dailyData.find(day => day.day === today);
          const todayUsageBytes = todayData?.usageBytes || 0;
          const todayUsageGB = (todayUsageBytes / (1024 * 1024 * 1024)).toFixed(3);
          
          // Count days with data
          const daysWithData = dailyData.filter(day => day.usageBytes > 0).length;
          
          // Add summary to the data
          const enhancedData = {
            ...result.data,
            summary: {
              todayUsageGB,
              totalUsageGB,
              daysWithData,
              totalUsageBytes,
              todayUsageBytes
            }
          };
          
          console.log('Enhanced daily usage data with summary:', enhancedData);
          setDailyUsage(enhancedData);
        } else {
          console.error('Failed to fetch daily usage: Invalid response format');
          setDailyUsage(null);
        }
      } else {
        console.error('Failed to fetch daily usage:', response.status, response.statusText);
        setDailyUsage(null);
      }
    } catch (error) {
      console.error('Error fetching daily usage:', error);
      setDailyUsage(null);
    }
    setLoadingDailyUsage(false);
  };

  // Start single account sync with debugging
  const syncSingleAccount = async () => {
    if (!client?.accountNumber) {
      toast({
        title: "Error",
        description: "No account number available for sync",
        variant: "destructive",
      });
      return;
    }

    setSyncInProgress(true);
    setSyncProgress(null);
    setSyncDebugInfo(null);
    
    try {
      const response = await fetch('/api/mtn-mobile-daily-usage/sync-single', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify({
          accountNumber: client.accountNumber
        })
      });
      
      if (response.ok) {
        const result = await response.json();
        if (result.ok) {
          setSyncSessionId(result.sessionId);
          setSyncDebugInfo(result.result.debugInfo);
          
          toast({
            title: "Sync Completed",
            description: `Successfully synced account ${client.accountNumber}`,
          });
          
          // Refresh daily usage data
          fetchDailyUsage();
        } else {
          throw new Error(result.error || "Failed to sync account");
        }
      } else {
        throw new Error("Failed to sync account");
      }
    } catch (error) {
      console.error("Error syncing account:", error);
      toast({
        title: "Error",
        description: error.message || "Failed to sync account",
        variant: "destructive",
      });
    }
    
    setSyncInProgress(false);
  };

  // Sync single account data for MTN Fixed
  const syncMtnFixedSingleAccount = async () => {
    if (!client?.accountNumber) {
      toast({
        title: "Error",
        description: "No account number available for sync",
        variant: "destructive",
      });
      return;
    }

    setMtnFixedSyncInProgress(true);
    setMtnFixedSyncProgress(null);
    setMtnFixedSyncDebugInfo(null);
    
    try {
      const response = await fetch('/api/mtn-mobile-daily-usage/sync-single', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify({
          accountNumber: client.accountNumber
        })
      });
      
      if (response.ok) {
        const result = await response.json();
        if (result.ok) {
          setMtnFixedSyncSessionId(result.sessionId);
          setMtnFixedSyncDebugInfo(result.result.debugInfo);
          
          toast({
            title: "Sync Completed",
            description: `Successfully synced account ${client.accountNumber}`,
          });
          
          // Refresh daily usage data
          fetchMtnFixedDailyUsage();
        } else {
          throw new Error(result.error || "Failed to sync account");
        }
      } else {
        throw new Error("Failed to sync account");
      }
    } catch (error) {
      console.error("Error syncing MTN Fixed account:", error);
      toast({
        title: "Error",
        description: error.message || "Failed to sync account",
        variant: "destructive",
      });
    }
    
    setMtnFixedSyncInProgress(false);
  };

  // Track client view and fetch MTN Mobile data when modal opens
  useEffect(() => {
    if (isOpen && client?.id) {
      // Track client view
      fetch(`/api/track-view/${client.id}`, {
        method: 'POST',
        credentials: 'include',
      }).catch(console.error);

      // Fetch MTN Mobile data if this is an MTN Mobile (GSM) client
      if (client.category === "MTN Mobile (GSM)" && client.accountNumber) {
        fetchUsageHistory();
        fetchCurrentSessions();
        fetchDailyUsage();
      }
      
      // Fetch MTN Fixed data if this is an MTN Fixed client
      if (client.category === "MTN Fixed" && client.accountNumber) {
        fetchMtnFixedUsageHistory();
        fetchMtnFixedDailyUsage();
      }
    }
    
    // Reset data when modal closes
    if (!isOpen) {
      setUsageHistory([]);
      setMtnFixedUsageHistory([]);
      setCurrentSessions([]);
      setDailyUsage(null);
      setMtnFixedDailyUsage(null);
    }
  }, [isOpen, client?.id, client?.category, client?.accountNumber]);

  if (!client) return null;

  const formatBytes = (bytes: number): string => {
    if (bytes === 0) return '0 GB';
    const gb = bytes / (1024 * 1024 * 1024);
    return `${gb.toFixed(2)} GB`;
  };

  const copyToClipboard = (text: string, label: string) => {
    navigator.clipboard.writeText(text).then(() => {
      toast({
        title: "Copied!",
        description: `${label} copied to clipboard`,
      });
    }).catch(() => {
      toast({
        title: "Copy failed",
        description: "Unable to copy to clipboard",
        variant: "destructive",
      });
    });
  };

  const copyAllInfo = () => {
    const allInfo = `
Client Information:
==================
Name: ${client.name || 'N/A'}
Category: ${client.category || 'N/A'}
Email: ${client.email || 'N/A'}
MSISDN: ${client.msisdn || 'N/A'}
Account Number: ${client.accountNumber || 'N/A'}
Service Details: ${client.serviceDetails || 'N/A'}
Status: ${client.status || 'N/A'}
Status 2: ${client.status2 || 'N/A'}
MSISDN: ${client.msisdn || 'N/A'}
SIM Serial Number: ${client.simSerialNumber || 'N/A'}
Contact Info: ${client.contactInfo || 'N/A'}
Address: ${client.address || 'N/A'}
Notes: ${client.notes || 'N/A'}
Is Reseller: ${client.isReseller ? 'Yes' : 'No'}
Created: ${client.createdAt ? new Date(client.createdAt).toLocaleString() : 'N/A'}
Updated: ${client.updatedAt ? new Date(client.updatedAt).toLocaleString() : 'N/A'}
    `.trim();

    copyToClipboard(allInfo, "All client information");
  };

  const InfoRow = ({ icon: Icon, label, value, copyable = true }: { 
    icon: any, 
    label: string, 
    value: string | null | undefined, 
    copyable?: boolean 
  }) => {
    if (!value) return null;
    
    return (
      <div className="flex items-center justify-between py-2 border-b border-gray-100 last:border-b-0">
        <div className="flex items-center space-x-2">
          <Icon className="w-4 h-4 text-gray-500" />
          <span className="text-sm font-medium text-gray-700">{label}:</span>
          <span className="text-sm text-gray-900">{value}</span>
        </div>
        {copyable && (
          <Button
            variant="ghost"
            size="sm"
            onClick={() => copyToClipboard(value, label)}
            className="h-6 w-6 p-0 hover:bg-gray-100"
          >
            <Copy className="w-3 h-3" />
          </Button>
        )}
      </div>
    );
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center space-x-2">
            <User className="w-5 h-5 text-blue-600" />
            <span>Account Information - {client.name}</span>
            {client.isReseller && (
              <Badge className="bg-purple-100 text-purple-800">
                Reseller
              </Badge>
            )}
          </DialogTitle>
          <DialogDescription>
            View and copy account details for {client.name}
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          {/* Quick Actions */}
          <div className="flex justify-end">
            <Button onClick={copyAllInfo} className="flex items-center space-x-2">
              <Copy className="w-4 h-4" />
              <span>Copy All Information</span>
            </Button>
          </div>

          {/* Personal Information */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg flex items-center space-x-2">
                <User className="w-5 h-5 text-blue-600" />
                <span>Personal Information</span>
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-1">
                <InfoRow icon={User} label="Full Name" value={client.name} />
                <InfoRow icon={Mail} label="Email Address" value={client.email || "No Email Address Configured"} />
                <InfoRow icon={Building} label="Category" value={client.category} copyable={false} />
              </div>
            </CardContent>
          </Card>

          {/* Contact Information */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg flex items-center space-x-2">
                <Phone className="w-5 h-5 text-green-600" />
                <span>Contact Information</span>
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-1">
                <InfoRow icon={Smartphone} label="MSISDN" value={client.msisdn} />
                <InfoRow icon={Phone} label="Contact Info" value={client.contactInfo} />
                <InfoRow icon={Smartphone} label="SIM Serial Number" value={client.simSerialNumber} />
              </div>
            </CardContent>
          </Card>

          {/* Account Details */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg flex items-center space-x-2">
                <CreditCard className="w-5 h-5 text-orange-600" />
                <span>Account Details</span>
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-1">
                <InfoRow icon={CreditCard} label="Account Number" value={client.accountNumber} />
                <InfoRow icon={MapPin} label="Address" value={client.address} />
                <InfoRow icon={Building} label="Service Details" value={client.serviceDetails} />
              </div>
            </CardContent>
          </Card>

          {/* Status Information */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg flex items-center space-x-2">
                <Badge className="w-5 h-5 text-purple-600" />
                <span>Status Information</span>
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-1">
                <div className="flex items-center justify-between py-2 border-b border-gray-100">
                  <div className="flex items-center space-x-2">
                    <Badge className="w-4 h-4 text-gray-500" />
                    <span className="text-sm font-medium text-gray-700">Status:</span>
                    <Badge variant={client.status === 'Active' ? 'default' : 'secondary'}>
                      {client.status || 'N/A'}
                    </Badge>
                  </div>
                  {client.status && (
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => copyToClipboard(client.status!, "Status")}
                      className="h-6 w-6 p-0 hover:bg-gray-100"
                    >
                      <Copy className="w-3 h-3" />
                    </Button>
                  )}
                </div>
                
                {client.status2 && (
                  <div className="flex items-center justify-between py-2 border-b border-gray-100">
                    <div className="flex items-center space-x-2">
                      <Badge className="w-4 h-4 text-gray-500" />
                      <span className="text-sm font-medium text-gray-700">Status 2:</span>
                      <Badge variant="outline">{client.status2}</Badge>
                    </div>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => copyToClipboard(client.status2!, "Status 2")}
                      className="h-6 w-6 p-0 hover:bg-gray-100"
                    >
                      <Copy className="w-3 h-3" />
                    </Button>
                  </div>
                )}

                <div className="flex items-center justify-between py-2">
                  <div className="flex items-center space-x-2">
                    <Building className="w-4 h-4 text-gray-500" />
                    <span className="text-sm font-medium text-gray-700">Reseller Account:</span>
                    <Badge variant={client.isReseller ? "default" : "outline"}>
                      {client.isReseller ? 'Yes' : 'No'}
                    </Badge>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Comments/Notes */}
          {client.notes && (
            <Card>
              <CardHeader>
                <CardTitle className="text-lg flex items-center space-x-2">
                  <FileText className="w-5 h-5 text-blue-600" />
                  <span>Comments & Notes</span>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="bg-gray-50 rounded-lg p-4 border border-gray-200">
                  <p className="text-sm text-gray-800 whitespace-pre-wrap">{client.notes}</p>
                  <div className="flex justify-end mt-2">
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => copyToClipboard(client.notes!, "Notes")}
                      className="h-6 w-6 p-0 hover:bg-gray-100"
                    >
                      <Copy className="w-3 h-3" />
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          )}

          {/* MTN Mobile (GSM) Usage History - Radius */}
          {client.category === "MTN Mobile (GSM)" && (
            <Card>
              <CardHeader>
                <CardTitle className="text-lg flex items-center space-x-2">
                  <BarChart3 className="w-5 h-5 text-orange-600" />
                  <span>3-Month Usage History - Radius</span>
                  {loadingUsage && <Loader2 className="w-4 h-4 animate-spin" />}
                </CardTitle>
              </CardHeader>
              <CardContent>
                {loadingUsage ? (
                  <div className="flex items-center justify-center py-8">
                    <Loader2 className="w-6 h-6 animate-spin text-orange-600" />
                    <span className="ml-2 text-gray-600">Loading usage data...</span>
                  </div>
                ) : usageHistory.length > 0 ? (
                  <div className="grid gap-4 md:grid-cols-3">
                    {usageHistory.map((month, index) => (
                      <div key={`radius-${month.year}-${month.month}`} className="bg-gradient-to-br from-orange-50 to-orange-100 rounded-lg p-4 border border-orange-200">
                        <div className="text-center">
                          <h4 className="font-semibold text-orange-900 mb-2">
                            {month.monthName} {month.year}
                            {index === 0 && <Badge className="ml-2 bg-orange-600 text-white text-xs">Current</Badge>}
                          </h4>
                          {month.success && month.data.length > 0 ? (
                            <div className="space-y-2">
                              {month.data.map((usage, idx) => (
                                <div key={idx} className="text-center">
                                  <div className="text-2xl font-bold text-orange-800">
                                    {formatBytes(parseInt(usage.Total) || 0)}
                                  </div>
                                  <div className="text-xs text-orange-600">
                                    Connected: {usage.ConnectedTime || '0:00:00'}
                                  </div>
                                  {usage.MSISDSN && (
                                    <div className="text-xs text-gray-600 font-mono">
                                      {usage.MSISDSN}
                                    </div>
                                  )}
                                </div>
                              ))}
                            </div>
                          ) : (
                            <div className="text-center">
                              <div className="text-2xl font-bold text-gray-400">0 GB</div>
                              <div className="text-xs text-gray-500">No usage data</div>
                            </div>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="text-center py-8 text-gray-500">
                    No usage history available for this account
                  </div>
                )}
              </CardContent>
            </Card>
          )}

          {/* MTN Mobile (GSM) Usage History - Client Billable */}
          {client.category === "MTN Mobile (GSM)" && (
            <Card>
              <CardHeader>
                <CardTitle className="text-lg flex items-center space-x-2">
                  <BarChart3 className="w-5 h-5 text-blue-600" />
                  <span>3-Month Usage History - Client Billable</span>
                  {loadingUsage && <Loader2 className="w-4 h-4 animate-spin" />}
                </CardTitle>
              </CardHeader>
              <CardContent>
                {loadingUsage ? (
                  <div className="flex items-center justify-center py-8">
                    <Loader2 className="w-6 h-6 animate-spin text-blue-600" />
                    <span className="ml-2 text-gray-600">Loading usage data...</span>
                  </div>
                ) : usageHistory.length > 0 ? (
                  <div className="grid gap-4 md:grid-cols-3">
                    {usageHistory.map((month, index) => (
                      <div key={`billable-${month.year}-${month.month}`} className="bg-gradient-to-br from-blue-50 to-blue-100 rounded-lg p-4 border border-blue-200">
                        <div className="text-center">
                          <h4 className="font-semibold text-blue-900 mb-2">
                            {month.monthName} {month.year}
                            {index === 0 && <Badge className="ml-2 bg-blue-600 text-white text-xs">Current</Badge>}
                          </h4>
                          {month.success && month.data.length > 0 ? (
                            <div className="space-y-2">
                              {month.data.map((usage, idx) => (
                                <div key={idx} className="text-center">
                                  <div className="text-2xl font-bold text-blue-800">
                                    {formatBytes((parseInt(usage.Total) || 0) * 2)}
                                  </div>
                                  <div className="text-xs text-blue-600">
                                    Connected: {usage.ConnectedTime || '0:00:00'}
                                  </div>
                                  {usage.MSISDSN && (
                                    <div className="text-xs text-gray-600 font-mono">
                                      {usage.MSISDSN}
                                    </div>
                                  )}
                                </div>
                              ))}
                            </div>
                          ) : (
                            <div className="text-center">
                              <div className="text-2xl font-bold text-gray-400">0 GB</div>
                              <div className="text-xs text-gray-500">No usage data</div>
                            </div>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="text-center py-8 text-gray-500">
                    No usage history available for this account
                  </div>
                )}
              </CardContent>
            </Card>
          )}

          {/* MTN Fixed Usage History - Radius */}
          {client.category === "MTN Fixed" && (
            <Card>
              <CardHeader>
                <CardTitle className="text-lg flex items-center space-x-2">
                  <BarChart3 className="w-5 h-5 text-orange-600" />
                  <span>3-Month Usage History - Radius</span>
                  {loadingMtnFixedUsage && <Loader2 className="w-4 h-4 animate-spin" />}
                </CardTitle>
              </CardHeader>
              <CardContent>
                {loadingMtnFixedUsage ? (
                  <div className="flex items-center justify-center py-8">
                    <Loader2 className="w-6 h-6 animate-spin text-orange-600" />
                    <span className="ml-2 text-gray-600">Loading usage data...</span>
                  </div>
                ) : mtnFixedUsageHistory.length > 0 ? (
                  <div className="grid gap-4 md:grid-cols-3">
                    {mtnFixedUsageHistory.map((month, index) => (
                      <div key={`mtn-fixed-radius-${month.year}-${month.month}`} className="bg-gradient-to-br from-orange-50 to-orange-100 rounded-lg p-4 border border-orange-200">
                        <div className="text-center">
                          <h4 className="font-semibold text-orange-900 mb-2">
                            {month.monthName} {month.year}
                            {index === 0 && <Badge className="ml-2 bg-orange-600 text-white text-xs">Current</Badge>}
                          </h4>
                          {month.success && month.data.length > 0 ? (
                            <div className="space-y-2">
                              {month.data.map((usage, idx) => (
                                <div key={idx} className="text-center">
                                  <div className="text-2xl font-bold text-orange-800">
                                    {formatBytes(parseInt(usage.Total) || 0)}
                                  </div>
                                  <div className="text-xs text-orange-600">
                                    Connected: {usage.ConnectedTime || '0:00:00'}
                                  </div>
                                  {usage.MSISDSN && (
                                    <div className="text-xs text-gray-600 font-mono">
                                      {usage.MSISDSN}
                                    </div>
                                  )}
                                </div>
                              ))}
                            </div>
                          ) : (
                            <div className="text-center">
                              <div className="text-2xl font-bold text-gray-400">0 GB</div>
                              <div className="text-xs text-gray-500">No usage data</div>
                            </div>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="text-center py-8 text-gray-500">
                    No usage history available for this account
                  </div>
                )}
              </CardContent>
            </Card>
          )}

          {/* MTN Fixed Usage History - Client Billable */}
          {client.category === "MTN Fixed" && (
            <Card>
              <CardHeader>
                <CardTitle className="text-lg flex items-center space-x-2">
                  <BarChart3 className="w-5 h-5 text-blue-600" />
                  <span>3-Month Usage History - Client Billable</span>
                  {loadingMtnFixedUsage && <Loader2 className="w-4 h-4 animate-spin" />}
                </CardTitle>
              </CardHeader>
              <CardContent>
                {loadingMtnFixedUsage ? (
                  <div className="flex items-center justify-center py-8">
                    <Loader2 className="w-6 h-6 animate-spin text-blue-600" />
                    <span className="ml-2 text-gray-600">Loading usage data...</span>
                  </div>
                ) : mtnFixedUsageHistory.length > 0 ? (
                  <div className="grid gap-4 md:grid-cols-3">
                    {mtnFixedUsageHistory.map((month, index) => (
                      <div key={`mtn-fixed-billable-${month.year}-${month.month}`} className="bg-gradient-to-br from-blue-50 to-blue-100 rounded-lg p-4 border border-blue-200">
                        <div className="text-center">
                          <h4 className="font-semibold text-blue-900 mb-2">
                            {month.monthName} {month.year}
                            {index === 0 && <Badge className="ml-2 bg-blue-600 text-white text-xs">Current</Badge>}
                          </h4>
                          {month.success && month.data.length > 0 ? (
                            <div className="space-y-2">
                              {month.data.map((usage, idx) => (
                                <div key={idx} className="text-center">
                                  <div className="text-2xl font-bold text-blue-800">
                                    {formatBytes((parseInt(usage.Total) || 0) * 2)}
                                  </div>
                                  <div className="text-xs text-blue-600">
                                    Connected: {usage.ConnectedTime || '0:00:00'}
                                  </div>
                                  {usage.MSISDSN && (
                                    <div className="text-xs text-gray-600 font-mono">
                                      {usage.MSISDSN}
                                    </div>
                                  )}
                                </div>
                              ))}
                            </div>
                          ) : (
                            <div className="text-center">
                              <div className="text-2xl font-bold text-gray-400">0 GB</div>
                              <div className="text-xs text-gray-500">No usage data</div>
                            </div>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="text-center py-8 text-gray-500">
                    No usage history available for this account
                  </div>
                )}
              </CardContent>
            </Card>
          )}

          {/* MTN Fixed Daily Usage for Current Month */}
          {client.category === "MTN Fixed" && (
            <Card className="bg-orange-50 dark:bg-orange-950/20 border-orange-200 dark:border-orange-800">
              <CardHeader>
                <CardTitle className="text-lg flex items-center justify-between text-orange-800 dark:text-orange-300">
                  <div className="flex items-center space-x-2">
                    <Clock className="w-5 h-5 text-orange-600" />
                    <span>Daily Usage - {new Date().toLocaleString('default', { month: 'long', year: 'numeric' })}</span>
                    {loadingMtnFixedDailyUsage && <Loader2 className="w-4 h-4 animate-spin" />}
                  </div>
                  <Button
                    onClick={syncMtnFixedSingleAccount}
                    disabled={mtnFixedSyncInProgress}
                    size="sm"
                    className="bg-orange-600 hover:bg-orange-700 text-white"
                  >
                    {mtnFixedSyncInProgress ? (
                      <>
                        <Loader2 className="h-4 w-4 animate-spin mr-2" />
                        Syncing...
                      </>
                    ) : (
                      <>
                        <Radio className="h-4 w-4 mr-2" />
                        Sync Daily Usage
                      </>
                    )}
                  </Button>
                </CardTitle>
              </CardHeader>
              <CardContent>
                {/* Sync Progress Bar */}
                {mtnFixedSyncInProgress && mtnFixedSyncProgress && (
                  <div className="mb-4 p-4 bg-orange-50 dark:bg-orange-950/20 rounded-lg border border-orange-200 dark:border-orange-800">
                    <div className="flex items-center gap-3 mb-3">
                      <Loader2 className="h-5 w-5 animate-spin text-orange-600" />
                      <div className="flex-1">
                        <div className="text-sm font-medium text-orange-800 dark:text-orange-300">
                          {mtnFixedSyncProgress.currentStatus}
                        </div>
                        <div className="text-xs text-orange-600 dark:text-orange-400 mt-1">
                          {mtnFixedSyncProgress.currentAccount && `Current: ${mtnFixedSyncProgress.currentAccount}`}
                        </div>
                      </div>
                    </div>
                    
                    {/* Progress bars */}
                    <div className="space-y-2">
                      {/* Accounts progress */}
                      <div>
                        <div className="flex justify-between text-xs text-orange-600 dark:text-orange-400 mb-1">
                          <span>Accounts</span>
                          <span>{mtnFixedSyncProgress.processedAccounts}/{mtnFixedSyncProgress.totalAccounts}</span>
                        </div>
                        <div className="w-full bg-orange-200 dark:bg-orange-800 rounded-full h-2">
                          <div 
                            className="bg-orange-600 h-2 rounded-full transition-all duration-300"
                            style={{ 
                              width: `${mtnFixedSyncProgress.totalAccounts > 0 ? (mtnFixedSyncProgress.processedAccounts / mtnFixedSyncProgress.totalAccounts) * 100 : 0}%`
                            }}
                          />
                        </div>
                      </div>
                      
                      {/* Days progress */}
                      {mtnFixedSyncProgress.totalDays > 0 && (
                        <div>
                          <div className="flex justify-between text-xs text-orange-600 dark:text-orange-400 mb-1">
                            <span>Days</span>
                            <span>{mtnFixedSyncProgress.processedDays}/{mtnFixedSyncProgress.totalDays}</span>
                          </div>
                          <div className="w-full bg-orange-200 dark:bg-orange-800 rounded-full h-2">
                            <div 
                              className="bg-orange-600 h-2 rounded-full transition-all duration-300"
                              style={{ 
                                width: `${(mtnFixedSyncProgress.processedDays / mtnFixedSyncProgress.totalDays) * 100}%`
                              }}
                            />
                          </div>
                        </div>
                      )}
                    </div>
                    
                    {/* Errors */}
                    {mtnFixedSyncProgress.errors && mtnFixedSyncProgress.errors.length > 0 && (
                      <div className="mt-3 p-2 bg-red-50 dark:bg-red-950/20 rounded border border-red-200 dark:border-red-800">
                        <div className="flex items-center gap-2 text-sm text-red-800 dark:text-red-300">
                          <AlertTriangle className="h-4 w-4" />
                          <span>{mtnFixedSyncProgress.errors.length} error(s) occurred</span>
                        </div>
                      </div>
                    )}
                  </div>
                )}
                {loadingMtnFixedDailyUsage ? (
                  <div className="flex items-center justify-center py-8">
                    <Loader2 className="w-6 h-6 animate-spin text-orange-600" />
                    <span className="ml-2 text-gray-600">Loading daily usage data...</span>
                  </div>
                ) : mtnFixedDailyUsage ? (
                  <div className="space-y-6">
                    {/* Summary Cards */}
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                      <div className="bg-gradient-to-br from-orange-50 to-orange-100 rounded-lg p-4 border border-orange-200">
                        <div className="text-center">
                          <h4 className="font-semibold text-orange-900 mb-1">Today's Usage</h4>
                          <div className="text-2xl font-bold text-orange-800">
                            {(parseFloat(mtnFixedDailyUsage.summary.todayUsageGB) * 2).toFixed(3)} GB
                          </div>
                          <div className="text-xs text-orange-600">
                            Day {mtnFixedDailyUsage.currentDay} of {new Date(mtnFixedDailyUsage.year, mtnFixedDailyUsage.month, 0).getDate()}
                          </div>
                        </div>
                      </div>
                      
                      <div className="bg-gradient-to-br from-amber-50 to-amber-100 rounded-lg p-4 border border-amber-200">
                        <div className="text-center">
                          <h4 className="font-semibold text-amber-900 mb-1">Total This Month</h4>
                          <div className="text-2xl font-bold text-amber-800">
                            {(parseFloat(mtnFixedDailyUsage.summary.totalUsageGB) * 2).toFixed(3)} GB
                          </div>
                          <div className="text-xs text-amber-600">
                            {mtnFixedDailyUsage.summary.daysWithData} days with data
                          </div>
                        </div>
                      </div>
                      
                      <div className="bg-gradient-to-br from-yellow-50 to-yellow-100 rounded-lg p-4 border border-yellow-200">
                        <div className="text-center">
                          <h4 className="font-semibold text-yellow-900 mb-1">Daily Average</h4>
                          <div className="text-2xl font-bold text-yellow-800">
                            {mtnFixedDailyUsage.summary.daysWithData > 0 
                              ? ((parseFloat(mtnFixedDailyUsage.summary.totalUsageGB) * 2) / mtnFixedDailyUsage.summary.daysWithData).toFixed(2) 
                              : '0.00'} GB
                          </div>
                          <div className="text-xs text-yellow-600">
                            Over {mtnFixedDailyUsage.summary.daysWithData} active days
                          </div>
                        </div>
                      </div>
                    </div>

                    {/* Daily Breakdown */}
                    <div>
                      <h4 className="font-semibold text-gray-900 mb-3 flex items-center">
                        <TrendingUp className="w-4 h-4 mr-2 text-orange-600" />
                        Daily Breakdown (Client Billable)
                      </h4>
                      <div className="max-h-64 overflow-y-auto border rounded-lg">
                        <div className="grid gap-2 p-4">
                          {mtnFixedDailyUsage.dailyUsage.slice().reverse().map((day) => (
                            <div 
                              key={day.day} 
                              className={`flex items-center justify-between p-3 rounded-lg border ${
                                day.day === mtnFixedDailyUsage.currentDay 
                                  ? 'bg-orange-50 border-orange-200' 
                                  : day.usageBytes > 0 
                                    ? 'bg-gray-50 border-gray-200' 
                                    : 'bg-red-50 border-red-200'
                              }`}
                            >
                              <div className="flex items-center space-x-3">
                                <div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold ${
                                  day.day === mtnFixedDailyUsage.currentDay 
                                    ? 'bg-orange-600 text-white' 
                                    : day.usageBytes > 0 
                                      ? 'bg-gray-600 text-white' 
                                      : 'bg-red-600 text-white'
                                }`}>
                                  {day.day}
                                </div>
                                <div>
                                  <div className="font-medium text-gray-900">
                                    {new Date(day.date).toLocaleDateString('en-US', { 
                                      weekday: 'short', 
                                      month: 'short', 
                                      day: 'numeric' 
                                    })}
                                    {day.day === mtnFixedDailyUsage.currentDay && (
                                      <Badge className="ml-2 bg-orange-600 text-white text-xs">Today</Badge>
                                    )}
                                  </div>
                                  <div className="text-xs text-gray-500">
                                    {day.success 
                                      ? `${day.entries} session${day.entries !== 1 ? 's' : ''}` 
                                      : day.error || 'Error loading data'
                                    }
                                  </div>
                                </div>
                              </div>
                              <div className="text-right">
                                <div className={`font-bold ${
                                  day.usageBytes > 0 ? 'text-gray-900' : 'text-gray-400'
                                }`}>
                                  {day.usageBytes > 0 ? (parseFloat(day.usageGB) * 2).toFixed(3) : '0.000'} GB
                                </div>
                                <div className="text-xs text-gray-500">
                                  {day.usageBytes > 0 
                                    ? `${((day.usageBytes * 2) / (1024 * 1024)).toFixed(0)} MB` 
                                    : 'No usage'
                                  }
                                </div>
                              </div>
                            </div>
                          ))}
                        </div>
                      </div>
                    </div>

                    {mtnFixedDailyUsage.summary.errorCount > 0 && (
                      <div className="bg-red-50 border border-red-200 rounded-lg p-4">
                        <div className="flex items-center space-x-2">
                          <AlertTriangle className="w-4 h-4 text-red-600" />
                          <span className="text-sm font-medium text-red-800">
                            {mtnFixedDailyUsage.summary.errorCount} day{mtnFixedDailyUsage.summary.errorCount !== 1 ? 's' : ''} failed to load
                          </span>
                        </div>
                        <div className="text-xs text-red-600 mt-1">
                          Some daily usage data could not be retrieved from the API
                        </div>
                      </div>
                    )}
                  </div>
                ) : (
                  <div className="text-center py-8 text-gray-500">
                    No daily usage data available for this account
                  </div>
                )}
              </CardContent>
            </Card>
          )}

          {/* MTN Mobile (GSM) Current Sessions */}
          {client.category === "MTN Mobile (GSM)" && (
            <Card>
              <CardHeader>
                <CardTitle className="text-lg flex items-center space-x-2">
                  <Radio className="w-5 h-5 text-green-600" />
                  <span>Current Active Sessions</span>
                  {loadingSessions && <Loader2 className="w-4 h-4 animate-spin" />}
                </CardTitle>
              </CardHeader>
              <CardContent>
                {loadingSessions ? (
                  <div className="flex items-center justify-center py-8">
                    <Loader2 className="w-6 h-6 animate-spin text-green-600" />
                    <span className="ml-2 text-gray-600">Loading session data...</span>
                  </div>
                ) : currentSessions.length > 0 ? (
                  <div className="space-y-4">
                    {currentSessions.map((session, index) => (
                      <div key={index} className="bg-gradient-to-r from-green-50 to-green-100 rounded-lg p-4 border border-green-200">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                          {session.username && (
                            <div className="flex items-center justify-between">
                              <div className="flex items-center space-x-2">
                                <User className="w-4 h-4 text-green-600" />
                                <span className="text-sm font-medium text-gray-700">Username:</span>
                                <span className="text-sm text-gray-900 font-mono">{session.username}</span>
                              </div>
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => copyToClipboard(session.username, "Username")}
                                className="h-6 w-6 p-0 hover:bg-green-100"
                              >
                                <Copy className="w-3 h-3" />
                              </Button>
                            </div>
                          )}
                          
                          {session.session_id && (
                            <div className="flex items-center justify-between">
                              <div className="flex items-center space-x-2">
                                <CreditCard className="w-4 h-4 text-green-600" />
                                <span className="text-sm font-medium text-gray-700">Session ID:</span>
                                <span className="text-sm text-gray-900 font-mono truncate">{session.session_id}</span>
                              </div>
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => copyToClipboard(session.session_id, "Session ID")}
                                className="h-6 w-6 p-0 hover:bg-green-100"
                              >
                                <Copy className="w-3 h-3" />
                              </Button>
                            </div>
                          )}
                          
                          {(session.ip_address || session.subscriber_ip) && (
                            <div className="flex items-center justify-between">
                              <div className="flex items-center space-x-2">
                                <MapPin className="w-4 h-4 text-green-600" />
                                <span className="text-sm font-medium text-gray-700">IP Address:</span>
                                <span className="text-sm text-gray-900 font-mono">{session.ip_address || session.subscriber_ip}</span>
                              </div>
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => copyToClipboard(session.ip_address || session.subscriber_ip || '', "IP Address")}
                                className="h-6 w-6 p-0 hover:bg-green-100"
                              >
                                <Copy className="w-3 h-3" />
                              </Button>
                            </div>
                          )}
                          
                          {(session.start_time || session.connect_time) && (
                            <div className="flex items-center justify-between">
                              <div className="flex items-center space-x-2">
                                <Calendar className="w-4 h-4 text-green-600" />
                                <span className="text-sm font-medium text-gray-700">Connect Time:</span>
                                <span className="text-sm text-gray-900">{session.start_time || session.connect_time}</span>
                              </div>
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => copyToClipboard(session.start_time || session.connect_time || '', "Connect Time")}
                                className="h-6 w-6 p-0 hover:bg-green-100"
                              >
                                <Copy className="w-3 h-3" />
                              </Button>
                            </div>
                          )}
                          
                          {(session.MSISDSN || session.UserName) && (
                            <div className="col-span-1 md:col-span-2">
                              <div className="flex items-center justify-between">
                                <div className="flex items-center space-x-2">
                                  <Smartphone className="w-4 h-4 text-green-600" />
                                  <span className="text-sm font-medium text-gray-700">MSISDN:</span>
                                  <span className="text-sm text-gray-900 font-mono">{session.MSISDSN}</span>
                                  {session.UserName && session.UserName !== session.MSISDSN && (
                                    <span className="text-sm text-gray-600">({session.UserName})</span>
                                  )}
                                </div>
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  onClick={() => copyToClipboard(session.MSISDSN || '', "MSISDN")}
                                  className="h-6 w-6 p-0 hover:bg-green-100"
                                >
                                  <Copy className="w-3 h-3" />
                                </Button>
                              </div>
                            </div>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="text-center py-8 text-gray-500">
                    No active sessions found for this account
                  </div>
                )}
              </CardContent>
            </Card>
          )}

          {/* MTN Mobile (GSM) Daily Usage for Current Month */}
          {client.category === "MTN Mobile (GSM)" && (
            <Card className="bg-purple-50 dark:bg-purple-950/20 border-purple-200 dark:border-purple-800">
              <CardHeader>
                <CardTitle className="text-lg flex items-center justify-between text-purple-800 dark:text-purple-300">
                  <div className="flex items-center space-x-2">
                    <Clock className="w-5 h-5 text-purple-600" />
                    <span>Daily Usage - {new Date().toLocaleString('default', { month: 'long', year: 'numeric' })}</span>
                    {loadingDailyUsage && <Loader2 className="w-4 h-4 animate-spin" />}
                  </div>
                  <Button
                    onClick={syncSingleAccount}
                    disabled={syncInProgress}
                    size="sm"
                    className="bg-purple-600 hover:bg-purple-700 text-white"
                  >
                    {syncInProgress ? (
                      <>
                        <Loader2 className="h-4 w-4 animate-spin mr-2" />
                        Syncing...
                      </>
                    ) : (
                      <>
                        <Radio className="h-4 w-4 mr-2" />
                        Sync Daily Usage
                      </>
                    )}
                  </Button>
                </CardTitle>
              </CardHeader>
              <CardContent>
                {/* Sync Progress Bar */}
                {syncInProgress && syncProgress && (
                  <div className="mb-4 p-4 bg-blue-50 dark:bg-blue-950/20 rounded-lg border border-blue-200 dark:border-blue-800">
                    <div className="flex items-center gap-3 mb-3">
                      <Loader2 className="h-5 w-5 animate-spin text-blue-600" />
                      <div className="flex-1">
                        <div className="text-sm font-medium text-blue-800 dark:text-blue-300">
                          {syncProgress.currentStatus}
                        </div>
                        <div className="text-xs text-blue-600 dark:text-blue-400 mt-1">
                          {syncProgress.currentAccount && `Current: ${syncProgress.currentAccount}`}
                        </div>
                      </div>
                    </div>
                    
                    {/* Progress bars */}
                    <div className="space-y-2">
                      {/* Accounts progress */}
                      <div>
                        <div className="flex justify-between text-xs text-blue-600 dark:text-blue-400 mb-1">
                          <span>Accounts</span>
                          <span>{syncProgress.processedAccounts}/{syncProgress.totalAccounts}</span>
                        </div>
                        <div className="w-full bg-blue-200 dark:bg-blue-800 rounded-full h-2">
                          <div 
                            className="bg-blue-600 h-2 rounded-full transition-all duration-300"
                            style={{ 
                              width: `${syncProgress.totalAccounts > 0 ? (syncProgress.processedAccounts / syncProgress.totalAccounts) * 100 : 0}%`
                            }}
                          />
                        </div>
                      </div>
                      
                      {/* Days progress */}
                      {syncProgress.totalDays > 0 && (
                        <div>
                          <div className="flex justify-between text-xs text-blue-600 dark:text-blue-400 mb-1">
                            <span>Days</span>
                            <span>{syncProgress.processedDays}/{syncProgress.totalDays}</span>
                          </div>
                          <div className="w-full bg-blue-200 dark:bg-blue-800 rounded-full h-2">
                            <div 
                              className="bg-blue-600 h-2 rounded-full transition-all duration-300"
                              style={{ 
                                width: `${(syncProgress.processedDays / syncProgress.totalDays) * 100}%`
                              }}
                            />
                          </div>
                        </div>
                      )}
                    </div>
                    
                    {/* Errors */}
                    {syncProgress.errors && syncProgress.errors.length > 0 && (
                      <div className="mt-3 p-2 bg-red-50 dark:bg-red-950/20 rounded border border-red-200 dark:border-red-800">
                        <div className="flex items-center gap-2 text-sm text-red-800 dark:text-red-300">
                          <AlertTriangle className="h-4 w-4" />
                          <span>{syncProgress.errors.length} error(s) occurred</span>
                        </div>
                      </div>
                    )}
                  </div>
                )}
                {loadingDailyUsage ? (
                  <div className="flex items-center justify-center py-8">
                    <Loader2 className="w-6 h-6 animate-spin text-purple-600" />
                    <span className="ml-2 text-gray-600">Loading daily usage data...</span>
                  </div>
                ) : dailyUsage ? (
                  <div className="space-y-6">
                    {/* Summary Cards */}
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                      <div className="bg-gradient-to-br from-purple-50 to-purple-100 rounded-lg p-4 border border-purple-200">
                        <div className="text-center">
                          <h4 className="font-semibold text-purple-900 mb-1">Today's Usage</h4>
                          <div className="text-2xl font-bold text-purple-800">
                            {(parseFloat(dailyUsage.summary.todayUsageGB) * 2).toFixed(3)} GB
                          </div>
                          <div className="text-xs text-purple-600">
                            Day {dailyUsage.currentDay} of {new Date(dailyUsage.year, dailyUsage.month, 0).getDate()}
                          </div>
                        </div>
                      </div>
                      
                      <div className="bg-gradient-to-br from-indigo-50 to-indigo-100 rounded-lg p-4 border border-indigo-200">
                        <div className="text-center">
                          <h4 className="font-semibold text-indigo-900 mb-1">Total This Month</h4>
                          <div className="text-2xl font-bold text-indigo-800">
                            {(parseFloat(dailyUsage.summary.totalUsageGB) * 2).toFixed(3)} GB
                          </div>
                          <div className="text-xs text-indigo-600">
                            {dailyUsage.summary.daysWithData} days with data
                          </div>
                        </div>
                      </div>
                      
                      <div className="bg-gradient-to-br from-green-50 to-green-100 rounded-lg p-4 border border-green-200">
                        <div className="text-center">
                          <h4 className="font-semibold text-green-900 mb-1">Daily Average</h4>
                          <div className="text-2xl font-bold text-green-800">
                            {dailyUsage.summary.daysWithData > 0 
                              ? ((parseFloat(dailyUsage.summary.totalUsageGB) * 2) / dailyUsage.summary.daysWithData).toFixed(2) 
                              : '0.00'} GB
                          </div>
                          <div className="text-xs text-green-600">
                            Over {dailyUsage.summary.daysWithData} active days
                          </div>
                        </div>
                      </div>
                    </div>

                    {/* Daily Breakdown */}
                    <div>
                      <h4 className="font-semibold text-gray-900 mb-3 flex items-center">
                        <TrendingUp className="w-4 h-4 mr-2 text-purple-600" />
                        Daily Breakdown
                      </h4>
                      <div className="max-h-64 overflow-y-auto border rounded-lg">
                        <div className="grid gap-2 p-4">
                          {dailyUsage.dailyUsage.slice().reverse().map((day) => (
                            <div 
                              key={day.day} 
                              className={`flex items-center justify-between p-3 rounded-lg border ${
                                day.day === dailyUsage.currentDay 
                                  ? 'bg-purple-50 border-purple-200' 
                                  : day.usageBytes > 0 
                                    ? 'bg-gray-50 border-gray-200' 
                                    : 'bg-red-50 border-red-200'
                              }`}
                            >
                              <div className="flex items-center space-x-3">
                                <div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold ${
                                  day.day === dailyUsage.currentDay 
                                    ? 'bg-purple-600 text-white' 
                                    : day.usageBytes > 0 
                                      ? 'bg-gray-600 text-white' 
                                      : 'bg-red-600 text-white'
                                }`}>
                                  {day.day}
                                </div>
                                <div>
                                  <div className="font-medium text-gray-900">
                                    {new Date(day.date).toLocaleDateString('en-US', { 
                                      weekday: 'short', 
                                      month: 'short', 
                                      day: 'numeric' 
                                    })}
                                    {day.day === dailyUsage.currentDay && (
                                      <Badge className="ml-2 bg-purple-600 text-white text-xs">Today</Badge>
                                    )}
                                  </div>
                                  <div className="text-xs text-gray-500">
                                    {day.success 
                                      ? `${day.entries} session${day.entries !== 1 ? 's' : ''}` 
                                      : day.error || 'Error loading data'
                                    }
                                  </div>
                                </div>
                              </div>
                              <div className="text-right">
                                <div className={`font-bold ${
                                  day.usageBytes > 0 ? 'text-gray-900' : 'text-gray-400'
                                }`}>
                                  {day.usageBytes > 0 ? (parseFloat(day.usageGB) * 2).toFixed(3) : '0.000'} GB
                                </div>
                                <div className="text-xs text-gray-500">
                                  {day.usageBytes > 0 
                                    ? `${((day.usageBytes * 2) / (1024 * 1024)).toFixed(0)} MB` 
                                    : 'No usage'
                                  }
                                </div>
                              </div>
                            </div>
                          ))}
                        </div>
                      </div>
                    </div>

                    {dailyUsage.summary.errorCount > 0 && (
                      <div className="bg-red-50 border border-red-200 rounded-lg p-4">
                        <div className="flex items-center space-x-2">
                          <AlertTriangle className="w-4 h-4 text-red-600" />
                          <span className="text-sm font-medium text-red-800">
                            {dailyUsage.summary.errorCount} day{dailyUsage.summary.errorCount !== 1 ? 's' : ''} failed to load
                          </span>
                        </div>
                        <div className="text-xs text-red-600 mt-1">
                          Some daily usage data could not be retrieved from the API
                        </div>
                      </div>
                    )}
                  </div>
                ) : (
                  <div className="text-center py-8 text-gray-500">
                    No daily usage data available for this account
                  </div>
                )}
              </CardContent>
            </Card>
          )}

          {/* Sync Debug Information */}
          {syncDebugInfo && (
            <Card>
              <CardHeader>
                <CardTitle className="text-lg flex items-center space-x-2">
                  <FileText className="w-5 h-5 text-blue-600" />
                  <span>Sync Debug Information</span>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {/* Summary */}
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                    <div className="bg-blue-50 rounded-lg p-3 border border-blue-200">
                      <div className="text-center">
                        <div className="text-lg font-bold text-blue-800">
                          {syncDebugInfo.summary.totalDaysProcessed}
                        </div>
                        <div className="text-xs text-blue-600">Days Processed</div>
                      </div>
                    </div>
                    <div className="bg-green-50 rounded-lg p-3 border border-green-200">
                      <div className="text-center">
                        <div className="text-lg font-bold text-green-800">
                          {syncDebugInfo.summary.successfulDays}
                        </div>
                        <div className="text-xs text-green-600">Successful</div>
                      </div>
                    </div>
                    <div className="bg-red-50 rounded-lg p-3 border border-red-200">
                      <div className="text-center">
                        <div className="text-lg font-bold text-red-800">
                          {syncDebugInfo.summary.failedDays}
                        </div>
                        <div className="text-xs text-red-600">Failed</div>
                      </div>
                    </div>
                    <div className="bg-purple-50 rounded-lg p-3 border border-purple-200">
                      <div className="text-center">
                        <div className="text-lg font-bold text-purple-800">
                          {(syncDebugInfo.summary.totalBytesProcessed / (1024 * 1024 * 1024)).toFixed(2)}
                        </div>
                        <div className="text-xs text-purple-600">GB Processed</div>
                      </div>
                    </div>
                  </div>

                  {/* API Call Details */}
                  <div>
                    <h4 className="font-semibold text-gray-900 mb-3">API Call Details</h4>
                    <div className="max-h-96 overflow-y-auto border rounded-lg bg-gray-50">
                      <div className="p-4 space-y-4">
                        {syncDebugInfo.apiCalls.map((call, index) => (
                          <div key={index} className="bg-white rounded-lg p-4 border border-gray-200">
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                              <div>
                                <h5 className="font-medium text-gray-900 mb-2">Day {call.day} - Request</h5>
                                <div className="text-sm space-y-1">
                                  <div><strong>URL:</strong> <code className="text-xs bg-gray-100 p-1 rounded">{call.url}</code></div>
                                  <div><strong>Original Account:</strong> {call.originalAccount}</div>
                                  <div><strong>Cleaned Account:</strong> {call.cleanedAccount}</div>
                                  <div><strong>Encoded Account:</strong> {call.encodedAccount}</div>
                                  <div><strong>Request Time:</strong> {new Date(call.requestTime).toLocaleString()}</div>
                                </div>
                              </div>
                              <div>
                                <h5 className="font-medium text-gray-900 mb-2">Response</h5>
                                <div className="text-sm space-y-1">
                                  <div><strong>Status:</strong> 
                                    <span className={`ml-2 px-2 py-1 rounded text-xs font-medium ${
                                      call.success ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                                    }`}>
                                      {call.response?.status || 'N/A'}
                                    </span>
                                  </div>
                                  {call.success && call.response?.processedBytes && (
                                    <>
                                      <div><strong>Processed:</strong> {call.response.processedGB} GB</div>
                                      <div><strong>Entries:</strong> {call.response.entriesCount}</div>
                                    </>
                                  )}
                                  {call.error && (
                                    <div><strong>Error:</strong> <span className="text-red-600">{call.error}</span></div>
                                  )}
                                </div>
                              </div>
                            </div>
                            
                            {/* Show raw response for debugging */}
                            {call.response?.rawText && (
                              <div className="mt-4 pt-4 border-t border-gray-200">
                                <h6 className="font-medium text-gray-900 mb-2">Raw API Response</h6>
                                <pre className="text-xs bg-gray-100 p-2 rounded overflow-x-auto max-h-32">
                                  {JSON.stringify(JSON.parse(call.response.rawText), null, 2)}
                                </pre>
                              </div>
                            )}
                          </div>
                        ))}
                      </div>
                    </div>
                  </div>

                  {/* Errors */}
                  {syncDebugInfo.errors.length > 0 && (
                    <div>
                      <h4 className="font-semibold text-gray-900 mb-3">Errors</h4>
                      <div className="bg-red-50 border border-red-200 rounded-lg p-4">
                        <div className="space-y-2">
                          {syncDebugInfo.errors.map((error, index) => (
                            <div key={index} className="text-sm text-red-800">
                              • {error}
                            </div>
                          ))}
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          )}

          {/* Timestamps */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg flex items-center space-x-2">
                <Calendar className="w-5 h-5 text-gray-600" />
                <span>Timestamps</span>
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-1">
                <InfoRow 
                  icon={Calendar} 
                  label="Created" 
                  value={client.createdAt ? new Date(client.createdAt).toLocaleString() : null} 
                />
                <InfoRow 
                  icon={Calendar} 
                  label="Last Updated" 
                  value={client.updatedAt ? new Date(client.updatedAt).toLocaleString() : null} 
                />
              </div>
            </CardContent>
          </Card>
        </div>
      </DialogContent>
    </Dialog>
  );
}