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 { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Plus, Search, Download, Eye, Edit, Trash2, Building } from "lucide-react";
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 { ClientWithSimswaps, Client } from "@shared/schema";

export default function StandardClients() {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [searchTerm, setSearchTerm] = useState("");
  const [categoryFilter, setCategoryFilter] = useState("All Categories");
  const [editingClient, setEditingClient] = useState<Client | null>(null);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [resultsPerPage, setResultsPerPage] = useState(20);

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

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

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

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

  const handleDeleteClient = (clientId: number) => {
    if (confirm("Are you sure you want to delete this client? This will also delete all associated SIMs.")) {
      deleteMutation.mutate(clientId);
    }
  };

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

  const handleExport = () => {
    toast({
      title: "Export",
      description: "Export functionality will be implemented",
    });
  };

  const getStatusColor = (status: string) => {
    switch (status.toLowerCase()) {
      case "active":
        return "bg-success text-white";
      case "suspended":
        return "bg-warning text-white";
      case "inactive":
        return "bg-error text-white";
      default:
        return "bg-gray-500 text-white";
    }
  };

  const getCategoryColor = (category: string) => {
    switch (category.toLowerCase()) {
      case "mtn":
        return "bg-purple-100 text-purple-800";
      case "vodacom":
        return "bg-red-100 text-red-800";
      case "cell c":
        return "bg-yellow-100 text-yellow-800";
      case "rain":
        return "bg-green-100 text-green-800";
      default:
        return "bg-gray-100 text-gray-800";
    }
  };

  // Filter out Telkom clients for standard view
  const standardClients = clients?.filter((client: ClientWithSimswaps) => client.category !== "Telkom") || [];

  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">Standard Clients</h2>
            <p className="text-gray-600 mt-1">Manage non-Telkom client data and SIMs</p>
          </div>
          <div className="flex items-center space-x-4">
            <div className="relative">
              <Input
                type="text"
                placeholder="Search 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>
            <RoleGuard requiredRole="admin">
              <Button onClick={handleAddClient} className="flex items-center space-x-2">
                <Plus size={20} />
                <span>Add Client</span>
              </Button>
            </RoleGuard>
          </div>
        </div>
      </div>

      {/* Content Area */}
      <div className="flex-1 overflow-auto p-6">
        <div className="bg-white rounded-xl shadow-sm border border-gray-200">
          <div className="px-6 py-4 border-b border-gray-200">
            <div className="flex items-center justify-between">
              <h3 className="text-lg font-bold text-gray-900">Standard Clients ({totalCount} total)</h3>
              <div className="flex items-center space-x-2">
                <Select value={categoryFilter} onValueChange={setCategoryFilter}>
                  <SelectTrigger className="w-48">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="All Categories">All Categories</SelectItem>
                    <SelectItem value="MTN">MTN</SelectItem>
                    <SelectItem value="Vodacom">Vodacom</SelectItem>
                    <SelectItem value="Cell C">Cell C</SelectItem>
                    <SelectItem value="Rain">Rain</SelectItem>
                  </SelectContent>
                </Select>
                <Select value={resultsPerPage.toString()} onValueChange={(value) => {
                  setResultsPerPage(parseInt(value));
                  setCurrentPage(1);
                }}>
                  <SelectTrigger className="w-32">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="10">10 per page</SelectItem>
                    <SelectItem value="20">20 per page</SelectItem>
                    <SelectItem value="50">50 per page</SelectItem>
                    <SelectItem value="100">100 per page</SelectItem>
                  </SelectContent>
                </Select>
                <Button variant="outline" onClick={handleExport} className="flex items-center space-x-2">
                  <Download size={16} />
                  <span>Export</span>
                </Button>
              </div>
            </div>
          </div>

          {isLoading ? (
            <div className="p-8">
              <div className="animate-pulse space-y-4">
                {[1, 2, 3, 4, 5].map((i) => (
                  <div key={i} className="h-16 bg-gray-200 rounded"></div>
                ))}
              </div>
            </div>
          ) : standardClients.length > 0 ? (
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow className="bg-gray-50">
                    <TableHead className="text-left">Company</TableHead>
                    <TableHead className="text-left">Contact</TableHead>
                    <TableHead className="text-left">Category</TableHead>
                    <TableHead className="text-left">SIM Count</TableHead>
                    <TableHead className="text-left">Status</TableHead>
                    <TableHead className="text-left">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {standardClients.map((client: ClientWithSimswaps) => (
                    <TableRow key={client.id} className={`hover:bg-gray-50 ${client.isReseller ? 'bg-blue-50 border-l-4 border-blue-400' : ''}`}>
                      <TableCell>
                        <div className="flex items-center">
                          <div className={`w-10 h-10 rounded-lg flex items-center justify-center mr-3 ${client.isReseller ? 'bg-blue-600' : 'bg-gray-200'}`}>
                            <Building className={`${client.isReseller ? 'text-white' : 'text-gray-600'}`} size={16} />
                          </div>
                          <div>
                            <div className="flex items-center space-x-2">
                              <div className="text-sm font-medium text-gray-900">{client.name}</div>
                              {client.isReseller && (
                                <Badge className="bg-blue-600 text-white text-xs px-2 py-1 hover:bg-blue-600">
                                  Reseller
                                </Badge>
                              )}
                            </div>
                            <div className="text-sm text-gray-500">{client.email}</div>
                          </div>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="text-sm text-gray-900">{client.contactInfo || 'N/A'}</div>
                        <div className="text-sm text-gray-500">{client.accountNumber || 'N/A'}</div>
                      </TableCell>
                      <TableCell>
                        <Badge className={getCategoryColor(client.category)} variant="secondary">
                          {client.category}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-sm text-gray-900">{client.simswaps?.length || 0}</TableCell>
                      <TableCell>
                        <Badge className={getStatusColor(client.status || 'Unknown')}>
                          {client.status || 'Unknown'}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center space-x-2">
                          <Button
                            variant="ghost"
                            size="sm"
                            className="text-primary hover:text-blue-700"
                          >
                            <Eye size={16} />
                          </Button>
                          <RoleGuard requiredRole="admin">
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleEditClient(client)}
                              className="text-gray-600 hover:text-gray-900"
                            >
                              <Edit size={16} />
                            </Button>
                          </RoleGuard>
                          <RoleGuard requiredRole="admin">
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleDeleteClient(client.id)}
                              className="text-error hover:text-red-700"
                              disabled={deleteMutation.isPending}
                            >
                              <Trash2 size={16} />
                            </Button>
                          </RoleGuard>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          ) : (
            <div className="p-12 text-center">
              <p className="text-gray-500">
                {searchTerm || categoryFilter !== "All Categories"
                  ? "No clients found matching your criteria"
                  : "No standard clients found"}
              </p>
            </div>
          )}

          {/* Pagination Controls */}
          {standardClients.length > 0 && totalPages > 1 && (
            <div className="px-6 py-4 border-t border-gray-200">
              <div className="flex items-center justify-between">
                <div className="text-sm text-gray-500">
                  Showing {((currentPage - 1) * resultsPerPage) + 1} to {Math.min(currentPage * resultsPerPage, totalCount)} of {totalCount} results
                </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}
                  >
                    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
                  </Button>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

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