import { useState } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent } from "@/components/ui/card";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Progress } from "@/components/ui/progress";
import { Plus, Search, ChevronLeft, ChevronRight, Edit, Trash2, Radio, Eye, TrendingUp, RefreshCw, Database, Loader2, AlertTriangle, TestTube, Calendar } from "lucide-react";
import SimEditModal from "@/components/sim-edit-modal";
import ClientEditModal from "@/components/client-edit-modal";
import ClientViewModal from "@/components/client-view-modal";
import Top15Modal from "@/components/top15-modal";
import RoleGuard from "@/components/role-guard";
import { useToast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
import { queryClient } from "@/lib/queryClient";
import type { Client } from "@shared/schema";

export default function MTNMobile() {
  const { toast } = useToast();
  const [searchTerm, setSearchTerm] = useState("");
  const [editingSim, setEditingSim] = useState<Client | null>(null);
  const [viewingClient, setViewingClient] = useState<Client | null>(null);
  const [isSimEditModalOpen, setIsSimEditModalOpen] = useState(false);
  const [isViewModalOpen, setIsViewModalOpen] = useState(false);
  const [isAddClientModalOpen, setIsAddClientModalOpen] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [clientToDelete, setClientToDelete] = useState<Client | null>(null);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [isTop15ModalOpen, setIsTop15ModalOpen] = useState(false);
  const [isBottom30ModalOpen, setIsBottom30ModalOpen] = useState(false);
  const [isDailyUsageSyncModalOpen, setIsDailyUsageSyncModalOpen] = useState(false);
  const [syncInProgress, setSyncInProgress] = useState(false);
  const [syncProgress, setSyncProgress] = useState<any>(null);
  const [syncSessionId, setSyncSessionId] = useState<string | null>(null);
  const [isTestModalOpen, setIsTestModalOpen] = useState(false);
  const [testResult, setTestResult] = useState<any>(null);
  const [testLoading, setTestLoading] = useState(false);
  const clientsPerPage = 20;

  const { data: clientsData, isLoading } = useQuery({
    queryKey: ["/api/clients", "MTN Mobile (GSM)", currentPage],
    queryFn: async () => {
      const offset = (currentPage - 1) * clientsPerPage;
      const params = new URLSearchParams({
        category: "MTN Mobile (GSM)",
        limit: clientsPerPage.toString(),
        offset: offset.toString(),
      });
      
      const response = await fetch(`/api/clients?${params}`, {
        credentials: "include",
      });
      if (!response.ok) throw new Error("Failed to fetch MTN Mobile clients");
      return response.json();
    },
  });

  const clients = clientsData?.clients || [];
  const totalCount = clientsData?.total || 0;
  const totalPages = Math.ceil(totalCount / clientsPerPage);

  // Delete mutation
  const deleteMutation = useMutation({
    mutationFn: async (clientId: number) => {
      return apiRequest("DELETE", `/api/clients/${clientId}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/clients"] });
      queryClient.invalidateQueries({ queryKey: ["/api/stats"] });
      queryClient.invalidateQueries({ queryKey: ["/api/recently-viewed"] });
      toast({
        title: "Success",
        description: "MTN Mobile client deleted successfully",
      });
      setIsDeleteDialogOpen(false);
      setClientToDelete(null);
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.message || "Failed to delete client",
        variant: "destructive",
      });
    },
  });

  // Top 15 query
  const { data: top15Data, isLoading: isTop15Loading, refetch: refetchTop15 } = useQuery({
    queryKey: ["/api/admin/mtn-mobile-top15"],
    queryFn: async () => {
      const response = await fetch("/api/admin/mtn-mobile-top15", {
        credentials: "include",
      });
      if (!response.ok) {
        throw new Error("Failed to fetch top 15 data");
      }
      return response.json();
    },
    enabled: isTop15ModalOpen, // Load when modal is open
  });

  // Bottom 30 query  
  const { data: bottom30Data, isLoading: isBottom30Loading, refetch: refetchBottom30 } = useQuery({
    queryKey: ["/api/admin/mtn-mobile-bottom30"],
    queryFn: async () => {
      const response = await fetch("/api/admin/mtn-mobile-bottom30", {
        credentials: "include",
      });
      if (!response.ok) {
        throw new Error("Failed to fetch bottom 30 data");
      }
      return response.json();
    },
    enabled: isBottom30ModalOpen, // Load when modal is open
  });

  // Bulk sync mutation for current month
  const syncMutation = useMutation({
    mutationFn: async () => {
      return apiRequest("POST", "/api/admin/sync-mtn-mobile-stats");
    },
    onSuccess: (data: any) => {
      toast({
        title: "Sync Completed",
        description: `Successfully synced ${data.processed} MTN Mobile accounts for current month`,
      });
      // Refresh the top 15 query after sync
      queryClient.invalidateQueries({ queryKey: ["/api/admin/mtn-mobile-top15"] });
      // Also refetch if modal is open
      if (isTop15ModalOpen) {
        refetchTop15();
      }
    },
    onError: (error: any) => {
      toast({
        title: "Sync Failed",
        description: error.message || "Failed to sync MTN Mobile statistics",
        variant: "destructive",
      });
    },
  });

  // 3-Month sync mutation
  const sync3MonthsMutation = useMutation({
    mutationFn: async () => {
      return apiRequest("POST", "/api/admin/sync-mtn-mobile-3months");
    },
    onSuccess: (data: any) => {
      toast({
        title: "3-Month Sync Completed", 
        description: `Successfully synced ${data.processed} records across ${data.months} months for ${data.clients} clients`,
      });
      // Refresh queries after sync
      queryClient.invalidateQueries({ queryKey: ["/api/admin/mtn-mobile-top15"] });
      queryClient.invalidateQueries({ queryKey: ["/api/clients"] });
    },
    onError: (error: any) => {
      toast({
        title: "3-Month Sync Failed",
        description: error.message || "Failed to sync 3 months of MTN Mobile statistics",
        variant: "destructive",
      });
    },
  });

  const handleEditSim = (sim: Client) => {
    setEditingSim(sim);
    setIsSimEditModalOpen(true);
  };

  const handleViewClient = (client: Client) => {
    setViewingClient(client);
    setIsViewModalOpen(true);
  };

  const handleDeleteClient = (client: Client) => {
    setClientToDelete(client);
    setIsDeleteDialogOpen(true);
  };

  const confirmDelete = () => {
    if (clientToDelete) {
      deleteMutation.mutate(clientToDelete.id);
    }
  };

  const handleAddClient = () => {
    setIsAddClientModalOpen(true);
  };

  const handleCloseAddClientModal = () => {
    setIsAddClientModalOpen(false);
  };

  const getStatusColor = (status: string) => {
    switch (status.toLowerCase()) {
      case "active":
        return "bg-green-600 text-white border-0";
      case "suspended":
        return "bg-red-600 text-white border-0";
      case "cancelled":
        return "bg-gray-700 text-white border-0";
      case "debit order unpaid":
        return "bg-orange-600 text-white border-0";
      case "pending":
        return "bg-yellow-600 text-white border-0";
      default:
        return "bg-gray-600 text-white border-0";
    }
  };

  // Top 15 handlers
  const handleSyncAndShowTop15 = async () => {
    try {
      await syncMutation.mutateAsync();
      // After sync, refetch top 15 data and show modal
      queryClient.invalidateQueries({ queryKey: ["/api/admin/mtn-mobile-top15"] });
      setIsTop15ModalOpen(true);
    } catch (error) {
      // Error is already handled by the mutation
    }
  }

  const handleShowBottom30 = () => {
    setIsBottom30ModalOpen(true);
  };

  const handleShowTop15 = () => {
    queryClient.invalidateQueries({ queryKey: ["/api/admin/mtn-mobile-top15"] });
    setIsTop15ModalOpen(true);
  };

  // Start batch sync for all MTN Mobile accounts
  const startBatchDailyUsageSync = async () => {
    setSyncInProgress(true);
    setSyncProgress(null);
    setIsDailyUsageSyncModalOpen(true);
    
    try {
      const response = await fetch('/api/mtn-mobile-daily-usage/sync', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
      });
      
      if (response.ok) {
        const result = await response.json();
        if (result.ok) {
          setSyncSessionId(result.sessionId);
          toast({
            title: "Sync Started",
            description: `Batch daily usage sync started for ${result.totalAccounts} accounts`,
          });
          
          // Start polling for progress
          pollSyncProgress(result.sessionId);
        } else {
          throw new Error(result.error || "Failed to start sync");
        }
      } else {
        throw new Error("Failed to start sync");
      }
    } catch (error) {
      console.error("Error starting sync:", error);
      toast({
        title: "Error",
        description: error instanceof Error ? error.message : "Failed to start batch sync",
        variant: "destructive",
      });
      setSyncInProgress(false);
      setIsDailyUsageSyncModalOpen(false);
    }
  };

  // Poll sync progress
  const pollSyncProgress = async (sessionId: string) => {
    try {
      const response = await fetch(`/api/mtn-mobile-daily-usage/sync/${sessionId}`, {
        credentials: 'include',
      });
      if (response.ok) {
        const result = await response.json();
        if (result.ok) {
          setSyncProgress(result.data);
          
          if (result.data.isCompleted || result.data.isCancelled) {
            setSyncInProgress(false);
            setSyncSessionId(null);
            
            if (result.data.isCancelled) {
              toast({
                title: "Sync Cancelled",
                description: "The daily usage sync was cancelled by user request",
                variant: "destructive",
              });
            } else {
              toast({
                title: "Sync Completed",
                description: `Successfully processed ${result.data.processedAccounts} accounts and ${result.data.processedDays} days`,
              });
            }
            
            // Auto-close modal after a short delay
            setTimeout(() => {
              setIsDailyUsageSyncModalOpen(false);
            }, 3000);
          } else {
            // Continue polling every 2 seconds
            setTimeout(() => pollSyncProgress(sessionId), 2000);
          }
        }
      }
    } catch (error) {
      console.error("Error polling sync progress:", error);
      // Continue polling even if there's an error
      setTimeout(() => pollSyncProgress(sessionId), 5000);
    }
  };

  // Stop sync
  const stopSync = async () => {
    if (!syncSessionId) return;
    
    try {
      const response = await fetch(`/api/mtn-mobile-daily-usage/sync/${syncSessionId}/stop`, {
        method: 'POST',
        credentials: 'include',
      });
      
      if (response.ok) {
        const result = await response.json();
        if (result.ok) {
          toast({
            title: "Stop Requested",
            description: "Sync cancellation has been requested. Please wait for it to stop safely...",
          });
        }
      }
    } catch (error) {
      console.error("Error stopping sync:", error);
      toast({
        title: "Error",
        description: "Failed to stop sync",
        variant: "destructive",
      });
    }
  };

  // Test Daily Usage API with specific account
  const testDailyUsageAPI = async () => {
    const testAccount = "27634038516@mobile.is.co.za";
    setTestLoading(true);
    setIsTestModalOpen(true);
    
    const requestDetails = {
      method: "GET",
      url: `/api/mtn-mobile-daily-usage/${encodeURIComponent(testAccount)}`,
      encodedUrl: `/api/mtn-mobile-daily-usage/${encodeURIComponent(testAccount)}`,
      testAccount: testAccount,
      timestamp: new Date().toISOString(),
      userAgent: navigator.userAgent,
    };
    
    try {
      console.log("Testing Daily Usage API with account:", testAccount);
      console.log("Request details:", requestDetails);
      
      const startTime = Date.now();
      const response = await fetch(requestDetails.url, {
        method: 'GET',
        credentials: 'include',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        }
      });
      const endTime = Date.now();
      
      const responseText = await response.text();
      let responseData;
      try {
        responseData = JSON.parse(responseText);
      } catch (e) {
        responseData = { error: "Failed to parse JSON", rawResponse: responseText };
      }
      
      const fullResult = {
        request: requestDetails,
        response: {
          status: response.status,
          statusText: response.statusText,
          headers: Object.fromEntries(response.headers.entries()),
          ok: response.ok,
          data: responseData,
          rawResponse: responseText,
          responseTime: endTime - startTime,
          timestamp: new Date().toISOString(),
        },
        success: response.ok,
        totalTime: endTime - startTime,
      };
      
      console.log("API Test Result:", fullResult);
      setTestResult(fullResult);
      
      toast({
        title: response.ok ? "API Test Successful" : "API Test Failed",
        description: `Status: ${response.status} - Response time: ${endTime - startTime}ms`,
        variant: response.ok ? "default" : "destructive",
      });
      
    } catch (error) {
      console.error("API Test Error:", error);
      const errorObj = error instanceof Error ? error : new Error("Unknown error");
      const errorResult = {
        request: requestDetails,
        response: null,
        error: {
          message: errorObj.message,
          name: errorObj.name,
          stack: errorObj.stack,
          timestamp: new Date().toISOString(),
        },
        success: false,
        totalTime: 0,
      };
      
      setTestResult(errorResult);
      
      toast({
        title: "API Test Error",
        description: errorObj.message || "Unknown error occurred",
        variant: "destructive",
      });
    }
    
    setTestLoading(false);
  };

  const filteredClients = clients.filter((client: Client) =>
    client.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    client.email?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    client.accountNumber?.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <>
      {/* Top Bar */}
      <div className="bg-white shadow-sm border-b border-gray-200 p-4 lg:p-6">
        <div className="flex flex-col lg:flex-row lg:items-center gap-4">
          {/* Header Section */}
          <div className="flex items-center space-x-4 flex-shrink-0">
            <div className="w-12 h-12 bg-orange-500 rounded-lg flex items-center justify-center">
              <Radio className="text-white" size={24} />
            </div>
            <div>
              <h1 className="text-xl lg:text-2xl font-bold text-gray-900">MTN Mobile (GSM)</h1>
              <p className="text-sm lg:text-base text-gray-600">Manage MTN Mobile client SIMs</p>
            </div>
          </div>
          
          {/* Search and Actions Section */}
          <div className="flex flex-col sm:flex-row lg:flex-row items-stretch sm:items-center gap-3 lg:ml-auto">
            {/* Search Input */}
            <div className="relative order-1 sm:order-1">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
              <Input
                placeholder="Search clients..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10 w-full sm:w-64 lg:w-80"
              />
            </div>
            
            {/* Action Buttons Container */}
            <div className="flex flex-wrap items-center gap-2 order-2 sm:order-2">
              <RoleGuard requiredRole="admin">
                <Button 
                  variant="outline"
                  size="sm"
                  onClick={testDailyUsageAPI}
                  disabled={testLoading}
                  className="border-blue-200 text-blue-700 hover:bg-blue-50 text-xs lg:text-sm"
                >
                  <TestTube className={`w-3 h-3 lg:w-4 lg:h-4 mr-1 lg:mr-2 ${testLoading ? 'animate-bounce' : ''}`} />
                  <span className="hidden sm:inline">{testLoading ? 'Testing...' : 'Test API'}</span>
                  <span className="sm:hidden">Test</span>
                </Button>
              </RoleGuard>
              
              <RoleGuard requiredRole="admin">
                <Button 
                  variant="outline"
                  size="sm"
                  onClick={() => setIsTop15ModalOpen(true)}
                  className="border-amber-200 text-amber-700 hover:bg-amber-50 text-xs lg:text-sm"
                >
                  <TrendingUp className="w-3 h-3 lg:w-4 lg:h-4 mr-1 lg:mr-2" />
                  <span className="hidden sm:inline">Top 15 Users</span>
                  <span className="sm:hidden">Top 15</span>
                </Button>
              </RoleGuard>

              <RoleGuard requiredRole="admin">
                <Button 
                  variant="outline"
                  size="sm"
                  onClick={handleShowBottom30}
                  className="border-red-200 text-red-700 hover:bg-red-50 text-xs lg:text-sm"
                >
                  <TrendingUp className="w-3 h-3 lg:w-4 lg:h-4 mr-1 lg:mr-2 rotate-180" />
                  <span className="hidden sm:inline">Bottom 30 Users</span>
                  <span className="sm:hidden">Bottom 30</span>
                </Button>
              </RoleGuard>
              
              <RoleGuard requiredRole="admin">
                <Button 
                  variant="outline"
                  size="sm"
                  onClick={handleSyncAndShowTop15}
                  disabled={syncMutation.isPending}
                  className="border-green-200 text-green-700 hover:bg-green-50 text-xs lg:text-sm"
                >
                  <RefreshCw className={`w-3 h-3 lg:w-4 lg:h-4 mr-1 lg:mr-2 ${syncMutation.isPending ? 'animate-spin' : ''}`} />
                  <span className="hidden lg:inline">{syncMutation.isPending ? 'Syncing...' : 'Sync & Top 15'}</span>
                  <span className="lg:hidden">{syncMutation.isPending ? 'Sync...' : 'Sync'}</span>
                </Button>
              </RoleGuard>
              
              <RoleGuard requiredRole="admin">
                <Button 
                  variant="outline"
                  size="sm"
                  onClick={() => sync3MonthsMutation.mutate()}
                  disabled={sync3MonthsMutation.isPending}
                  className="border-blue-200 text-blue-700 hover:bg-blue-50 text-xs lg:text-sm"
                >
                  <Calendar className={`w-3 h-3 lg:w-4 lg:h-4 mr-1 lg:mr-2 ${sync3MonthsMutation.isPending ? 'animate-spin' : ''}`} />
                  <span className="hidden lg:inline">{sync3MonthsMutation.isPending ? 'Syncing 3 Months...' : 'Sync 3 Months'}</span>
                  <span className="lg:hidden">{sync3MonthsMutation.isPending ? '3M...' : '3M'}</span>
                </Button>
              </RoleGuard>
              
              <RoleGuard requiredRole="admin">
                <Button 
                  variant="outline"
                  size="sm"
                  onClick={startBatchDailyUsageSync}
                  disabled={syncInProgress}
                  className="border-purple-200 text-purple-700 hover:bg-purple-50 text-xs lg:text-sm"
                >
                  <Database className={`w-3 h-3 lg:w-4 lg:h-4 mr-1 lg:mr-2 ${syncInProgress ? 'animate-pulse' : ''}`} />
                  <span className="hidden lg:inline">{syncInProgress ? 'Syncing Daily Usage...' : 'Sync Daily Usage'}</span>
                  <span className="lg:hidden">{syncInProgress ? 'Daily...' : 'Daily'}</span>
                </Button>
              </RoleGuard>

              <RoleGuard requiredRole="admin">
                <Button 
                  size="sm"
                  onClick={handleAddClient}
                  className="text-xs lg:text-sm"
                >
                  <Plus className="w-3 h-3 lg:w-4 lg:h-4 mr-1 lg:mr-2" />
                  <span className="hidden sm:inline">Add Client</span>
                  <span className="sm:hidden">Add</span>
                </Button>
              </RoleGuard>
            </div>
          </div>
        </div>
      </div>

      {/* Content Area */}
      <div className="flex-1 overflow-auto p-6">
        {isLoading ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
            {[1, 2, 3, 4, 5, 6, 7, 8].map((i) => (
              <div key={i} className="bg-white rounded-xl shadow-sm border border-gray-200 p-4 animate-pulse">
                <div className="h-32 bg-gray-200 rounded"></div>
              </div>
            ))}
          </div>
        ) : filteredClients && filteredClients.length > 0 ? (
          <>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
              {filteredClients.map((client: Client) => (
                <Card key={client.id} className={`shadow-sm border hover:shadow-md transition-shadow ${client.isReseller ? 'bg-blue-50 border-blue-300 ring-2 ring-blue-200' : 'border-gray-200'}`}>
                  <CardContent className="p-4">
                    <div className="flex items-center justify-between mb-3">
                      <div className="flex items-center space-x-2">
                        <Radio className={`${client.isReseller ? 'text-blue-600' : 'text-orange-500'}`} size={16} />
                        <Badge className="bg-orange-100 text-orange-800 hover:bg-orange-100">
                          MTN Mobile
                        </Badge>
                        {client.isReseller && (
                          <Badge className="bg-blue-600 text-white text-xs px-2 py-1 hover:bg-blue-600">
                            Reseller
                          </Badge>
                        )}
                      </div>
                      <div className="flex items-center space-x-1">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleViewClient(client)}
                          className="h-8 w-8 p-0 text-green-600 hover:text-green-700"
                        >
                          <Eye className="h-4 w-4" />
                        </Button>
                        <RoleGuard requiredRole="admin">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleEditSim(client)}
                            className="h-8 w-8 p-0"
                          >
                            <Edit className="h-4 w-4" />
                          </Button>
                        </RoleGuard>
                        <RoleGuard requiredRole="admin">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleDeleteClient(client)}
                            className="h-8 w-8 p-0 text-red-500 hover:text-red-700"
                            disabled={deleteMutation.isPending}
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </RoleGuard>
                      </div>
                    </div>

                    <div className="space-y-2">
                      <div>
                        <h4 className="font-semibold text-gray-900 mb-1">{client.name}</h4>
                        <p className="text-sm text-gray-600">{client.email || 'No email'}</p>
                      </div>

                      <div className="space-y-1">
                        <div className="flex justify-between">
                          <span className="text-xs text-gray-500">Account:</span>
                          <span className="text-xs font-medium">{client.accountNumber || 'N/A'}</span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-xs text-gray-500">Status:</span>
                          <Badge className={`${getStatusColor(client.status || '')} text-xs`}>
                            {client.status || 'Unknown'}
                          </Badge>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-xs text-gray-500">Status 2:</span>
                          <Badge className={`${getStatusColor(client.status2 || '')} text-xs`}>
                            {client.status2 || 'N/A'}
                          </Badge>
                        </div>
                      </div>

                      {client.serviceDetails && (
                        <div className="mt-2 p-2 bg-gray-50 rounded text-xs text-gray-600 line-clamp-3">
                          {client.serviceDetails}
                        </div>
                      )}
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>

            {/* Pagination Controls */}
            <div className="mt-6 flex items-center justify-between">
              <div className="text-sm text-gray-700">
                Page {currentPage} - {filteredClients.length} clients shown
              </div>
              <div className="flex items-center space-x-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
                  disabled={currentPage === 1}
                >
                  <ChevronLeft className="h-4 w-4" />
                  Previous
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setCurrentPage(prev => prev + 1)}
                  disabled={!clients || clients.length < clientsPerPage}
                >
                  Next
                  <ChevronRight className="h-4 w-4" />
                </Button>
              </div>
            </div>
          </>
        ) : (
          <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-12 text-center">
            <Radio className="mx-auto h-12 w-12 text-gray-400 mb-4" />
            <p className="text-gray-500">
              {searchTerm ? "No MTN Mobile clients found matching your search" : "No MTN Mobile clients found"}
            </p>
          </div>
        )}
      </div>

      <SimEditModal
        sim={editingSim}
        simType="primary"
        isOpen={isSimEditModalOpen}
        onClose={() => setIsSimEditModalOpen(false)}
      />
      
      <ClientEditModal
        client={null}
        isOpen={isAddClientModalOpen}
        onClose={handleCloseAddClientModal}
        defaultCategory="MTN Mobile (GSM)"
      />

      <ClientViewModal
        client={viewingClient}
        isOpen={isViewModalOpen}
        onClose={() => setIsViewModalOpen(false)}
      />

      <Top15Modal
        isOpen={isTop15ModalOpen}
        onClose={() => setIsTop15ModalOpen(false)}
        data={top15Data}
        isLoading={isTop15Loading}
      />

      {/* Daily Usage Sync Progress Modal */}
      <Dialog open={isDailyUsageSyncModalOpen} onOpenChange={setIsDailyUsageSyncModalOpen}>
        <DialogContent className="sm:max-w-[600px]">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Database className="h-5 w-5 text-purple-600" />
              Daily Usage Sync Progress
            </DialogTitle>
            <DialogDescription>
              Syncing daily usage data for all MTN Mobile accounts
            </DialogDescription>
          </DialogHeader>
          
          <div className="space-y-6">
            {syncProgress && (
              <>
                {/* Current Status */}
                <div className="flex items-center gap-3 p-4 bg-blue-50 dark:bg-blue-950/20 rounded-lg border border-blue-200 dark:border-blue-800">
                  <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 Statistics */}
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                  <div className="text-center p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                    <div className="text-lg font-semibold text-gray-900 dark:text-gray-100">
                      {syncProgress.processedAccounts}
                    </div>
                    <div className="text-xs text-gray-600 dark:text-gray-400">Accounts Processed</div>
                  </div>
                  <div className="text-center p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                    <div className="text-lg font-semibold text-gray-900 dark:text-gray-100">
                      {syncProgress.totalAccounts}
                    </div>
                    <div className="text-xs text-gray-600 dark:text-gray-400">Total Accounts</div>
                  </div>
                  <div className="text-center p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                    <div className="text-lg font-semibold text-gray-900 dark:text-gray-100">
                      {syncProgress.processedDays}
                    </div>
                    <div className="text-xs text-gray-600 dark:text-gray-400">Days Processed</div>
                  </div>
                  <div className="text-center p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                    <div className="text-lg font-semibold text-gray-900 dark:text-gray-100">
                      {syncProgress.totalDays || 0}
                    </div>
                    <div className="text-xs text-gray-600 dark:text-gray-400">Total Days</div>
                  </div>
                </div>

                {/* Progress Bars */}
                <div className="space-y-4">
                  {/* Accounts Progress */}
                  <div>
                    <div className="flex justify-between text-sm text-gray-600 dark:text-gray-400 mb-2">
                      <span>Accounts Progress</span>
                      <span>{syncProgress.processedAccounts}/{syncProgress.totalAccounts}</span>
                    </div>
                    <Progress 
                      value={syncProgress.totalAccounts > 0 ? (syncProgress.processedAccounts / syncProgress.totalAccounts) * 100 : 0}
                      className="h-3"
                    />
                  </div>
                  
                  {/* Days Progress */}
                  {syncProgress.totalDays > 0 && (
                    <div>
                      <div className="flex justify-between text-sm text-gray-600 dark:text-gray-400 mb-2">
                        <span>Days Progress</span>
                        <span>{syncProgress.processedDays}/{syncProgress.totalDays}</span>
                      </div>
                      <Progress 
                        value={(syncProgress.processedDays / syncProgress.totalDays) * 100}
                        className="h-3"
                      />
                    </div>
                  )}
                </div>

                {/* Errors Section */}
                {syncProgress.errors && syncProgress.errors.length > 0 && (
                  <div className="p-4 bg-red-50 dark:bg-red-950/20 rounded-lg border border-red-200 dark:border-red-800">
                    <div className="flex items-center gap-2 text-sm text-red-800 dark:text-red-300 mb-2">
                      <AlertTriangle className="h-4 w-4" />
                      <span className="font-medium">{syncProgress.errors.length} error(s) occurred</span>
                    </div>
                    <div className="max-h-32 overflow-y-auto">
                      {syncProgress.errors.slice(0, 5).map((error: string, index: number) => (
                        <div key={index} className="text-xs text-red-700 dark:text-red-400 mb-1">
                          • {error}
                        </div>
                      ))}
                      {syncProgress.errors.length > 5 && (
                        <div className="text-xs text-red-600 dark:text-red-500 italic">
                          ...and {syncProgress.errors.length - 5} more errors
                        </div>
                      )}
                    </div>
                  </div>
                )}

                {/* Completion Status */}
                {(syncProgress.isCompleted || syncProgress.isCancelled) && (
                  <div className={`p-4 rounded-lg border ${
                    syncProgress.isCancelled 
                      ? 'bg-orange-50 dark:bg-orange-950/20 border-orange-200 dark:border-orange-800' 
                      : 'bg-green-50 dark:bg-green-950/20 border-green-200 dark:border-green-800'
                  }`}>
                    <div className={`flex items-center gap-2 text-sm ${
                      syncProgress.isCancelled 
                        ? 'text-orange-800 dark:text-orange-300' 
                        : 'text-green-800 dark:text-green-300'
                    }`}>
                      <Database className="h-4 w-4" />
                      <span className="font-medium">
                        {syncProgress.isCancelled ? 'Sync was cancelled' : 'Sync completed successfully!'}
                      </span>
                    </div>
                    <div className={`text-xs mt-1 ${
                      syncProgress.isCancelled 
                        ? 'text-orange-700 dark:text-orange-400' 
                        : 'text-green-700 dark:text-green-400'
                    }`}>
                      This modal will close automatically in a few seconds.
                    </div>
                  </div>
                )}

                {/* Action Buttons */}
                {syncProgress && !syncProgress.isCompleted && !syncProgress.isCancelled && (
                  <div className="flex justify-end gap-3 pt-4 border-t border-gray-200 dark:border-gray-700">
                    <Button
                      variant="outline"
                      onClick={stopSync}
                      className="border-red-200 text-red-700 hover:bg-red-50 dark:border-red-800 dark:text-red-300 dark:hover:bg-red-950/20"
                      disabled={!syncSessionId}
                    >
                      <AlertTriangle className="w-4 h-4 mr-2" />
                      Stop Sync
                    </Button>
                  </div>
                )}
              </>
            )}

            {/* Initial Loading State */}
            {!syncProgress && syncInProgress && (
              <div className="flex items-center justify-center p-8">
                <Loader2 className="h-8 w-8 animate-spin text-purple-600" />
                <span className="ml-3 text-purple-600">Initializing batch sync...</span>
              </div>
            )}
          </div>
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation Dialog */}
      <AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete MTN Mobile Client</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to permanently delete the client "{clientToDelete?.name}"? 
              This action will completely remove all data associated with this account, including:
              <br /><br />
              • Client information and contact details
              <br />
              • All SIM swap history and records
              <br />
              • Recently viewed tracking data
              <br /><br />
              <strong>This action cannot be undone.</strong>
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel 
              onClick={() => {
                setIsDeleteDialogOpen(false);
                setClientToDelete(null);
              }}
            >
              Cancel
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={confirmDelete}
              disabled={deleteMutation.isPending}
              className="bg-red-600 hover:bg-red-700 text-white"
            >
              {deleteMutation.isPending ? "Deleting..." : "Delete Client"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* API Test Results Modal */}
      <Dialog open={isTestModalOpen} onOpenChange={setIsTestModalOpen}>
        <DialogContent className="sm:max-w-[900px] max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <TestTube className="h-5 w-5 text-blue-600" />
              Daily Usage API Test Results
            </DialogTitle>
            <DialogDescription>
              Detailed request and response information for API testing
            </DialogDescription>
          </DialogHeader>
          
          <div className="space-y-6">
            {testResult && (
              <>
                {/* Test Summary */}
                <div className={`p-4 rounded-lg border ${
                  testResult.success 
                    ? 'bg-green-50 dark:bg-green-950/20 border-green-200 dark:border-green-800' 
                    : 'bg-red-50 dark:bg-red-950/20 border-red-200 dark:border-red-800'
                }`}>
                  <div className={`flex items-center gap-2 text-sm font-medium ${
                    testResult.success 
                      ? 'text-green-800 dark:text-green-300' 
                      : 'text-red-800 dark:text-red-300'
                  }`}>
                    <div className={`w-2 h-2 rounded-full ${
                      testResult.success ? 'bg-green-600' : 'bg-red-600'
                    }`}></div>
                    <span>
                      {testResult.success ? 'Test Successful' : 'Test Failed'}
                      {testResult.response && ` - ${testResult.response.status} ${testResult.response.statusText}`}
                      {testResult.totalTime > 0 && ` - ${testResult.totalTime}ms`}
                    </span>
                  </div>
                </div>

                {/* Request Details */}
                <div className="space-y-3">
                  <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">Request Details</h3>
                  <div className="bg-gray-50 dark:bg-gray-800 rounded-lg p-4">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                      <div>
                        <span className="font-medium text-gray-700 dark:text-gray-300">Method:</span>
                        <span className="ml-2 font-mono bg-gray-200 dark:bg-gray-700 px-2 py-1 rounded">
                          {testResult.request.method}
                        </span>
                      </div>
                      <div>
                        <span className="font-medium text-gray-700 dark:text-gray-300">Test Account:</span>
                        <span className="ml-2 font-mono bg-gray-200 dark:bg-gray-700 px-2 py-1 rounded">
                          {testResult.request.testAccount}
                        </span>
                      </div>
                      <div className="md:col-span-2">
                        <span className="font-medium text-gray-700 dark:text-gray-300">URL:</span>
                        <div className="mt-1 p-2 bg-gray-200 dark:bg-gray-700 rounded font-mono text-xs break-all">
                          {testResult.request.url}
                        </div>
                      </div>
                      <div className="md:col-span-2">
                        <span className="font-medium text-gray-700 dark:text-gray-300">Encoded URL:</span>
                        <div className="mt-1 p-2 bg-gray-200 dark:bg-gray-700 rounded font-mono text-xs break-all">
                          {testResult.request.encodedUrl}
                        </div>
                      </div>
                      <div>
                        <span className="font-medium text-gray-700 dark:text-gray-300">Timestamp:</span>
                        <div className="mt-1 font-mono text-xs">
                          {testResult.request.timestamp}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Response Details */}
                {testResult.response && (
                  <div className="space-y-3">
                    <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">Response Details</h3>
                    <div className="bg-gray-50 dark:bg-gray-800 rounded-lg p-4">
                      <div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm mb-4">
                        <div>
                          <span className="font-medium text-gray-700 dark:text-gray-300">Status:</span>
                          <span className={`ml-2 px-2 py-1 rounded text-xs font-mono ${
                            testResult.response.ok 
                              ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200' 
                              : 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200'
                          }`}>
                            {testResult.response.status}
                          </span>
                        </div>
                        <div>
                          <span className="font-medium text-gray-700 dark:text-gray-300">Status Text:</span>
                          <span className="ml-2 font-mono">
                            {testResult.response.statusText}
                          </span>
                        </div>
                        <div>
                          <span className="font-medium text-gray-700 dark:text-gray-300">Response Time:</span>
                          <span className="ml-2 font-mono">
                            {testResult.response.responseTime}ms
                          </span>
                        </div>
                      </div>
                      
                      {/* Response Headers */}
                      <div className="mb-4">
                        <span className="font-medium text-gray-700 dark:text-gray-300">Headers:</span>
                        <div className="mt-1 p-2 bg-gray-200 dark:bg-gray-700 rounded">
                          <pre className="text-xs overflow-x-auto">
                            {JSON.stringify(testResult.response.headers, null, 2)}
                          </pre>
                        </div>
                      </div>

                      {/* Response Data */}
                      <div>
                        <span className="font-medium text-gray-700 dark:text-gray-300">Response Data:</span>
                        <div className="mt-1 p-2 bg-gray-200 dark:bg-gray-700 rounded">
                          <pre className="text-xs overflow-x-auto max-h-64 overflow-y-auto">
                            {JSON.stringify(testResult.response.data, null, 2)}
                          </pre>
                        </div>
                      </div>

                      {/* Raw Response (if different) */}
                      {testResult.response.rawResponse && testResult.response.rawResponse !== JSON.stringify(testResult.response.data) && (
                        <div className="mt-4">
                          <span className="font-medium text-gray-700 dark:text-gray-300">Raw Response:</span>
                          <div className="mt-1 p-2 bg-gray-200 dark:bg-gray-700 rounded">
                            <pre className="text-xs overflow-x-auto max-h-32 overflow-y-auto">
                              {testResult.response.rawResponse}
                            </pre>
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                )}

                {/* Error Details */}
                {testResult.error && (
                  <div className="space-y-3">
                    <h3 className="text-lg font-semibold text-red-700 dark:text-red-300">Error Details</h3>
                    <div className="bg-red-50 dark:bg-red-950/20 rounded-lg p-4 border border-red-200 dark:border-red-800">
                      <div className="text-sm space-y-2">
                        <div>
                          <span className="font-medium text-red-700 dark:text-red-300">Error:</span>
                          <span className="ml-2 text-red-600 dark:text-red-400">
                            {testResult.error.name}: {testResult.error.message}
                          </span>
                        </div>
                        {testResult.error.stack && (
                          <div>
                            <span className="font-medium text-red-700 dark:text-red-300">Stack Trace:</span>
                            <div className="mt-1 p-2 bg-red-100 dark:bg-red-900/50 rounded">
                              <pre className="text-xs overflow-x-auto max-h-32 overflow-y-auto text-red-600 dark:text-red-400">
                                {testResult.error.stack}
                              </pre>
                            </div>
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                )}
              </>
            )}

            {/* Loading State */}
            {testLoading && !testResult && (
              <div className="flex items-center justify-center p-8">
                <Loader2 className="h-8 w-8 animate-spin text-blue-600" />
                <span className="ml-3 text-blue-600">Testing API endpoint...</span>
              </div>
            )}
          </div>
        </DialogContent>
      </Dialog>

      {/* Top 15 Modal */}
      <Top15Modal
        isOpen={isTop15ModalOpen}
        onClose={() => setIsTop15ModalOpen(false)}
        data={top15Data}
        isLoading={isTop15Loading}
      />

      {/* Bottom 30 Modal */}
      <Top15Modal
        isOpen={isBottom30ModalOpen}
        onClose={() => setIsBottom30ModalOpen(false)}
        data={bottom30Data}
        isLoading={isBottom30Loading}
        isBottomModal={true}
      />
    </>
  );
}