import { useState } from "react";
import { useQuery } 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 { Plus, Search, Package, Clock, Edit, Activity, User, Smartphone, Settings, Zap, Loader2, Eye } from "lucide-react";
import StaffNotifications from "@/components/staff-notifications";
import ClientEditModal from "@/components/client-edit-modal";
import ClientViewModal from "@/components/client-view-modal";
import UsageStatsModal from "@/components/usage-stats-modal";
import RoleGuard from "@/components/role-guard";
import { useAuth } from "@/hooks/use-auth";
import { useToast } from "@/hooks/use-toast";
import { VERSION } from "@shared/version";
import type { Client, ClientWithSimswaps } from "@shared/schema";

export default function Dashboard() {
  const { toast } = useToast();
  const [searchTerm, setSearchTerm] = useState("");
  const [editingClient, setEditingClient] = useState<Client | null>(null);
  const [viewingClient, setViewingClient] = useState<ClientWithSimswaps | null>(null);
  const [usageStatsClient, setUsageStatsClient] = useState<Client | null>(null);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [isViewModalOpen, setIsViewModalOpen] = useState(false);
  const [isUsageStatsModalOpen, setIsUsageStatsModalOpen] = useState(false);

  const { data: recentlyViewed, isLoading } = useQuery<ClientWithSimswaps[]>({
    queryKey: ["/api/recently-viewed"],
  });

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

  const handleViewClient = (client: ClientWithSimswaps) => {
    setViewingClient(client);
    setIsViewModalOpen(true);
  };

  const handleViewUsageStats = (client: ClientWithSimswaps) => {
    setUsageStatsClient(client);
    setIsUsageStatsModalOpen(true);
  };

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

  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">Client Dashboard</h2>
            <p className="text-gray-600 mt-1">Manage 4G/5G client data and SIM relationships</p>
          </div>
          <div className="flex items-center space-x-4">
            {/* Version Display */}
            <Card className="bg-gradient-to-r from-blue-50 to-indigo-50 border-blue-200">
              <CardContent className="px-4 py-2">
                <div className="flex items-center gap-2">
                  <Package className="w-4 h-4 text-blue-600" />
                  <span className="text-sm font-medium text-blue-900">Masterfile {VERSION}</span>
                  <Badge className="bg-blue-600 hover:bg-blue-700 text-xs">v{VERSION}</Badge>
                </div>
              </CardContent>
            </Card>
            {/* Search Bar */}
            <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">
        {/* Staff Notifications - Animated */}
        <div className="animate-slide-in-left">
          <StaffNotifications />
        </div>

        {/* Recently Viewed Accounts */}
        <Card className="mb-8 animate-slide-in-left-delay">
          <CardHeader>
            <CardTitle className="flex items-center space-x-2">
              <Clock className="w-5 h-5 text-blue-600" />
              <span>Recently Viewed Accounts</span>
              <Badge variant="secondary">{recentlyViewed?.length || 0} accounts</Badge>
            </CardTitle>
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <div className="flex items-center justify-center py-8">
                <Loader2 className="w-8 h-8 animate-spin text-blue-600" />
                <span className="ml-2 text-gray-600">Loading recent accounts...</span>
              </div>
            ) : recentlyViewed && recentlyViewed.length > 0 ? (
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                {recentlyViewed.slice(0, 10).map((client: ClientWithSimswaps) => (
                  <Card key={client.id} className="border border-gray-200 hover:border-blue-300 transition-colors">
                    <CardContent className="p-4">
                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <div className="flex items-center space-x-2 mb-2">
                            <h3 className="font-semibold text-gray-900">{client.name}</h3>
                            <Badge variant="outline" className="text-xs">
                              {client.category}
                            </Badge>
                            {client.isReseller && (
                              <Badge className="bg-purple-100 text-purple-800 text-xs">
                                Reseller
                              </Badge>
                            )}
                          </div>
                          
                          <div className="space-y-1 text-sm text-gray-600">
                            {client.email && (
                              <p className="flex items-center">
                                <User className="w-3 h-3 mr-1" />
                                {client.email}
                              </p>
                            )}
                            {client.msisdn && (
                              <p className="flex items-center">
                                <Smartphone className="w-3 h-3 mr-1" />
                                {client.msisdn}
                              </p>
                            )}
                            {client.accountNumber && (
                              <p className="flex items-center">
                                <Settings className="w-3 h-3 mr-1" />
                                Account: {client.accountNumber}
                              </p>
                            )}
                          </div>
                        </div>
                        
                        <div className="flex flex-col space-y-1">
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => handleViewClient(client)}
                            className="h-8 px-2 text-blue-600 border-blue-200 hover:bg-blue-50"
                          >
                            <Eye className="w-3 h-3 mr-1" />
                            View Details
                          </Button>
                          
                          <RoleGuard requiredRole="admin">
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => handleEditClient(client)}
                              className="h-8 px-2"
                            >
                              <Edit className="w-3 h-3 mr-1" />
                              Edit
                            </Button>
                          </RoleGuard>
                          
                          {client.category === "MTN Fixed" && (
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => handleViewUsageStats(client)}
                              className="h-8 px-2 text-green-600 border-green-200 hover:bg-green-50"
                            >
                              <Activity className="w-3 h-3 mr-1" />
                              Stats
                            </Button>
                          )}
                        </div>
                      </div>
                      
                      {client.simswaps && client.simswaps.length > 0 && (
                        <div className="mt-3 pt-3 border-t border-gray-100">
                          <div className="flex items-center text-xs text-gray-500">
                            <Zap className="w-3 h-3 mr-1" />
                            {client.simswaps.length} SIM swap{client.simswaps.length !== 1 ? 's' : ''}
                          </div>
                        </div>
                      )}
                    </CardContent>
                  </Card>
                ))}
              </div>
            ) : (
              <div className="text-center py-8">
                <Clock className="w-12 h-12 text-gray-400 mx-auto mb-2" />
                <p className="text-gray-500">No recently viewed accounts</p>
                <p className="text-sm text-gray-400 mt-1">View client accounts to see them here</p>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      <ClientEditModal
        client={editingClient}
        isOpen={isEditModalOpen}
        onClose={() => setIsEditModalOpen(false)}
      />
      
      <ClientViewModal
        client={viewingClient}
        isOpen={isViewModalOpen}
        onClose={() => setIsViewModalOpen(false)}
      />
      
      <UsageStatsModal
        client={usageStatsClient}
        isOpen={isUsageStatsModalOpen}
        onClose={() => setIsUsageStatsModalOpen(false)}
      />
    </>
  );
}
