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 { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Search, Plus, Edit, Trash2, Eye, EyeOff } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
import type { Client, ClientWithSimswaps } from "@shared/schema";
import ClientEditModal from "@/components/client-edit-modal";
import SimEditModal from "@/components/sim-edit-modal";
import RoleGuard from "@/components/role-guard";

export default function TelkomSmart() {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [search, setSearch] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const [isAddModalOpen, setIsAddModalOpen] = useState(false);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [isSimEditModalOpen, setIsSimEditModalOpen] = useState(false);
  const [selectedClient, setSelectedClient] = useState<ClientWithSimswaps | null>(null);
  const [selectedSim, setSelectedSim] = useState<Client | null>(null);
  const [showMSISDN, setShowMSISDN] = useState(false);

  const limit = 20;
  const offset = (currentPage - 1) * limit;

  const { data: response, isLoading } = useQuery({
    queryKey: ["/api/clients", search, "Telkom Smartphone Uncapped", limit, offset],
    queryFn: async () => {
      const params = new URLSearchParams({
        search: search || "",
        category: "Telkom Smartphone Uncapped",
        limit: limit.toString(),
        offset: offset.toString(),
      });
      const res = await fetch(`/api/clients?${params}`);
      if (!res.ok) throw new Error("Failed to fetch clients");
      return res.json();
    },
  });

  const clients = response?.clients || [];
  const total = response?.total || 0;
  const totalPages = Math.ceil(total / limit);

  const deleteClientMutation = useMutation({
    mutationFn: async (clientId: number) => {
      await apiRequest("DELETE", `/api/clients/${clientId}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/clients"] });
      toast({
        title: "Success",
        description: "Client deleted successfully",
      });
    },
    onError: (error: Error) => {
      toast({
        title: "Error",
        description: error.message,
        variant: "destructive",
      });
    },
  });

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

  const handleEditSim = (client: Client) => {
    setSelectedSim(client);
    setIsSimEditModalOpen(true);
  };

  const handleDeleteClient = (clientId: number) => {
    if (confirm("Are you sure you want to delete this client?")) {
      deleteClientMutation.mutate(clientId);
    }
  };

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    setCurrentPage(1);
  };

  const filteredClients = (clients || []).filter((client: ClientWithSimswaps) =>
    client.category === "Telkom Smartphone Uncapped"
  );

  return (
    <div className="p-6">
      <div className="flex justify-between items-center mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Telkom Smart</h1>
          <p className="text-gray-600">Manage Telkom Smartphone Uncapped clients</p>
        </div>
        <RoleGuard requiredRole="admin">
          <Button onClick={() => setIsAddModalOpen(true)} className="flex items-center gap-2">
            <Plus size={16} />
            Add Client
          </Button>
        </RoleGuard>
      </div>

      {/* Search and Filters */}
      <Card className="mb-6">
        <CardContent className="pt-6">
          <form onSubmit={handleSearch} className="flex gap-4 items-end">
            <div className="flex-1">
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Search Clients
              </label>
              <Input
                placeholder="Search by name, email, MSISDN, or account number..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="w-full"
              />
            </div>
            <Button type="submit" className="flex items-center gap-2">
              <Search size={16} />
              Search
            </Button>
            <Button
              type="button"
              variant="outline"
              onClick={() => setShowMSISDN(!showMSISDN)}
              className="flex items-center gap-2"
            >
              {showMSISDN ? <EyeOff size={16} /> : <Eye size={16} />}
              {showMSISDN ? "Hide" : "Show"} MSISDN
            </Button>
          </form>
        </CardContent>
      </Card>

      {/* Results Summary */}
      <div className="mb-4">
        <p className="text-sm text-gray-600">
          Showing {filteredClients.length} of {total} Telkom Smart clients
          {search && ` matching "${search}"`}
        </p>
      </div>

      {/* Clients Grid */}
      {isLoading ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {[...Array(6)].map((_, i) => (
            <Card key={i} className="animate-pulse">
              <CardContent className="p-6">
                <div className="h-4 bg-gray-200 rounded mb-2"></div>
                <div className="h-3 bg-gray-200 rounded mb-4"></div>
                <div className="h-3 bg-gray-200 rounded mb-2"></div>
                <div className="h-3 bg-gray-200 rounded"></div>
              </CardContent>
            </Card>
          ))}
        </div>
      ) : filteredClients.length === 0 ? (
        <Card>
          <CardContent className="p-12 text-center">
            <p className="text-gray-500 mb-4">No Telkom Smart clients found</p>
            <Button onClick={() => setIsAddModalOpen(true)}>
              Add Your First Client
            </Button>
          </CardContent>
        </Card>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {filteredClients.map((client: ClientWithSimswaps) => (
            <Card 
              key={client.id} 
              className={`transition-all hover:shadow-md ${
                client.isReseller ? 'bg-blue-50 border-blue-200' : ''
              }`}
            >
              <CardHeader className="pb-3">
                <div className="flex justify-between items-start">
                  <div className="flex-1">
                    <CardTitle className="text-lg mb-1 flex items-center gap-2">
                      {client.name}
                      {client.isReseller && (
                        <Badge variant="secondary" className="bg-blue-100 text-blue-800 text-xs">
                          Reseller
                        </Badge>
                      )}
                    </CardTitle>
                    <p className="text-sm text-gray-600">{client.email}</p>
                  </div>
                  <Badge variant="outline" className="text-xs">
                    {client.status}
                  </Badge>
                </div>
              </CardHeader>
              <CardContent className="pt-0">
                <div className="space-y-2 text-sm">
                  {showMSISDN && client.msisdn && (
                    <div>
                      <span className="font-medium">MSISDN:</span> {client.msisdn}
                    </div>
                  )}
                  {client.contactInfo && (
                    <div>
                      <span className="font-medium">Contact:</span> {client.contactInfo}
                    </div>
                  )}
                  {client.status2 && (
                    <div>
                      <span className="font-medium">Status 2:</span> {client.status2}
                    </div>
                  )}
                  {client.serviceDetails && (
                    <div>
                      <span className="font-medium">Service:</span> {client.serviceDetails}
                    </div>
                  )}
                  {client.simswaps && client.simswaps.length > 0 && (
                    <div>
                      <span className="font-medium">SIM Swaps:</span> {client.simswaps.length}
                    </div>
                  )}
                </div>
                <div className="flex gap-2 mt-4">
                  <RoleGuard requiredRole="admin">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handleEditClient(client)}
                      className="flex items-center gap-1"
                    >
                      <Edit size={14} />
                      Edit
                    </Button>
                  </RoleGuard>
                  <RoleGuard requiredRole="admin">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handleEditSim(client)}
                      className="flex items-center gap-1"
                    >
                      <Edit size={14} />
                      SIM
                    </Button>
                  </RoleGuard>
                  <RoleGuard requiredRole="admin">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handleDeleteClient(client.id)}
                      className="flex items-center gap-1 text-red-600 hover:text-red-700"
                    >
                      <Trash2 size={14} />
                      Delete
                    </Button>
                  </RoleGuard>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex justify-center items-center space-x-2 mt-8">
          <Button
            variant="outline"
            disabled={currentPage === 1}
            onClick={() => setCurrentPage(currentPage - 1)}
          >
            Previous
          </Button>
          <span className="text-sm text-gray-600">
            Page {currentPage} of {totalPages}
          </span>
          <Button
            variant="outline"
            disabled={currentPage === totalPages}
            onClick={() => setCurrentPage(currentPage + 1)}
          >
            Next
          </Button>
        </div>
      )}

      {/* Modals */}
      <ClientEditModal
        client={selectedClient}
        isOpen={isAddModalOpen || isEditModalOpen}
        onClose={() => {
          setIsAddModalOpen(false);
          setIsEditModalOpen(false);
          setSelectedClient(null);
        }}
        defaultCategory="Telkom Smartphone Uncapped"
      />

      <SimEditModal
        sim={selectedSim}
        isOpen={isSimEditModalOpen}
        onClose={() => {
          setIsSimEditModalOpen(false);
          setSelectedSim(null);
        }}
        simType="primary"
      />
    </div>
  );
}