"use client";

import { useState, useEffect } from "react";
import { Button } from "../../../../../src/components/ui/button";
import { Input } from "../../../../../src/components/ui/input";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "../../../../../src/components/ui/table";
import { 
  Eye, 
  Search, 
  ChevronLeft, 
  ChevronRight,
  ArrowUp,
  ArrowDown,
  ArrowUpDown,
  X,
  MapPin,
  Phone,
  Calendar,
  User,
  Home,
  Map
} from "lucide-react";
import { toast } from "sonner";
import { useDebounce } from "../../../../../src/hooks/useDebounce";
import ExportExcel from "@/components/ui-elements/ExportExcel";
import * as XLSX from "xlsx";

interface Lead {
  _id: string;
  name: string;
  phone_number: string;
  state?: string | { _id: string; name: string; code?: string; country?: string };
  city?: string;
  address?: string;
  createdAt: string;
  pincode?: string;
  email?: string;
}

type SortField = "name" | "phone_number" | "createdAt";

export default function LeadsManagement() {
  const [leads, setLeads] = useState<Lead[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const debouncedSearch = useDebounce(search, 400);

  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(10);

  const [pagination, setPagination] = useState({
    total: 0,
    pages: 0,
    page: 1,
    limit: 10,
  });

  const [isViewOpen, setIsViewOpen] = useState(false);
  const [viewing, setViewing] = useState<Lead | null>(null);

  const [sortField, setSortField] = useState<SortField>("createdAt");
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");

  useEffect(() => {
    fetchLeads();
  }, [debouncedSearch, page, limit, sortField, sortOrder]);

  const fetchLeads = async () => {
    try {
      setLoading(true);

      const params = new URLSearchParams({
        page: page.toString(),
        limit: limit.toString(),
        ...(debouncedSearch && { search: debouncedSearch }),
        sort: sortField,
        order: sortOrder,
      });

      const res = await fetch(`/api/leads?${params}`);
      const data = await res.json();

      if (data.success) {
        setLeads(data.data || []);
        setPagination(
          data.pagination || {
            total: 0,
            pages: 0,
            page,
            limit,
          }
        );
      } else {
        toast.error(data.error || "Failed to load leads");
      }
    } catch (err) {
      console.error(err);
      toast.error("Error fetching leads");
    } finally {
      setLoading(false);
    }
  };

  const handlePageChange = (newPage: number) => {
    setPage(newPage);
  };

  const handleSort = (field: SortField) => {
    if (sortField === field) {
      setSortOrder(sortOrder === "asc" ? "desc" : "asc");
    } else {
      setSortField(field);
      setSortOrder(field === "createdAt" ? "desc" : "asc");
    }
    setPage(1);
  };

  const getSortIcon = (field: SortField) => {
    if (sortField !== field) {
      return <ArrowUpDown className="h-4 w-4 text-gray-400" />;
    }
    return sortOrder === "asc" ? (
      <ArrowUp className="h-4 w-4" />
    ) : (
      <ArrowDown className="h-4 w-4" />
    );
  };

  const getFullAddress = (lead: Lead) => {
    const parts = [];
    if (lead.address) parts.push(lead.address);
    if (lead.city) parts.push(lead.city);
    const stateName = typeof lead.state === 'object' ? lead.state?.name : lead.state;
    if (stateName) parts.push(stateName);
    if (lead.pincode) parts.push(lead.pincode);
    return parts.join(", ");
  };

  const getMapEmbedUrl = (lead: Lead) => {
    const fullAddress = getFullAddress(lead);
    if (!fullAddress) return "https://www.google.com/maps?q=India&output=embed";
    const encodedAddress = encodeURIComponent(fullAddress);
    // Using Google Maps embed without API key requirement
    return `https://www.google.com/maps?q=${encodedAddress}&output=embed`;
  };

  const openInGoogleMaps = (lead: Lead) => {
    const fullAddress = getFullAddress(lead);
    if (fullAddress) {
      const encodedAddress = encodeURIComponent(fullAddress);
      window.open(`https://www.google.com/maps/search/?api=1&query=${encodedAddress}`, "_blank");
    }
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleString("en-IN", {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  

  const downloadExcel = async () => {
    setLoading(true)
    try {    
      const params = new URLSearchParams({
        page: '1',
        limit: '1000',
        ...(debouncedSearch && { search: debouncedSearch }),
        sort: 'createdAt',
        order: 'desc',
      });

      const res = await fetch(`/api/leads?${params}`);
      const data = await res.json();

      if (data.success) {
        const modData = data?.data?.map((dt: any) => ({
          name: dt.name,
          phone: dt?.phone_number || '',
          address: dt?.address || '',
          createdAt: dt?.createdAt ? formatDate(dt.createdAt) : ''
        }))
        // Convert JSON to worksheet
        const worksheet = XLSX.utils.json_to_sheet(modData);

        // Create workbook
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, "Leads");

        // Download file
        XLSX.writeFile(workbook, "leads.xlsx");
        toast.success('Excel downloaded successfully')
      }
    } catch(error) {
      console.error('Error fetching data', error)
    } finally {
      setLoading(false)
    }
  };

  return (
    <div className="space-y-6">
      {/* SEARCH AND FILTERS */}
      <div className="flex flex-col sm:flex-row gap-4">
        <div className="relative flex-1 max-w-sm">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 h-4 w-4" />
          <Input
            placeholder="Search by name or phone..."
            value={search}
            onChange={(e) => {
              setSearch(e.target.value);
              setPage(1);
            }}
            className="pl-10"
          />
        </div>

        <select
          value={limit}
          onChange={(e) => {
            setLimit(Number(e.target.value));
            setPage(1);
          }}
          className="px-3 py-2.5 rounded-md border"
        >
          <option value={6}>6</option>
          <option value={10}>10</option>
          <option value={20}>20</option>
          <option value={50}>50</option>
        </select>

        <div className="flex items-center ml-auto">
          <ExportExcel downloadExcel={downloadExcel} loading={loading} />
        </div>
      </div>

      {/* TABLE */}
      <div className="rounded-md border overflow-x-auto">
        <Table>
          <TableHeader className="dark:bg-gray-800">
            <TableRow>
              <TableHead 
                className="text-center cursor-pointer"
                onClick={() => handleSort("createdAt")}
              >
                <div className="flex items-center justify-center gap-2">
                  ID
                  {getSortIcon("createdAt")}
                </div>
              </TableHead>
              
              <TableHead 
                className="text-center cursor-pointer"
                onClick={() => handleSort("name")}
              >
                <div className="flex items-center gap-2">
                  Name
                  {getSortIcon("name")}
                </div>
              </TableHead>
              
              <TableHead 
                className="text-center cursor-pointer"
                onClick={() => handleSort("phone_number")}
              >
                <div className="flex items-center gap-2">
                  Phone Number
                  {getSortIcon("phone_number")}
                </div>
              </TableHead>
              
              {/* <TableHead>State</TableHead>
              <TableHead>City</TableHead> */}
              <TableHead>Address</TableHead>
              <TableHead className="text-center">Created At</TableHead>
              <TableHead className="text-center">Actions</TableHead>
            </TableRow>
          </TableHeader>

          <TableBody className="dark:bg-gray-800">
            {loading ? (
              <TableRow className='bg-white dark:bg-gray-900 hover:bg-gray-50 dark:hover:bg-gray-800'>
                <TableCell colSpan={6} className="text-center py-8">
                  Loading...
                </TableCell>
              </TableRow>
            ) : leads.length === 0 ? (
              <TableRow className='bg-white dark:bg-gray-900 hover:bg-gray-50 dark:hover:bg-gray-800'>
                <TableCell colSpan={6} className="text-center py-8">
                  No leads found
                </TableCell>
              </TableRow>
            ) : (
              leads.map((l, index) => (
                <TableRow key={l._id} className='bg-white dark:bg-gray-900 hover:bg-gray-50 dark:hover:bg-gray-800'>
                  <TableCell className="text-center">
                    {(page - 1) * limit + index + 1}
                  </TableCell>
                  <TableCell className="font-medium">{l.name}</TableCell>
                  <TableCell>{l.phone_number}</TableCell>
                  {/* <TableCell>{typeof l.state === 'object' ? l.state?.name : l.state}</TableCell> */}
                  {/* <TableCell>{l.city || "-"}</TableCell> */}
                  <TableCell className="max-w-xs truncate">{l.address || "-"}</TableCell>
                  <TableCell className="text-center">
                    {formatDate(l.createdAt)}
                  </TableCell>
                  <TableCell className="text-center">
                    <Button
                      size="sm"
                      variant="ghost"
                      onClick={() => {
                        setViewing(l);
                        setIsViewOpen(true);
                      }}
                    >
                      <Eye className="w-4 h-4" />
                    </Button>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {/* PAGINATION */}
      {pagination.pages > 1 && (
        <div className="mt-4 flex items-center justify-between flex-wrap gap-4">
          <div className="text-sm text-gray-500">
            Showing {(page - 1) * limit + 1} to{" "}
            {Math.min(page * limit, pagination.total)} of {pagination.total}
          </div>

          <div className="flex items-center gap-2">
            <Button
              variant="default"
              size="sm"
              onClick={() => handlePageChange(page - 1)}
              disabled={page === 1}
            >
              <ChevronLeft className="h-4 w-4" />
              Previous
            </Button>

            <span className="text-sm">
              Page {page} of {pagination.pages}
            </span>

            <Button
              variant="default"
              size="sm"
              onClick={() => handlePageChange(page + 1)}
              disabled={page === pagination.pages}
            >
              Next
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      )}

      {/* VIEW MODAL */}
      {isViewOpen && viewing && (
        <div className="fixed inset-0 z-50 overflow-y-auto">
          {/* Overlay */}
          <div 
            className="fixed inset-0 bg-black bg-opacity-50 transition-opacity"
            onClick={() => setIsViewOpen(false)}
          />

          {/* Modal */}
          <div className="relative min-h-screen flex items-center justify-center p-4">
            <div className="relative bg-white rounded-xl shadow-xl max-w-4xl w-full max-h-[90vh] overflow-y-auto">
              {/* Header */}
              <div className="sticky top-0 bg-white border-b px-6 py-4 flex justify-between items-center">
                <h2 className="text-xl font-semibold text-gray-800">Lead Details</h2>
                <button
                  onClick={() => setIsViewOpen(false)}
                  className="p-2 hover:bg-gray-100 rounded-full transition"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>

              {/* Content */}
              <div className="p-6">
                <div className="grid md:grid-cols-2 gap-6">
                  {/* Left Column - Lead Information */}
                  <div className="space-y-4">
                    <h3 className="text-lg font-semibold text-gray-700 border-b pb-2">
                      Personal Information
                    </h3>
                    
                    {/* Name */}
                    <div className="flex items-start gap-3">
                      <User className="w-5 h-5 text-primary mt-0.5" />
                      <div>
                        <p className="text-sm text-gray-500">Full Name</p>
                        <p className="font-medium text-gray-800">{viewing.name}</p>
                      </div>
                    </div>

                    {/* Phone */}
                    <div className="flex items-start gap-3">
                      <Phone className="w-5 h-5 text-primary mt-0.5" />
                      <div>
                        <p className="text-sm text-gray-500">Phone Number</p>
                        <p className="font-medium text-gray-800">
                          <a href={`tel:${viewing.phone_number}`} className="hover:text-primary">
                            {viewing.phone_number}
                          </a>
                        </p>
                      </div>
                    </div>

                    {/* Email (if available) */}
                    {viewing.email && (
                      <div className="flex items-start gap-3">
                        {/* <Mail className="w-5 h-5 text-primary mt-0.5" /> */}
                        <div>
                          <p className="text-sm text-gray-500">Email Address</p>
                          <p className="font-medium text-gray-800">
                            <a href={`mailto:${viewing.email}`} className="hover:text-primary">
                              {viewing.email}
                            </a>
                          </p>
                        </div>
                      </div>
                    )}

                    {/* Created At */}
                    <div className="flex items-start gap-3">
                      <Calendar className="w-5 h-5 text-primary mt-0.5" />
                      <div>
                        <p className="text-sm text-gray-500">Submitted On</p>
                        <p className="font-medium text-gray-800">{formatDate(viewing.createdAt)}</p>
                      </div>
                    </div>

                    {/* Address Section */}
                    <div className="pt-4">
                      <h3 className="text-lg font-semibold text-gray-700 border-b pb-2 mb-3">
                        Address Details
                      </h3>
                      
                      {/* Address */}
                      {(viewing.address || viewing.city || viewing.state || viewing.pincode) && (
                        <div className="flex items-start gap-3 mb-3">
                          <Home className="w-5 h-5 text-primary mt-0.5" />
                          <div>
                            <p className="text-sm text-gray-500">Complete Address</p>
                            <p className="font-medium text-gray-800">{getFullAddress(viewing)}</p>
                          </div>
                        </div>
                      )}

                      {/* City */}
                      {viewing.city && (
                        <div className="flex items-start gap-3 mb-2 ml-8">
                          <div>
                            <p className="text-sm text-gray-500">City</p>
                            <p className="text-gray-800">{viewing.city}</p>
                          </div>
                        </div>
                      )}

                      {/* State */}
                      {(typeof viewing.state === 'object' ? viewing.state?.name : viewing.state) && (
                        <div className="flex items-start gap-3 mb-2 ml-8">
                          <div>
                            <p className="text-sm text-gray-500">State</p>
                            <p className="text-gray-800">
                              {typeof viewing.state === 'object' ? viewing.state?.name : viewing.state}
                            </p>
                          </div>
                        </div>
                      )}

                      {/* Pincode */}
                      {viewing.pincode && (
                        <div className="flex items-start gap-3 mb-2 ml-8">
                          <div>
                            <p className="text-sm text-gray-500">Pincode</p>
                            <p className="text-gray-800">{viewing.pincode}</p>
                          </div>
                        </div>
                      )}
                    </div>
                  </div>

                  {/* Right Column - Map */}
                  <div className="space-y-4">
                    <div className="flex items-center justify-between">
                      <h3 className="text-lg font-semibold text-gray-700 border-b pb-2">
                        Location Map
                      </h3>
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => openInGoogleMaps(viewing)}
                        className="gap-2"
                      >
                        <Map className="w-4 h-4" />
                        Open in Google Maps
                      </Button>
                    </div>
                    
                    {/* Map Iframe */}
                    <div className="rounded-lg overflow-hidden border shadow-sm">
                      <iframe
                        src={getMapEmbedUrl(viewing)}
                        width="100%"
                        height="400"
                        style={{ border: 0 }}
                        allowFullScreen
                        loading="lazy"
                        referrerPolicy="no-referrer-when-downgrade"
                        title={`Map location for ${viewing.name}`}
                        className="w-full"
                      />
                    </div>
                    
                    {!viewing.address && !viewing.city && !viewing.state && (
                      <p className="text-sm text-gray-500 text-center mt-2">
                        No address information available to display on map.
                      </p>
                    )}
                  </div>
                </div>

                {/* Action Buttons */}
                <div className="flex justify-end gap-3 mt-6 pt-4 border-t">
                  <Button
                    variant="outline"
                    onClick={() => setIsViewOpen(false)}
                  >
                    Close
                  </Button>
                  {viewing.phone_number && (
                    <Button
                      onClick={() => window.open(`tel:${viewing.phone_number}`)}
                      className="gap-2"
                    >
                      <Phone className="w-4 h-4" />
                      Call Lead
                    </Button>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}