import { useState } from "react";
import { useQuery } 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 { 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 type { Client } from "@shared/schema";

export default function AxxessTelkom() {
  const { toast } = useToast();
  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 clientsPerPage = 20;

  const { data: clientsData, isLoading } = useQuery({
    queryKey: ["/api/clients", "Axxess (Telkom)", currentPage],
    queryFn: async () => {
      const offset = (currentPage - 1) * clientsPerPage;
      const params = new URLSearchParams({
        category: "Axxess (Telkom)",
        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 (Telkom) clients");
      return response.json();
    },
  });

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

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

  const handleDeleteSim = (simId: number) => {
    const confirmed = window.confirm("Are you sure you want to delete this client?");
    if (confirmed) {
      fetch(`/api/clients/${simId}`, {
        method: 'DELETE',
        credentials: 'include'
      })
      .then(response => {
        if (response.ok) {
          toast({
            title: "Success",
            description: "Client deleted successfully",
          });
          // Refresh the data
          window.location.reload();
        } else {
          throw new Error('Failed to delete client');
        }
      })
      .catch(error => {
        toast({
          title: "Error",
          description: "Failed to delete client",
          variant: "destructive",
        });
      });
    }
  };

  const handleCloseAddClientModal = () => {
    setIsAddClientModalOpen(false);
    // Refresh the page to show new data
    window.location.reload();
  };

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

  return (
    <>
      <div className="p-6 space-y-6">
        {/* Header */}
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-3">
            <Users className="w-8 h-8 text-blue-600" />
            <div>
              <h1 className="text-2xl font-bold text-gray-900">Axxess (Telkom)</h1>
              <p className="text-gray-600">Manage Axxess Telkom clients</p>
            </div>
          </div>
          
          <div className="flex items-center space-x-3">
            <Badge variant="outline" className="text-sm">
              Total: {totalCount}
            </Badge>
            <RoleGuard requiredRole="admin">
              <Button onClick={() => setIsAddClientModalOpen(true)}>
                <Plus className="w-4 h-4 mr-2" />
                Add Client
              </Button>
            </RoleGuard>
          </div>
        </div>

        {/* Search */}
        <div className="flex items-center space-x-4 mb-6">
          <div className="relative flex-1 max-w-md">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
            <Input
              placeholder="Search clients..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10"
            />
          </div>
        </div>

        {/* Loading state */}
        {isLoading && (
          <div className="flex justify-center items-center h-64">
            <div className="text-gray-500">Loading clients...</div>
          </div>
        )}

        {/* Client Cards */}
        {!isLoading && (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {filteredClients.map((client: Client) => (
              <Card key={client.id} className="hover:shadow-md transition-shadow">
                <CardContent className="p-4">
                  <div className="flex justify-between items-start mb-3">
                    <div className="flex-1">
                      <h3 className="font-medium text-gray-900 truncate">
                        {client.name}
                        {client.isReseller && (
                          <Badge variant="secondary" className="ml-2 bg-blue-100 text-blue-800 text-xs">
                            Reseller
                          </Badge>
                        )}
                      </h3>
                      <p className="text-sm text-gray-600 truncate">{client.email}</p>
                    </div>
                    <Badge variant="outline" className="text-xs">
                      {client.status}
                    </Badge>
                  </div>

                  <div className="space-y-1 text-sm text-gray-600 mb-3">
                    {client.msisdn && (
                      <div>
                        <span className="font-medium">MSISDN:</span> {client.msisdn}
                      </div>
                    )}
                    {client.accountNumber && (
                      <div>
                        <span className="font-medium">Account:</span> {client.accountNumber}
                      </div>
                    )}
                    {client.serviceDetails && (
                      <div>
                        <span className="font-medium">Service:</span> {client.serviceDetails}
                      </div>
                    )}
                  </div>

                  <div className="flex justify-end space-x-2">
                    <RoleGuard requiredRole="admin">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleEditSim(client)}
                      >
                        <Edit className="w-3 h-3 mr-1" />
                        Edit
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleDeleteSim(client.id)}
                        className="text-red-600 hover:text-red-700 hover:border-red-300"
                      >
                        <Trash2 className="w-3 h-3 mr-1" />
                        Delete
                      </Button>
                    </RoleGuard>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        )}

        {/* Empty state */}
        {!isLoading && filteredClients.length === 0 && (
          <div className="text-center py-12">
            <Users className="w-12 h-12 text-gray-400 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-gray-900 mb-2">No clients found</h3>
            <p className="text-gray-600 mb-4">
              {searchTerm ? "No clients match your search criteria." : "No Axxess (Telkom) clients have been added yet."}
            </p>
            <RoleGuard requiredRole="admin">
              <Button onClick={() => setIsAddClientModalOpen(true)}>
                <Plus className="w-4 h-4 mr-2" />
                Add First Client
              </Button>
            </RoleGuard>
          </div>
        )}

        {/* Pagination */}
        {!isLoading && totalPages > 1 && (
          <div className="flex items-center justify-between">
            <p className="text-sm text-gray-700">
              Showing {((currentPage - 1) * clientsPerPage) + 1} to {Math.min(currentPage * clientsPerPage, totalCount)} of {totalCount} results
            </p>
            <div className="flex items-center space-x-2">
              <Button
                variant="outline"
                size="sm"
                onClick={() => setCurrentPage(prev => Math.max(prev - 1, 1))}
                disabled={currentPage === 1}
              >
                <ChevronLeft className="w-4 h-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(prev + 1, totalPages))}
                disabled={currentPage === totalPages}
              >
                Next
                <ChevronRight className="w-4 h-4" />
              </Button>
            </div>
          </div>
        )}
      </div>

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