import { useState } from "react";
import { useQuery } 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 { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Search as SearchIcon, Filter, Building, Edit, Grid3X3, List, Star, Layers, Eye, BarChart3 } from "lucide-react";
import SimEditModal from "@/components/sim-edit-modal";
import UsageStatsModal from "@/components/usage-stats-modal";
import ClientViewModal from "@/components/client-view-modal";
import type { ClientWithSimswaps, Client } from "@shared/schema";

export default function Search() {
  const [searchTerm, setSearchTerm] = useState("");
  const [categoryFilter, setCategoryFilter] = useState("All Categories");
  const [statusFilter, setStatusFilter] = useState("All Statuses");
  const [hasSearched, setHasSearched] = useState(false);
  const [editingSim, setEditingSim] = useState<Client | null>(null);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [viewMode, setViewMode] = useState<"enhanced" | "list">("enhanced");
  const [isUsageStatsModalOpen, setIsUsageStatsModalOpen] = useState(false);
  const [selectedClient, setSelectedClient] = useState<Client | null>(null);
  const [isViewModalOpen, setIsViewModalOpen] = useState(false);
  const [viewingClient, setViewingClient] = useState<Client | null>(null);

  const { data: searchData, isLoading, refetch } = useQuery({
    queryKey: ["/api/clients", searchTerm, categoryFilter, statusFilter],
    queryFn: async () => {
      const params = new URLSearchParams();
      if (searchTerm) params.append("search", searchTerm);
      if (categoryFilter !== "All Categories") params.append("category", categoryFilter);
      params.append("limit", "1000"); // Get all matching results for search
      params.append("offset", "0");
      
      const response = await fetch(`/api/clients?${params.toString()}`, {
        credentials: "include",
      });
      if (!response.ok) throw new Error("Failed to fetch clients");
      return response.json();
    },
    enabled: false, // Don't load automatically
  });

  const searchResults = searchData?.clients || [];
  const totalResults = searchData?.total || 0;

  const handleSearch = () => {
    setHasSearched(true);
    refetch();
  };

  const handleEditSim = (client: Client) => {
    setEditingSim(client);
    setIsEditModalOpen(true);
  };

  const handleViewUsageStats = (client: Client) => {
    setSelectedClient(client);
    setIsUsageStatsModalOpen(true);
  };

  const handleViewClient = async (client: Client) => {
    setViewingClient(client);
    setIsViewModalOpen(true);
    
    // Track the view
    try {
      await fetch(`/api/track-view/${client.id}`, {
        method: 'POST',
        credentials: 'include',
      });
    } catch (error) {
      console.error('Failed to track view:', error);
    }
  };

  const handleCloseEditModal = () => {
    setEditingSim(null);
    setIsEditModalOpen(false);
  };

  const getStatusColor = (status: string | null) => {
    if (!status) return "bg-gray-500 text-white";
    
    switch (status.toLowerCase()) {
      case "active":
        return "bg-green-500 text-white";
      case "suspended":
        return "bg-yellow-500 text-white";
      case "cancelled":
        return "bg-red-500 text-white";
      case "debit order unpaid":
        return "bg-orange-500 text-white";
      case "pending":
        return "bg-blue-500 text-white";
      default:
        return "bg-gray-500 text-white";
    }
  };

  const getCategoryColor = (category: string | null) => {
    if (!category) return "bg-gray-100 text-gray-800";
    
    switch (category.toLowerCase()) {
      case "telkom":
        return "bg-blue-100 text-blue-800";
      case "mtn mobile (gsm)":
        return "bg-purple-100 text-purple-800";
      case "mtn fixed":
        return "bg-orange-100 text-orange-800";
      case "axxess (mtn fixed)":
        return "bg-green-100 text-green-800";
      default:
        return "bg-gray-100 text-gray-800";
    }
  };

  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">Search & Filter</h2>
            <p className="text-gray-600 mt-1">Advanced search across clients and SIM data</p>
          </div>
          {/* View Mode Toggle */}
          {hasSearched && searchResults.length > 0 && (
            <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>
      </div>

      {/* Content Area */}
      <div className="flex-1 overflow-auto p-6">
        {/* Search Controls */}
        <Card className="mb-6">
          <CardHeader>
            <CardTitle className="flex items-center space-x-2">
              <Filter size={20} />
              <span>Search Filters</span>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Search Term</label>
                <div className="relative">
                  <Input
                    type="text"
                    placeholder="Search by name, email, MSISDN, SIM serial..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="pl-10"
                    onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
                  />
                  <SearchIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={16} />
                </div>
              </div>
              <div className="flex items-end">
                <Button onClick={handleSearch} className="w-full">
                  <SearchIcon size={16} className="mr-2" />
                  Search
                </Button>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Category</label>
                <Select value={categoryFilter} onValueChange={setCategoryFilter}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="All Categories">All Categories</SelectItem>
                    <SelectItem value="Telkom">Telkom</SelectItem>
                    <SelectItem value="MTN Mobile (GSM)">MTN Mobile (GSM)</SelectItem>
                    <SelectItem value="MTN Fixed">MTN Fixed</SelectItem>
                    <SelectItem value="Axxess (MTN Fixed)">Axxess (MTN Fixed)</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Search Results */}
        <Card>
          <CardHeader>
            <CardTitle>
              Search Results {hasSearched && `(${totalResults} found)`}
            </CardTitle>
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <div className="space-y-4">
                {[1, 2, 3, 4, 5].map((i) => (
                  <div key={i} className="h-16 bg-gray-200 rounded animate-pulse"></div>
                ))}
              </div>
            ) : searchResults && searchResults.length > 0 ? (
              viewMode === "enhanced" ? (
                <div className="space-y-4">
                  {searchResults.map((client: Client) => (
                    <div key={client.id} className={`border rounded-lg p-4 hover:shadow-sm transition-shadow ${client.isReseller ? 'bg-blue-50 border-blue-300 ring-2 ring-blue-200' : 'border-gray-200'}`}>
                    <div className="flex items-center justify-between">
                      <div className="flex items-center space-x-4">
                        <div className={`w-12 h-12 rounded-lg flex items-center justify-center ${client.isReseller ? 'bg-blue-600' : 'bg-gray-200'}`}>
                          <Building className={`${client.isReseller ? 'text-white' : 'text-gray-600'}`} size={20} />
                        </div>
                        <div>
                          <div className="flex items-center space-x-2">
                            <h4 className="text-lg font-semibold text-gray-900">{client.name}</h4>
                            {client.isReseller && (
                              <Badge className="bg-blue-600 text-white text-xs px-2 py-1 hover:bg-blue-600">
                                Reseller
                              </Badge>
                            )}
                          </div>
                          <p className="text-gray-600">{client.email}</p>
                          {client.category === 'Telkom' ? (
                            <>
                              <p className="text-sm text-gray-500">Account Number: {client.accountNumber || "N/A"}</p>
                              <p className="text-sm text-gray-500">SIM: {client.simSerialNumber || "N/A"}</p>
                              {!client.isPrimarySim && (client as any).primarySimInfo && (
                                <p className="text-sm text-blue-600 font-medium">
                                  {client.accountNumber || 'N/A'} is secondary to {(client as any).primarySimInfo.accountNumber || 'N/A'}
                                </p>
                              )}
                            </>
                          ) : (
                            <>
                              <p className="text-sm text-gray-500">MSISDN: {client.msisdn || "N/A"}</p>
                              <p className="text-sm text-gray-500">SIM: {client.simSerialNumber || "N/A"}</p>
                            </>
                          )}
                        </div>
                      </div>
                      <div className="flex items-center space-x-2">
                        <Badge className={getCategoryColor(client.category)} variant="secondary">
                          {client.category}
                        </Badge>
                        <Badge className={getStatusColor(client.status)}>
                          {client.status || "Unknown"}
                        </Badge>
                        {client.status2 && (
                          <Badge variant="outline">
                            {client.status2}
                          </Badge>
                        )}
                        {client.isPrimarySim && (
                          <Badge className="bg-yellow-100 text-yellow-800" variant="secondary">
                            Primary
                          </Badge>
                        )}
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleViewClient(client)}
                          className="h-8 w-8 p-0 text-green-600 hover:text-green-700"
                          title="View Client Details"
                        >
                          <Eye className="h-4 w-4" />
                        </Button>
                        {client.category === 'MTN Fixed' && (
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleViewUsageStats(client)}
                            className="h-8 w-8 p-0"
                            title="View Usage Statistics"
                          >
                            <BarChart3 className="h-4 w-4" />
                          </Button>
                        )}
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleEditSim(client)}
                          className="h-8 w-8 p-0"
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                    <div className="mt-2 text-sm text-gray-600">
                      <p><strong>Account:</strong> {client.accountNumber}</p>
                      <p><strong>Service:</strong> {client.serviceDetails}</p>
                    </div>
                  </div>
                  ))}
                </div>
              ) : (
                <div className="overflow-x-auto">
                  <table className="w-full text-xs">
                    <thead className="bg-gradient-to-r from-blue-100 to-indigo-100 border-b-2 border-blue-300">
                      <tr>
                        <th className="px-3 py-2 text-left text-xs font-bold text-blue-900 uppercase tracking-wide">Client & SIM Info</th>
                        <th className="px-3 py-2 text-left text-xs font-bold text-blue-900 uppercase tracking-wide">Category</th>
                        <th className="px-3 py-2 text-left text-xs font-bold text-blue-900 uppercase tracking-wide">Account/MSISDN</th>
                        <th className="px-3 py-2 text-left text-xs font-bold text-blue-900 uppercase tracking-wide">Status</th>
                        <th className="px-3 py-2 text-left text-xs font-bold text-blue-900 uppercase tracking-wide">Action</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-100">
                      {searchResults.map((client: Client) => (
                        <tr key={client.id} className={`hover:bg-blue-50 transition-colors ${client.isReseller ? 'bg-blue-25' : ''}`}>
                          <td className="px-3 py-2">
                            <div className="space-y-1">
                              {/* Client Name with Primary Badge */}
                              <div className="flex items-center space-x-2">
                                <div className="flex items-center space-x-1">
                                  {client.isPrimarySim && (
                                    <Star className="text-yellow-600 fill-current" size={10} />
                                  )}
                                  <span className="font-bold text-gray-900 text-xs">{client.name}</span>
                                </div>
                                {client.isReseller && (
                                  <span className="bg-blue-500 text-white text-xs px-1 py-0.5 rounded">R</span>
                                )}
                                {client.isPrimarySim && (
                                  <span className="bg-yellow-100 text-yellow-800 text-xs px-1 py-0.5 rounded font-bold">PRIMARY</span>
                                )}
                              </div>
                              
                              {/* SIM Details */}
                              <div className={`${client.isPrimarySim ? 'bg-gradient-to-r from-yellow-50 to-amber-50 border border-yellow-200' : 'bg-gray-50 border border-gray-200'} rounded p-1`}>
                                <div className="text-xs">
                                  <div>
                                    <span className="text-gray-500">SIM:</span>
                                    <div className="font-mono text-gray-900">{client.simSerialNumber || "N/A"}</div>
                                  </div>
                                  <div>
                                    <span className="text-gray-500">Email:</span>
                                    <div className="text-gray-700 truncate max-w-32">{client.email}</div>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </td>
                          
                          <td className="px-3 py-2">
                            <Badge className={`${getCategoryColor(client.category)} text-xs`} variant="secondary">
                              {client.category}
                            </Badge>
                          </td>
                          
                          <td className="px-3 py-2">
                            <div className="space-y-1">
                              {client.category === 'Telkom' ? (
                                <>
                                  <div>
                                    <span className="text-gray-500 text-xs">Account:</span>
                                    <div className="font-semibold text-gray-900">{client.accountNumber || "N/A"}</div>
                                  </div>
                                  {!client.isPrimarySim && (client as any).primarySimInfo && (
                                    <div className="text-xs text-blue-600 font-medium">
                                      → Secondary to {(client as any).primarySimInfo.accountNumber || 'N/A'}
                                    </div>
                                  )}
                                </>
                              ) : (
                                <div>
                                  <span className="text-gray-500 text-xs">MSISDN:</span>
                                  <div className="font-mono text-gray-900">{client.msisdn || "N/A"}</div>
                                </div>
                              )}
                              <div>
                                <span className="text-gray-500 text-xs">Service:</span>
                                <div className="text-gray-700 text-xs truncate max-w-32">{client.serviceDetails}</div>
                              </div>
                            </div>
                          </td>
                          
                          <td className="px-3 py-2">
                            <div className="space-y-1">
                              <span className={`inline-flex px-1 py-0.5 text-xs font-medium rounded ${
                                client.status?.toLowerCase() === 'active' 
                                  ? 'bg-green-100 text-green-700' 
                                  : 'bg-red-100 text-red-700'
                              }`}>
                                {client.status || "Unknown"}
                              </span>
                              {client.status2 && (
                                <div>
                                  <span className="inline-flex px-1 py-0.5 text-xs rounded bg-gray-100 text-gray-700">
                                    {client.status2}
                                  </span>
                                </div>
                              )}
                            </div>
                          </td>
                          
                          <td className="px-3 py-2">
                            <div className="flex space-x-1">
                              <Button
                                variant="outline"
                                size="sm"
                                onClick={() => handleViewClient(client)}
                                className="text-xs h-6 px-2 text-green-600 hover:text-green-700 border-green-200 hover:bg-green-50"
                              >
                                <Eye size={10} className="mr-1" />
                                View
                              </Button>
                              {client.category === 'MTN Fixed' && (
                                <Button
                                  variant="outline"
                                  size="sm"
                                  onClick={() => handleViewUsageStats(client)}
                                  className="text-xs h-6 px-2"
                                  title="View Usage Statistics"
                                >
                                  <BarChart3 size={10} className="mr-1" />
                                  Stats
                                </Button>
                              )}
                              <Button
                                variant="outline"
                                size="sm"
                                onClick={() => handleEditSim(client)}
                                className="text-xs h-6 px-2"
                              >
                                <Edit size={10} className="mr-1" />
                                Edit
                              </Button>
                            </div>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )
            ) : (
              <div className="text-center py-12">
                <p className="text-gray-500">
                  {hasSearched 
                    ? "No results found matching your search criteria"
                    : "Enter search criteria and click Search to find clients"}
                </p>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Edit Modal */}
      <SimEditModal
        sim={editingSim}
        isOpen={isEditModalOpen}
        onClose={handleCloseEditModal}
        simType="primary"
      />

      {/* Usage Statistics Modal */}
      <UsageStatsModal
        client={selectedClient}
        isOpen={isUsageStatsModalOpen}
        onClose={() => setIsUsageStatsModalOpen(false)}
      />

      {/* Client View Modal */}
      <ClientViewModal
        client={viewingClient}
        isOpen={isViewModalOpen}
        onClose={() => setIsViewModalOpen(false)}
      />
    </>
  );
}
