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 { 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 { Plus, Search, ChevronLeft, ChevronRight, Edit, Trash2, Users } from "lucide-react";
import SimEditModal from "@/components/sim-edit-modal";
import ClientEditModal from "@/components/client-edit-modal";
import RoleGuard from "@/components/role-guard";
import { useToast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
import type { Client } from "@shared/schema";

export default function Axxess() {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [searchTerm, setSearchTerm] = useState("");
  const [editingSim, setEditingSim] = useState<Client | null>(null);
  const [isSimEditModalOpen, setIsSimEditModalOpen] = 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 clientsPerPage = 20;

  const { data: clientsData, isLoading } = useQuery({
    queryKey: ["/api/clients", "Axxess (MTN Fixed)", currentPage],
    queryFn: async () => {
      const offset = (currentPage - 1) * clientsPerPage;
      const params = new URLSearchParams({
        category: "Axxess (MTN Fixed)",
        limit: clientsPerPage.toString(),
        offset: offset.toString(),
      });
      
      const response = await fetch(`/api/clients?${params}`, {
        credentials: "include",
      });
      if (!response.ok) throw new Error("Failed to fetch Axxess 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: "Axxess (MTN Fixed) client deleted successfully",
      });
      setIsDeleteDialogOpen(false);
      setClientToDelete(null);
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.message || "Failed to delete client",
        variant: "destructive",
      });
    },
  });

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

  const handleDeleteSim = (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";
    }
  };

  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-6">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-4">
            <div className="w-12 h-12 bg-purple-500 rounded-lg flex items-center justify-center">
              <Users className="text-white" size={24} />
            </div>
            <div>
              <h1 className="text-2xl font-bold text-gray-900">Axxess (MTN Fixed)</h1>
              <p className="text-gray-600">Manage Axxess client SIMs</p>
            </div>
          </div>
          <div className="flex items-center space-x-3">
            <div className="relative">
              <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-80"
              />
            </div>
            <RoleGuard requiredRole="admin">
              <Button onClick={handleAddClient}>
                <Plus className="mr-2" size={16} />
                Add Client
              </Button>
            </RoleGuard>
          </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].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">
                        <Users className={`${client.isReseller ? 'text-blue-600' : 'text-purple-500'}`} size={16} />
                        <Badge className="bg-purple-100 text-purple-800 hover:bg-purple-100">
                          Axxess
                        </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">
                        <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={() => handleDeleteSim(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>
                        {client.status2 && (
                          <div className="flex justify-between">
                            <span className="text-xs text-gray-500">Status 2:</span>
                            <span className="text-xs font-medium">{client.status2}</span>
                          </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">
            <Users className="mx-auto h-12 w-12 text-gray-400 mb-4" />
            <p className="text-gray-500">
              {searchTerm ? "No Axxess clients found matching your search" : "No Axxess clients found"}
            </p>
          </div>
        )}
      </div>

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

      {/* Delete Confirmation Dialog */}
      <AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Axxess (MTN Fixed) 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 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>
    </>
  );
}