import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { Plus, Search, ChevronLeft, ChevronRight, Grid3X3, List, Eye, Layers, Building, Star, ChevronDown, ChevronUp } from "lucide-react";
import TelkomClientCard from "@/components/telkom-client-card";
import ClientEditModal from "@/components/client-edit-modal";
import SimEditModal from "@/components/sim-edit-modal";
import ClientViewModal from "@/components/client-view-modal";
import RoleGuard from "@/components/role-guard";
import { useToast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
import type { TelkomClient, Client } from "@shared/schema";

export default function TelkomClients() {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [searchTerm, setSearchTerm] = useState("");
  const [editingClient, setEditingClient] = useState<Client | null>(null);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [editingSim, setEditingSim] = useState<any>(null);
  const [editingSimType, setEditingSimType] = useState<"primary" | "secondary">("primary");
  const [isSimEditModalOpen, setIsSimEditModalOpen] = useState(false);
  const [viewingClient, setViewingClient] = useState<Client | null>(null);
  const [isViewModalOpen, setIsViewModalOpen] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [clientsPerPage, setClientsPerPage] = useState(5);
  const [viewMode, setViewMode] = useState<"enhanced" | "list">("enhanced");
  const [expandedClients, setExpandedClients] = useState<Set<number>>(new Set());
  const [clientToDelete, setClientToDelete] = useState<TelkomClient | null>(null);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);

  const { data: telkomData, isLoading } = useQuery({
    queryKey: ["/api/clients/telkom", currentPage, clientsPerPage],
    queryFn: async () => {
      const response = await fetch(`/api/clients/telkom?page=${currentPage}&limit=${clientsPerPage}`, {
        credentials: "include",
      });
      if (!response.ok) throw new Error("Failed to fetch Telkom clients");
      return response.json();
    },
  });

  const telkomClients = telkomData?.clients || [];
  const totalCount = telkomData?.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/telkom"] });
      queryClient.invalidateQueries({ queryKey: ["/api/stats"] });
      queryClient.invalidateQueries({ queryKey: ["/api/recently-viewed"] });
      toast({
        title: "Success",
        description: "Telkom client deleted successfully",
      });
      setIsDeleteDialogOpen(false);
      setClientToDelete(null);
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.message || "Failed to delete client",
        variant: "destructive",
      });
    },
  });

  const handleEditClient = (client: TelkomClient) => {
    setEditingClient(client);
    setIsEditModalOpen(true);
  };

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

  const handleDeleteClient = (clientId: number) => {
    const client = telkomClients.find((c: TelkomClient) => c.id === clientId);
    if (client) {
      setClientToDelete(client);
      setIsDeleteDialogOpen(true);
    }
  };

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

  const handleAddClient = () => {
    setEditingClient(null);
    setIsEditModalOpen(true);
  };

  const handleEditSim = async (sim: any, simType: "primary" | "secondary") => {
    if (simType === "secondary" && sim.id) {
      // Fetch complete secondary SIM data with primary relationship info
      try {
        const response = await fetch(`/api/clients/${sim.id}`);
        if (response.ok) {
          const completeSimData = await response.json();
          setEditingSim(completeSimData);
        } else {
          setEditingSim(sim);
        }
      } catch (error) {
        console.error('Error fetching complete SIM data:', error);
        setEditingSim(sim);
      }
    } else {
      setEditingSim(sim);
    }
    setEditingSimType(simType);
    setIsSimEditModalOpen(true);
  };

  const filteredClients = (telkomClients || []).filter((client: TelkomClient) =>
    client.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    client.contactInfo?.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const toggleClientExpansion = (clientId: number) => {
    setExpandedClients(prev => {
      const newSet = new Set(prev);
      if (newSet.has(clientId)) {
        newSet.delete(clientId);
      } else {
        newSet.add(clientId);
      }
      return newSet;
    });
  };

  return (
    <>
      {/* Top Bar */}
      <div className="bg-white border-b border-gray-200 px-6 py-4">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-2xl font-bold text-gray-900">Telkom Clients</h2>
            <p className="text-gray-600 mt-1">Manage Telkom clients with Primary + Secondary SIM relationships</p>
          </div>
          <div className="flex items-center space-x-4">
            {/* View Mode Toggle */}
            <div className="flex items-center bg-gray-100 rounded-lg p-1">
              <Button
                variant={viewMode === "enhanced" ? "default" : "ghost"}
                size="sm"
                onClick={() => setViewMode("enhanced")}
                className="flex items-center space-x-2 px-3 py-2"
              >
                <Grid3X3 size={16} />
                <span>Enhanced View</span>
              </Button>
              <Button
                variant={viewMode === "list" ? "default" : "ghost"}
                size="sm"
                onClick={() => setViewMode("list")}
                className="flex items-center space-x-2 px-3 py-2"
              >
                <List size={16} />
                <span>List View</span>
              </Button>
            </div>
            <div className="relative">
              <Input
                type="text"
                placeholder="Search Telkom clients..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-80 pl-10"
              />
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
            </div>
            <Select value={clientsPerPage.toString()} onValueChange={(value) => {
              setClientsPerPage(parseInt(value));
              setCurrentPage(1);
            }}>
              <SelectTrigger className="w-40">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="2">2 per page</SelectItem>
                <SelectItem value="5">5 per page</SelectItem>
                <SelectItem value="10">10 per page</SelectItem>
                <SelectItem value="20">20 per page</SelectItem>
              </SelectContent>
            </Select>
            <RoleGuard requiredRole="admin">
              <Button onClick={handleAddClient} className="flex items-center space-x-2">
                <Plus size={20} />
                <span>Add Telkom Client</span>
              </Button>
            </RoleGuard>
          </div>
        </div>
      </div>

      {/* Content Area */}
      <div className="flex-1 overflow-auto p-6">
        {isLoading ? (
          <div className="space-y-4">
            {[1, 2, 3].map((i) => (
              <div key={i} className="bg-white rounded-xl shadow-sm border border-gray-200 p-6 animate-pulse">
                <div className="h-48 bg-gray-200 rounded"></div>
              </div>
            ))}
          </div>
        ) : filteredClients && filteredClients.length > 0 ? (
          viewMode === "enhanced" ? (
            <div className="space-y-4">
              {filteredClients.map((client: TelkomClient) => (
                <TelkomClientCard
                  key={client.id}
                  client={client}
                  onEdit={handleEditClient}
                  onDelete={handleDeleteClient}
                  onEditSim={handleEditSim}
                  onView={handleViewClient}
                />
              ))}
            </div>
          ) : (
            <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
              <div className="space-y-1">
                {filteredClients.map((client: TelkomClient) => {
                  const isExpanded = expandedClients.has(client.id);
                  return (
                    <div key={client.id} className="border border-gray-300 rounded-lg overflow-hidden">
                      {/* Primary SIM Row - Clickable to expand/collapse */}
                      <div 
                        className={`bg-gradient-to-r from-yellow-100 to-amber-100 p-2 cursor-pointer hover:from-yellow-200 hover:to-amber-200 transition-colors ${client.isReseller ? 'border-l-4 border-l-blue-500' : ''}`}
                        onClick={() => toggleClientExpansion(client.id)}
                      >
                        <div className="flex items-center justify-between">
                          <div className="flex items-center space-x-3 flex-1 min-w-0">
                            {/* Expand/Collapse Icon */}
                            <div className="flex items-center space-x-1 flex-shrink-0">
                              {client.secondarySims && client.secondarySims.length > 0 ? (
                                isExpanded ? (
                                  <ChevronDown size={16} className="text-yellow-700" />
                                ) : (
                                  <ChevronRight size={16} className="text-yellow-700" />
                                )
                              ) : (
                                <div className="w-4 h-4"></div>
                              )}
                              <Star className="text-yellow-600 fill-current" size={14} />
                            </div>
                            
                            {/* Client Name */}
                            <div className="flex items-center space-x-2 min-w-0 flex-shrink-0">
                              <span className="font-bold text-gray-900 text-sm truncate max-w-32">{client.name}</span>
                              {client.isReseller && (
                                <span className="bg-blue-600 text-white text-xs px-1 py-0.5 rounded font-medium flex-shrink-0">R</span>
                              )}
                            </div>
                            
                            {/* Primary SIM Details - More compact layout */}
                            <div className="flex items-center space-x-4 text-xs min-w-0 flex-1">
                              <div className="flex-shrink-0">
                                <span className="text-gray-500">Account:</span>
                                <span className="font-semibold text-gray-900 ml-1">{client.accountNumber}</span>
                              </div>
                              <div className="min-w-0 flex-shrink-0">
                                <span className="text-gray-500">SIM:</span>
                                <span className="font-mono text-gray-900 ml-1 truncate">{client.primarySim.simNumber}</span>
                              </div>
                              <div className="min-w-0 flex-shrink-0">
                                <span className="text-gray-500">Phone:</span>
                                <span className="font-mono text-gray-900 ml-1">{client.primarySim.phoneNumber}</span>
                              </div>
                              <div className="flex-shrink-0">
                                <span className={`inline-flex px-1 py-0.5 text-xs font-medium rounded ${
                                  client.primarySim.status.toLowerCase() === 'active' 
                                    ? 'bg-green-100 text-green-700' 
                                    : 'bg-red-100 text-red-700'
                                }`}>
                                  {client.primarySim.status}
                                </span>
                              </div>
                            </div>
                          </div>
                          
                          {/* Right Side Info */}
                          <div className="flex items-center space-x-2 flex-shrink-0">
                            {client.secondarySims && client.secondarySims.length > 0 && (
                              <div className="text-center">
                                <div className="text-lg font-bold text-blue-600">{client.secondarySims.length}</div>
                                <div className="text-xs text-gray-600">Sec</div>
                              </div>
                            )}
                            
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={(e) => {
                                e.stopPropagation();
                                handleEditClient(client);
                              }}
                              className="h-7 px-2 text-xs"
                            >
                              <Eye size={12} className="mr-1" />
                              View
                            </Button>
                          </div>
                        </div>
                      </div>
                      
                      {/* Expanded Secondary SIMs Section */}
                      {isExpanded && client.secondarySims && client.secondarySims.length > 0 && (
                        <div className="bg-gray-50 border-t border-gray-200">
                          <div className="p-4">
                            <div className="mb-3">
                              <h4 className="text-sm font-semibold text-gray-700 flex items-center">
                                <Layers className="mr-2" size={14} />
                                Secondary SIMs ({client.secondarySims.length})
                              </h4>
                            </div>
                            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">
                              {client.secondarySims.map((sim, index) => (
                                <div key={index} className="bg-white border border-gray-200 rounded-lg p-3 hover:shadow-md transition-shadow">
                                  <div className="flex items-center justify-between mb-2">
                                    <span className="text-xs font-medium text-gray-500 bg-gray-100 px-2 py-1 rounded">
                                      SIM #{index + 1}
                                    </span>
                                    <span className={`inline-flex px-2 py-1 text-xs font-medium rounded ${
                                      sim.status.toLowerCase() === 'active' 
                                        ? 'bg-green-100 text-green-700' 
                                        : 'bg-red-100 text-red-700'
                                    }`}>
                                      {sim.status}
                                    </span>
                                  </div>
                                  
                                  <div className="space-y-2 text-sm">
                                    <div>
                                      <span className="text-gray-500 text-xs">Name:</span>
                                      <div className="font-medium text-gray-900 truncate">{sim.name}</div>
                                    </div>
                                    <div>
                                      <span className="text-gray-500 text-xs">SIM:</span>
                                      <div className="font-mono text-gray-900 text-xs">{sim.simNumber}</div>
                                    </div>
                                    <div>
                                      <span className="text-gray-500 text-xs">Phone:</span>
                                      <div className="font-mono text-gray-900 text-xs">{sim.phoneNumber}</div>
                                    </div>
                                    <div>
                                      <span className="text-gray-500 text-xs">MSISDN:</span>
                                      <div className="font-mono text-gray-900 text-xs">{sim.msisdn}</div>
                                    </div>
                                    <div>
                                      <span className="text-gray-500 text-xs">Plan:</span>
                                      <div className="text-gray-900 text-xs truncate">{sim.dataPlan}</div>
                                    </div>
                                    <div>
                                      <span className="text-gray-500 text-xs">Email:</span>
                                      <div className="text-gray-900 text-xs truncate">{sim.email}</div>
                                    </div>
                                  </div>
                                </div>
                              ))}
                            </div>
                          </div>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>
          )
        ) : (
          <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-12 text-center">
            <p className="text-gray-500">
              {searchTerm ? "No Telkom clients found matching your search" : "No Telkom clients found"}
            </p>
          </div>
        )}
        
        {/* Pagination Controls */}
        {telkomClients.length > 0 && totalPages > 1 && (
          <div className="mt-6 flex items-center justify-between">
            <div className="text-sm text-gray-700">
              Showing {((currentPage - 1) * clientsPerPage) + 1} to {Math.min(currentPage * clientsPerPage, totalCount)} of {totalCount} Telkom clients
            </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>
              <span className="text-sm text-gray-600">
                Page {currentPage} of {totalPages}
              </span>
              <Button
                variant="outline"
                size="sm"
                onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
                disabled={currentPage === totalPages}
              >
                Next
                <ChevronRight className="h-4 w-4" />
              </Button>
            </div>
          </div>
        )}
      </div>

      <ClientEditModal
        client={editingClient}
        isOpen={isEditModalOpen}
        onClose={() => setIsEditModalOpen(false)}
      />

      <SimEditModal
        sim={editingSim}
        simType={editingSimType}
        isOpen={isSimEditModalOpen}
        onClose={() => setIsSimEditModalOpen(false)}
      />

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

      {/* Delete Confirmation Dialog */}
      <AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Telkom 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 />
              • Primary SIM and all secondary SIMs ({clientToDelete?.secondarySims?.length || 0} secondary SIMs)
              <br />
              • All service 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>
    </>
  );
}
