"use client"

import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Search, Filter, MapPin, Phone, Mail, Users, CheckCircle, DollarSign, Smartphone, Download, Calendar, User, CreditCard, Building } from "lucide-react"
import { Input } from "@/components/ui/input"
import { AddAgentModal } from "./modals/add-agent-modal"
import { AddSuperAgentModal } from "./modals/add-super-agent-modal";
import { EditSuperAgentModal } from "./modals/edit-super-agent-modal";
import { RejectAgentModal } from "./modals/reject-agent-modal";
import Link from "next/link"
import Swal from "sweetalert2";
import * as XLSX from "xlsx";

import { useState, useEffect } from "react";
import https from "@/services/https";

export default function AgentsPage() {
  const [agentsData, setAgentsData] = useState([]);
  const [superAgentsData, setSuperAgentsData] = useState([]);
  const [pendingAgentsData, setPendingAgentsData] = useState([]);
  const [activeTab, setActiveTab] = useState("agents");
  const [reload, setReload] = useState(false);
  const [selectedAgent, setSelectedAgent] = useState(null);
  const [isImageModalOpen, setIsImageModalOpen] = useState(false);

  const fetchAgents = async () => {
    try {
      const token = localStorage.getItem("token");
      const response = await fetch(`${https.baseUrl}/agents`, {
        headers: {
          "x-auth-token": token,
        },
      });
      if (!response.ok) {
        throw new Error("Failed to fetch agents");
      }
      const data = await response.json();
      setAgentsData(data);
    } catch (error) {
      console.error("Error fetching agents:", error);
    }
  };

  const fetchSuperAgents = async () => {
    try {
      const token = localStorage.getItem("token");
      const response = await fetch(`${https.baseUrl}/super-agents`, { 
        headers: {
          "x-auth-token": token,
        },
      });
      if (!response.ok) {
        throw new Error("Failed to fetch super-agents");
      }
      const data = await response.json();
      setSuperAgentsData(data);
    } catch (error) {
      console.error("Error fetching super-agents:", error);
    }
  };

  const fetchPendingAgents = async () => {
    try {
      const token = localStorage.getItem("token");
      const response = await fetch(`${https.baseUrl}/agents?status=pending`, {
        headers: {
          "x-auth-token": token,
        },
      });
      if (!response.ok) {
        throw new Error("Failed to fetch pending agents");
      }
      const data = await response.json();
      setPendingAgentsData(data);
    } catch (error) {
      console.error("Error fetching pending agents:", error);
    }
  };

  const handleApprove = async (agentId) => {
    try {
      const token = localStorage.getItem("token");
      const response = await fetch(`${https.baseUrl}/admin/agents/${agentId}/approval`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
          "x-auth-token": token,
        },
        body: JSON.stringify({ status: "active" }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.msg || "Failed to approve agent");
      }

      Swal.fire("Agent approved successfully");
      setReload(!reload);
    } catch (error) {
      console.error("Error approving agent:", error);
      alert(error.message);
    }
  };

  const handleDownload = () => {
    const data = activeTab === "agents" ? agentsData : superAgentsData;
    const worksheet = XLSX.utils.json_to_sheet(data);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, "Agents");
    XLSX.writeFile(workbook, "agents-data.xlsx");
  };

  useEffect(() => {
    if (activeTab === "agents") {
      fetchAgents();
    } else if (activeTab === "super-agents") {
      fetchSuperAgents();
    } else {
      fetchPendingAgents();
    }
  }, [activeTab, reload]);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">Agents</h1>
          <p className="text-muted-foreground">Manage your field agents and sales representatives</p>
        </div>
        {activeTab === "agents" ? (
          <AddAgentModal onAgentAdded={fetchAgents} reload={reload} setReload={setReload} />
        ) : (
          <AddAgentModal onAgentAdded={fetchAgents} reload={reload} setReload={setReload} />
        )}
      </div>

      <div className="flex border-b">
        <Button onClick={() => setActiveTab("agents")} className={`mr-2 transition-colors ${activeTab === "agents" ? "bg-brand-primary text-white" : "bg-transparent text-gray-500 hover:bg-[#f1ac04]"}`}>Agents</Button>
        <Button onClick={() => setActiveTab("super-agents")} className={`mr-2 transition-colors ${activeTab === "super-agents" ? "bg-brand-primary text-white" : "bg-transparent text-gray-500 hover:bg-[#f1ac04]"}`}>Super Agents</Button>
        <Button onClick={() => setActiveTab("pending-requests")} className={`transition-colors ${activeTab === "pending-requests" ? "bg-brand-primary text-white" : "bg-transparent text-gray-500 hover:bg-[#f1ac04]"}`}>Pending Requests</Button>
      </div>

      {activeTab !== "pending-requests" && (
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
          <Card className="shadow-md rounded-lg border hover:shadow-lg transition-shadow">
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Total {activeTab === "agents" ? "Agents" : "Super Agents"}</CardTitle>
              <Users className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-blue-600">{activeTab === "agents" ? agentsData.length : superAgentsData.length}</div>
              <p className="text-xs text-muted-foreground">{/* Dynamic data */}</p>
            </CardContent>
          </Card>
          <Card className="shadow-md rounded-lg border hover:shadow-lg transition-shadow">
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Active {activeTab === "agents" ? "Agents" : "Super Agents"}</CardTitle>
              <CheckCircle className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-green-600">{activeTab === "agents" ? agentsData.filter(agent => agent.status === 'active').length : superAgentsData.filter(agent => agent.status === 'active').length}</div>
              <p className="text-xs text-muted-foreground">{/* Dynamic data */}</p>
            </CardContent>
          </Card>
          <Card className="shadow-md rounded-lg border hover:shadow-lg transition-shadow">
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Total Sales</CardTitle>
              <DollarSign className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-green-600">NGN {activeTab === "agents" ? agentsData.reduce((acc, agent) => acc + (parseFloat(agent.totalSales) || 0), 0).toLocaleString() : superAgentsData.reduce((acc, agent) => acc + (parseFloat(agent.totalSales) || 0), 0).toLocaleString()}</div>
              <p className="text-xs text-muted-foreground">{/* Dynamic data */}</p>
            </CardContent>
          </Card>
          <Card className="shadow-md rounded-lg border hover:shadow-lg transition-shadow">
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Devices Managed</CardTitle>
              <Smartphone className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-purple-600">{activeTab === "agents" ? agentsData.reduce((acc, agent) => acc + parseFloat(agent.devicesManaged || 0), 0) : superAgentsData.reduce((acc, agent) => acc + parseFloat(agent.devicesManaged || 0), 0)}</div>
              <p className="text-xs text-muted-foreground">{/* Dynamic data */}</p>
            </CardContent>
          </Card>
        </div>
      )}

      <Card className="shadow-md rounded-lg border hover:shadow-lg transition-shadow">
        <CardHeader>
          <CardTitle>
            {activeTab === "agents" ? "Agent Directory" : activeTab === "super-agents" ? "Super Agent Directory" : "Pending Agent Requests"}
          </CardTitle>
          <CardDescription>
            {activeTab === "agents" ? "View and manage all field agents" : activeTab === "super-agents" ? "View and manage all super agents" : "Approve or reject pending agent requests"}
          </CardDescription>
          <div className="flex items-center space-x-2">
            <div className="relative flex-1">
              <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
              <Input placeholder={`Search ${activeTab === "agents" ? "agents" : activeTab === "super-agents" ? "super agents" : "requests"}...`} className="pl-8" />
            </div>
            <Button variant="outline" size="sm">
              <Filter className="mr-2 h-4 w-4" />
              Filter
            </Button>
            <Button variant="outline" size="sm" onClick={handleDownload}>
              <Download className="mr-2 h-4 w-4" />
              Download
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          {activeTab === "pending-requests" ? (
            <Table>
              <TableHeader className="bg-gray-100">
                <TableRow>
                  <TableHead>Agent</TableHead>
                  <TableHead>Contact</TableHead>
                  <TableHead>Region</TableHead>
                  {/* <TableHead>Date Applied</TableHead> */}
                  <TableHead>Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody className="text-blue-900">
                {pendingAgentsData.length > 0 && pendingAgentsData.map((agent) => (
                  <TableRow key={agent.id} className="hover:bg-gray-100 even:bg-gray-50">
                    <TableCell>
                      <div>
                        <div className="font-medium text-blue-900">{agent.name}</div>
                        <div className="text-sm text-blue-700">{agent.id}</div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="space-y-1">
                        <div className="flex items-center text-sm text-blue-900">
                          <Mail className="mr-1 h-3 w-3" />
                          {agent.email}
                        </div>
                        <div className="flex items-center text-sm text-blue-700">
                          <Phone className="mr-1 h-3 w-3" />
                          {agent.phone}
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center">
                        <MapPin className="mr-1 h-3 w-3" />
                        {agent.region}
                      </div>
                    </TableCell>
                    {/* <TableCell>{new Date(agent.createdAt).toLocaleDateString()}</TableCell> */}
                    <TableCell>
                      <div className="flex items-center space-x-2">
                        <Button variant="outline" size="sm" onClick={() => setSelectedAgent(agent)}>
                          Review
                        </Button>
                        <RejectAgentModal agent={agent} onAgentRejected={() => setReload(!reload)} />
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          ) : (
            <Table>
              <TableHeader className="bg-gray-100">
                <TableRow>
                  <TableHead>{activeTab === "agents" ? "Agent" : "Super Agent"}</TableHead>
                  <TableHead>Contact</TableHead>
                  <TableHead>Account Number</TableHead>
                  <TableHead>Region</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Credit Balance</TableHead>
                  <TableHead>Devices</TableHead>
                  {activeTab !== "agents" &&<TableHead>Agent Managed</TableHead>}
                  <TableHead>Total Sales</TableHead>
                  <TableHead>Total Customers</TableHead>
                  <TableHead>Last Active</TableHead>
                  <TableHead>Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody className="text-blue-900">
                {(activeTab === "agents" ? agentsData : superAgentsData).length > 0 && (activeTab === "agents" ? agentsData : superAgentsData).map((agent) => (
                  <TableRow key={agent.id} className="hover:bg-gray-100 even:bg-gray-50">
                    <TableCell>
                      <div>
                        <div className="font-medium text-blue-900">{agent.name}</div>
                        <div className="text-sm text-blue-700">{agent.id}</div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="space-y-1">
                        <div className="flex items-center text-sm text-blue-900">
                          <Mail className="mr-1 h-3 w-3" />
                          {agent.email}
                        </div>
                        <div className="flex items-center text-sm text-blue-700">
                          <Phone className="mr-1 h-3 w-3" />
                          {agent.phone}
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center">
                        {agent.accountNumber ?? 'N/A'}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center">
                        <MapPin className="mr-1 h-3 w-3" />
                        {agent.region}
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant={agent.status === "active" ? "success" : agent.status === "pending" ? "default" : "destructive"}>{agent.status}</Badge>
                    </TableCell>
                    <TableCell className={parseFloat(agent.credit_balance) > 0 ? "text-green-600" : "text-red-600"}>NGN {agent.credit_balance ? parseFloat(agent.credit_balance).toLocaleString() : 0}</TableCell> 
                    <TableCell>{agent.devicesManaged}</TableCell>
                    {activeTab !== "agents" && <TableCell>{agent.agentsManaged}</TableCell>}
                    <TableCell className="text-green-600">NGN {agent.totalSales ? parseFloat(agent.totalSales).toLocaleString() : 0}</TableCell>
                    <TableCell>{agent.totalCustomers}</TableCell>
                    <TableCell>{agent.last_active ? new Date(agent.last_active).toLocaleString() : 'N/A'}</TableCell>
                    <TableCell>
                      <div className="flex items-center space-x-2">
                        <Link href={ activeTab === "agents" ? `/agents/${agent.id}` : `/super-agents/${agent.id}`}>
                          <Button variant="outline" size="sm">
                            View Details
                          </Button>
                        </Link>
                        {activeTab === "super-agents" && (
                          <EditSuperAgentModal superAgent={agent} onUpdate={fetchSuperAgents} />
                        )}
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>
      <Dialog open={!!selectedAgent} onOpenChange={(isOpen) => {
        if (!isOpen) {
          setSelectedAgent(null);
          setIsImageModalOpen(false);
        } else {
          setSelectedAgent(selectedAgent);
        }
      }}>
        <DialogContent className="sm:max-w-[425px]">
          {selectedAgent && (
            <>
              <DialogHeader>
                <DialogTitle>Agent Preview</DialogTitle>
                <CardDescription>Review the details of the pending agent.</CardDescription>
              </DialogHeader>
              <div className="py-4">
                <div className="space-y-4">
                  {selectedAgent.profile_img && (
                    <div className="flex justify-center">
                      <button onClick={() => setIsImageModalOpen(true)}>
                        <img
                          src={`data:image/jpeg;base64,${selectedAgent.profile_img}`}
                          alt="Profile"
                          className="w-32 h-32 rounded-full object-cover border-4 border-white shadow-lg cursor-pointer hover:opacity-80 transition-opacity"
                        />
                      </button>
                    </div>
                  )}
                  <div className="space-y-2 text-center">
                    <h3 className="text-xl font-semibold">{selectedAgent.name}</h3>
                    <p className="text-sm text-muted-foreground">{selectedAgent.id}</p>
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm pt-4">
                    <div className="flex items-center"><User className="mr-2 h-4 w-4 text-muted-foreground" /><span>{selectedAgent.username}</span></div>
                    <div className="flex items-center"><Mail className="mr-2 h-4 w-4 text-muted-foreground" /><span>{selectedAgent.email || 'N/A'}</span></div>
                    <div className="flex items-center"><Phone className="mr-2 h-4 w-4 text-muted-foreground" /><span>{selectedAgent.phone}</span></div>
                    <div className="flex items-center"><CreditCard className="mr-2 h-4 w-4 text-muted-foreground" /><span>{selectedAgent.accountNumber}</span></div>
                    <div className="flex items-center col-span-1 md:col-span-2"><MapPin className="mr-2 h-4 w-4 text-muted-foreground" /><span>{`${selectedAgent.address}, ${selectedAgent.city}, ${selectedAgent.region}`}</span></div>
                    {selectedAgent.landmark && <div className="flex items-center col-span-1 md:col-span-2"><Building className="mr-2 h-4 w-4 text-muted-foreground" /><span>{selectedAgent.landmark}</span></div>}
                    <div className="flex items-center">
                      <Badge variant={selectedAgent.status === "active" ? "success" : selectedAgent.status === "pending" ? "default" : "destructive"}>{selectedAgent.status}</Badge>
                    </div>
                    {selectedAgent.createdAt && <div className="flex items-center"><Calendar className="mr-2 h-4 w-4 text-muted-foreground" /><span>{new Date(selectedAgent.createdAt).toLocaleDateString()}</span></div>}
                  </div>
                </div>
              </div>
              <DialogFooter>
                <Button variant="outline" onClick={() => setSelectedAgent(null)}>Cancel</Button>
                <RejectAgentModal agent={selectedAgent} onAgentRejected={() => {
                  setSelectedAgent(null);
                  setReload(!reload);
                }} />
                <Button onClick={() => {
                  handleApprove(selectedAgent.id);
                  setSelectedAgent(null);
                }}>Approve</Button>
              </DialogFooter>
            </>
          )}
        </DialogContent>
      </Dialog>

      <Dialog open={isImageModalOpen} onOpenChange={setIsImageModalOpen}>
        <DialogContent className="max-w-3xl">
          {selectedAgent && selectedAgent.profile_img && (
            <img
              src={`data:image/jpeg;base64,${selectedAgent.profile_img}`}
              alt="Profile"
              className="w-full h-auto rounded-lg"
            />
          )}
        </DialogContent>
      </Dialog>
    </div>
  )
}
