"use client";

import { useState, useEffect, useRef, useMemo } from "react";
import Image from "next/image";
import { toast } from "react-hot-toast";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "../../../../../../src/components/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "../../../../../../src/components/ui/select";
import {
  Plus,
  Edit,
  Trash2,
  Search,
  ChevronLeft,
  ChevronRight as ChevronRightIcon,
  ArrowUp,
  ArrowDown,
  Eye,
  X,
  ArrowUpDown,
} from "lucide-react";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "../../../../../../src/components/ui/table";
import { createPortal } from "react-dom";
import { Button } from "../../../../../../src/components/ui/button";
import { Label } from "@radix-ui/react-label";
import { Input } from "../../../../../../src/components/ui/input";
import Editor from "../../../../../../src/app/admin/_components/editor/Editor";
import { Badge } from "../../../../../../src/components/ui/badge";
import { Tooltip } from "../../../../../../src/components/ui/tooltip";
import ImagePreviewModal from "../../../../../../src/components/ImagePreview/ImagePreviewer";
import DefaultImage from "@/app/admin/_components/Defaultimage";

interface Banner {
  _id: string;
  banner_title: string;
  banner_slug: string;
  banner_description: string;
  banner_image: string;
  status: boolean;
  createdAt: string;
  updatedAt: string;
}

interface PaginationData {
  page: number;
  limit: number;
  total: number;
  pages: number;
}

const BannerManagement = () => {
  const [banners, setBanners] = useState<Banner[]>([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [sortField, setSortField] = useState<
    "createdAt" | "banner_title" | "status"
  >("createdAt");
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");
  const [pagination, setPagination] = useState<PaginationData>({
    page: 1,
    limit: 10,
    total: 0,
    pages: 0,
  });
  const [viewingBanner, setViewingBanner] = useState<Banner | null>(null);
  const [isViewDialogOpen, setIsViewDialogOpen] = useState(false);

  // Modal states
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [selectedBanner, setSelectedBanner] = useState<Banner | null>(null);
  const [activeIndex, setActiveIndex] = useState(0);
  const [open, setOpen] = useState(false);
  const openPreview = (index: number) => {
    setActiveIndex(index);
    setOpen(true);
  };

  // Form states
  const [formData, setFormData] = useState({
    banner_title: "",
    banner_description: "",
    status: true,
    banner_image: null as File | null,
  });

  const fileInputRef = useRef<HTMLInputElement>(null);
  const editFileInputRef = useRef<HTMLInputElement>(null);

  // Format date function
  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString("en-US", {
      year: "numeric",
      month: "long",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  // Fetch banners
  const fetchBanners = async (
    page = 1,
    search = "",
    status = "all",
    sort = sortField,
    order = sortOrder,
  ) => {
    try {
      setLoading(true);
      const params = new URLSearchParams({
        page: page.toString(),
        limit: pagination.limit.toString(),
        sort: sort,
        order: order,
        ...(search && { search }),
        ...(status !== "all" && { status }),
      });

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

      if (data.success) {
        setBanners(data.data);
        setPagination(data.pagination);
      } else {
        toast.error(data.error || "Failed to fetch banners");
      }
    } catch (error) {
      console.error("Error fetching banners:", error);
      toast.error("Failed to fetch banners");
    } finally {
      setLoading(false);
    }
  };

  const handleLimitChange = (value: string) => {
    const newLimit = parseInt(value);
    setPagination((prev) => ({ ...prev, limit: newLimit, page: 1 }));
    fetchBanners(1, searchTerm, statusFilter, sortField, sortOrder);
  };

  const handleSort = (field: "createdAt" | "banner_title" | "status") => {
    const newOrder =
      sortField === field && sortOrder === "asc" ? "desc" : "asc";
    setSortField(field);
    setSortOrder(newOrder);
    fetchBanners(pagination.page, searchTerm, statusFilter, field, newOrder);
  };

  useEffect(() => {
    fetchBanners();
  }, []);

  // Handle search and filter
  useEffect(() => {
    const timeoutId = setTimeout(() => {
      fetchBanners(1, searchTerm, statusFilter, sortField, sortOrder);
    }, 500);

    return () => clearTimeout(timeoutId);
  }, [searchTerm, statusFilter, sortField, sortOrder]);

  // Handle page change
  const handlePageChange = (page: number) => {
    fetchBanners(page, searchTerm, statusFilter, sortField, sortOrder);
  };

  // Reset form
  const resetForm = () => {
    setFormData({
      banner_title: "",
      banner_description: "",
      status: true,
      banner_image: null,
    });
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
    if (editFileInputRef.current) {
      editFileInputRef.current.value = "";
    }
  };

  // Handle create banner
  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!formData.banner_title.trim()) {
      toast.error("Banner title is required");
      return;
    }

    if (!formData.banner_image) {
      toast.error("Banner image is required");
      return;
    }

    try {
      setSubmitting(true);

      const formDataToSend = new FormData();
      formDataToSend.append("banner_title", formData.banner_title);
      formDataToSend.append("banner_description", formData.banner_description);
      formDataToSend.append("status", formData.status.toString());
      formDataToSend.append("banner_image", formData.banner_image);

      const response = await fetch("/api/banners", {
        method: "POST",
        body: formDataToSend,
      });

      const data = await response.json();

      if (data.success) {
        toast.success("Banner created successfully");
        setShowCreateModal(false);
        resetForm();
        fetchBanners(
          pagination.page,
          searchTerm,
          statusFilter,
          sortField,
          sortOrder,
        );
      } else {
        toast.error(data.error || "Failed to create banner");
      }
    } catch (error) {
      console.error("Error creating banner:", error);
      toast.error("Failed to create banner");
    } finally {
      setSubmitting(false);
    }
  };

  // Handle edit banner
  const handleEdit = async (e: React.FormEvent) => {
    e.preventDefault();
    console.log("Selected", selectedBanner);
    if (!selectedBanner) return;

    if (!formData.banner_title.trim()) {
      toast.error("Banner title is required");
      return;
    }

    try {
      setSubmitting(true);

      const formDataToSend = new FormData();
      formDataToSend.append("banner_title", formData.banner_title);
      formDataToSend.append("banner_description", formData.banner_description);
      formDataToSend.append("status", formData.status.toString());

      if (formData.banner_image) {
        formDataToSend.append("banner_image", formData.banner_image);
      }

      const response = await fetch(`/api/banners/${selectedBanner._id}`, {
        method: "PUT",
        body: formDataToSend,
      });

      const data = await response.json();

      if (data.success) {
        toast.success("Banner updated successfully");
        setShowEditModal(false);
        resetForm();
        fetchBanners(
          pagination.page,
          searchTerm,
          statusFilter,
          sortField,
          sortOrder,
        );
      } else {
        toast.error(data.error || "Failed to update banner");
      }
    } catch (error) {
      console.error("Error updating banner:", error);
      toast.error("Failed to update banner");
    } finally {
      setSubmitting(false);
    }
  };

  // Handle delete banner
  const handleDelete = async () => {
    if (!selectedBanner) return;

    try {
      setSubmitting(true);

      const response = await fetch(`/api/banners/${selectedBanner._id}`, {
        method: "DELETE",
      });

      const data = await response.json();

      if (data.success) {
        toast.success("Banner deleted successfully");
        setShowDeleteModal(false);
        setSelectedBanner(null);
        fetchBanners(
          pagination.page,
          searchTerm,
          statusFilter,
          sortField,
          sortOrder,
        );
      } else {
        toast.error(data.error || "Failed to delete banner");
      }
    } catch (error) {
      console.error("Error deleting banner:", error);
      toast.error("Failed to delete banner");
    } finally {
      setSubmitting(false);
    }
  };

  // Open edit modal
  const openEditModal = (banner: Banner) => {
    console.log("Banner", banner);
    setFormData({
      banner_title: banner.banner_title,
      banner_description: banner.banner_description,
      status: banner.status,
      banner_image: null,
    });
    setSelectedBanner(banner);
    setShowEditModal(true);
  };

  // Open delete modal
  const openDeleteModal = (banner: Banner) => {
    setSelectedBanner(banner);
    setShowDeleteModal(true);
  };

  const handleView = (banner: Banner) => {
    setViewingBanner(banner);
    setIsViewDialogOpen(true);
  };

  // Close modal
  const handleCloseModal = () => {
    setShowEditModal(false);
    setShowCreateModal(false);
    resetForm();
  };

  const previewImages = useMemo(
    () =>
      banners
        .map((item: any) => ({
          src: item.banner_image,
          name: item.banner_title,
        }))
        .filter((i) => typeof i.src === "string" && i.src.trim()),
    [banners],
  );

  return (
    <div className="p-0">
      {/* Header */}
      <div>
        {/* <h4 className="text-xl font-semibold text-black dark:text-white">
            Banner Management
          </h4> */}
        <div className="mb-1 text-sm text-gray-500">
          Total Banners: {pagination.total}
        </div>
      </div>
      {/* View Dialog - Fixed */}
      <Dialog open={isViewDialogOpen} onOpenChange={setIsViewDialogOpen}>
        <DialogContent className="max-w-2xl">
          <div className="mx-auto my-1 flex min-h-[calc(100%-0.5rem)] max-w-lg items-center">
            <div className="relative flex w-full flex-col gap-0 rounded-lg border-0 border-stroke bg-white p-0 text-dark-5 shadow-lg dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
              <DialogHeader>
                <DialogTitle>Banner Details</DialogTitle>
                <X
                  className="h-6 w-6 cursor-pointer p-1 text-white"
                  onClick={() => {
                    setIsViewDialogOpen(false);
                  }}
                />
              </DialogHeader>

              {viewingBanner && (
                <div className="flex flex-1 flex-col p-4 pb-0 pl-2 pr-2">
                  <div className="max-h-[60vh] min-h-[60vh] flex-1 space-y-4 overflow-y-auto pb-4 pl-2 pr-2 pt-2">
                    <div className="space-y-6 pb-4">
                      {/* Banner Image */}
                      {viewingBanner.banner_image ? (
                        <div className="flex justify-center">
                          <img
                            src={viewingBanner.banner_image}
                            alt={viewingBanner.banner_title}
                            className="max-h-64 w-full rounded-lg border-2 border-gray-200 object-cover"
                          />
                        </div>
                      ) : (
                        <DefaultImage />
                      )}

                      <div className="grid grid-cols-2 gap-3">
                        <div className="space-y-0.5">
                          <Label className="text-xs text-gray-500">
                            Banner Title
                          </Label>
                          <p className="text-sm font-medium">
                            {viewingBanner.banner_title}
                          </p>
                        </div>

                        <div className="space-y-0.5">
                          <Label className="text-xs text-gray-500">Slug</Label>
                          <p className="break-all text-sm">
                            {viewingBanner.banner_slug}
                          </p>
                        </div>

                        <div className="space-y-0.5">
                          <Label className="mr-2 text-xs text-gray-500">
                            Status
                          </Label>
                          <Badge
                            variant={
                              viewingBanner.status ? "default" : "secondary"
                            }
                            className="mt-1"
                          >
                            {viewingBanner.status ? "Active" : "Inactive"}
                          </Badge>
                        </div>

                        {viewingBanner.banner_description && (
                          <div className="col-span-2 space-y-0.5">
                            <Label className="text-xs text-gray-500">
                              Description
                            </Label>
                            <div
                              className="prose prose-sm max-h-48 overflow-y-auto whitespace-pre-wrap break-words rounded-md bg-gray-50 p-3 text-sm text-gray-800 dark:bg-[#324153] dark:text-white"
                              dangerouslySetInnerHTML={{
                                __html: viewingBanner.banner_description,
                              }}
                            />
                          </div>
                        )}

                        <div className="col-span-2 pt-2">
                          <div className="grid grid-cols-2 gap-3 border-t pt-2">
                            <div className="space-y-0.5">
                              <Label className="text-xs text-gray-500">
                                Created At
                              </Label>
                              <p className="text-xs text-gray-500">
                                {formatDate(viewingBanner.createdAt)}
                              </p>
                            </div>

                            <div className="space-y-0.5">
                              <Label className="text-xs text-gray-500">
                                Last Updated
                              </Label>
                              <p className="text-xs text-gray-500">
                                {formatDate(viewingBanner.updatedAt)}
                              </p>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>

                  <div className="-mx-2 flex justify-end space-x-3 border-t px-4 pb-3 pt-3">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => {
                        setIsViewDialogOpen(false);
                        openEditModal(viewingBanner);
                      }}
                    >
                      <Edit className="h-4 w-4" />
                      Edit
                    </Button>
                    <Button
                      variant="danger"
                      size="sm"
                      onClick={() => {
                        setIsViewDialogOpen(false);
                        openDeleteModal(viewingBanner);
                      }}
                    >
                      <Trash2 className="h-4 w-4" />
                      Delete
                    </Button>
                  </div>
                </div>
              )}
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* Filters */}
      <div className="flex flex-col gap-4 py-1 pt-0 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex w-full flex-row gap-4 py-1 pt-0 sm:max-w-[700px] sm:items-center">
          <div className="flex-1">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-gray-400" />
              <Input
                type="text"
                placeholder="Search banners..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10"
              />
              <X
                className="absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 cursor-pointer text-gray-400"
                onClick={() => setSearchTerm("")}
              />
            </div>
          </div>

          {/* PAGINATION LIMIT DROPDOWN */}
          <div className="flex items-center gap-2">
            <Label className="whitespace-nowrap text-sm">Show:</Label>
            <select
              value={pagination.limit.toString()}
              onChange={(e) => handleLimitChange(e.target.value)}
              className="border-input focus:ring-ring rounded-md border bg-transparent p-3 text-sm focus:outline-none focus:ring-2 focus:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-[#3B3B3B]"
            >
              <option value="6">6</option>
              <option value="10">10</option>
              <option value="20">20</option>
              <option value="50">50</option>
            </select>
          </div>

          <div className="sm:w-48">
            <select
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
              className="border-input focus:ring-ring rounded-md border bg-transparent p-3 text-sm focus:outline-none focus:ring-2 focus:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-[#3B3B3B]"
            >
              <option value="all">All Status</option>
              <option value="true">Active</option>
              <option value="false">Inactive</option>
            </select>
          </div>
        </div>
        <div className="mb-0 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
          <Dialog
            open={showCreateModal || showEditModal}
            onOpenChange={handleCloseModal}
          >
            <Button
              onClick={() => setShowCreateModal(true)}
              className="inline-flex items-center justify-center rounded-md bg-primary px-4 py-2 text-center font-medium text-white hover:bg-opacity-90"
            >
              <Plus className="h-4 w-4" />
              Add Banner
            </Button>
            <DialogContent className="max-w-2xl">
              <div className="mx-auto my-1 flex min-h-[calc(100%-0.5rem)] max-w-lg items-center">
                <div className="relative flex w-full flex-col gap-0 rounded-lg border-0 border-stroke bg-white p-0 text-dark-5 shadow-lg dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
                  <DialogHeader>
                    <DialogTitle>
                      {showEditModal ? "Edit Banner" : "Add New Banner"}
                    </DialogTitle>
                    <X
                      className="h-6 w-6 cursor-pointer p-1 text-white"
                      onClick={() => {
                        handleCloseModal();
                      }}
                    />
                  </DialogHeader>
                  <form
                    onSubmit={showCreateModal ? handleCreate : handleEdit}
                    className="flex flex-1 flex-col p-4 pb-0 pl-2 pr-2"
                  >
                    <div className="max-h-[60vh] min-h-[60vh] flex-1 space-y-4 overflow-y-auto pb-4 pl-2 pr-2 pt-2">
                      <div className="mb-4">
                        <label className="mb-2.5 block font-medium text-black dark:text-white">
                          Banner Title{" "}
                          <span className="font-bold text-red-600">*</span>
                        </label>
                        <input
                          type="text"
                          value={formData.banner_title}
                          onChange={(e) =>
                            setFormData({
                              ...formData,
                              banner_title: e.target.value,
                            })
                          }
                          className="disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input w-full rounded-lg border-[1.5px] border-stroke bg-transparent px-5 py-3 text-black outline-none transition disabled:cursor-default dark:text-white dark:focus:border-primary"
                          required
                        />
                      </div>

                      <div className="mb-4">
                        <label className="mb-2.5 block font-medium text-black dark:text-white">
                          Description
                        </label>
                        <Editor
                          value={formData.banner_description}
                          onChange={(value: any) =>
                            setFormData({
                              ...formData,
                              banner_description: value,
                            })
                          }
                          rows={3}
                          className="disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input w-full rounded-lg border-[1.5px] border-stroke bg-transparent px-5 py-3 text-black outline-none transition focus:border-primary active:border-primary disabled:cursor-default dark:text-white dark:focus:border-primary"
                        />
                      </div>

                      <div className="mb-4">
                        <label className="mb-2.5 block font-medium text-black dark:text-white">
                          Banner Image <span className="text-red">*</span>
                        </label>
                        <input
                          ref={fileInputRef}
                          type="file"
                          accept="image/*"
                          onChange={(e) =>
                            setFormData({
                              ...formData,
                              banner_image: e.target.files?.[0] || null,
                            })
                          }
                          className="disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input w-full rounded-lg border-[1.5px] border-stroke bg-transparent px-5 py-3 text-black outline-none transition focus:border-primary active:border-primary disabled:cursor-default dark:text-white dark:focus:border-primary"
                          required={!showEditModal}
                        />
                        {showEditModal &&
                          selectedBanner?.banner_image &&
                          !formData.banner_image && (
                            <div className="mt-2">
                              <img
                                src={selectedBanner.banner_image}
                                alt="Current banner"
                                className="h-20 rounded-lg border object-cover"
                              />
                              <p className="mt-1 text-xs text-gray-500">
                                Current image
                              </p>
                            </div>
                          )}
                        {formData.banner_image && (
                          <img
                            src={
                              formData.banner_image instanceof File
                                ? URL.createObjectURL(formData.banner_image)
                                : formData.banner_image
                            }
                            className="mt-3 h-28 rounded-lg border object-cover"
                            alt="Preview"
                          />
                        )}
                      </div>

                      <div className="mb-6">
                        <label className="flex cursor-pointer">
                          <div className="relative">
                            <input
                              type="checkbox"
                              checked={formData.status}
                              onChange={(e) =>
                                setFormData({
                                  ...formData,
                                  status: e.target.checked,
                                })
                              }
                              className="sr-only"
                            />
                            <div
                              className={`block h-6 w-10 rounded-full bg-gray-400 dark:bg-[#5A616B] ${formData.status ? "bg-primary" : ""}`}
                            ></div>
                            <div
                              className={`absolute left-1 top-1 h-4 w-4 rounded-full bg-white transition ${
                                formData.status
                                  ? "!right-1 !translate-x-full !bg-white"
                                  : "bg-green"
                              }`}
                            ></div>
                          </div>
                          <span className="ml-3 text-sm font-medium text-black dark:text-white">
                            {formData?.status ? "Active" : "Inactive"}
                          </span>
                        </label>
                      </div>
                    </div>

                    <div className="-mx-2 flex justify-end space-x-3 border-t px-4 pb-3 pt-3">
                      <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        onClick={handleCloseModal}
                      >
                        Cancel
                      </Button>
                      <button
                        type="submit"
                        disabled={submitting}
                        className="rounded-lg bg-primary px-6 py-2 text-sm font-medium text-white hover:bg-opacity-90 disabled:cursor-not-allowed disabled:opacity-50"
                      >
                        {showEditModal
                          ? submitting
                            ? "Updating..."
                            : "Update Banner"
                          : submitting
                            ? "Creating..."
                            : "Create Banner"}
                      </button>
                    </div>
                  </form>
                </div>
              </div>
            </DialogContent>
          </Dialog>
        </div>
      </div>

      {/* Table */}
      <div className="mt-4 rounded-md">
        <Table className="border bg-white dark:bg-gray-900">
          <TableHeader className="bg-gray-100 dark:bg-gray-800">
            <TableRow className="bg-white hover:bg-gray-50 dark:bg-gray-900 dark:hover:bg-gray-800">
              {/* ID Column with Sort */}
              <TableHead
                className="cursor-pointer text-center hover:bg-gray-50"
                onClick={() => handleSort("createdAt")}
              >
                <div className="flex items-center justify-center gap-2">
                  ID
                  {sortField === "createdAt" ? (
                    sortOrder === "asc" ? (
                      <ArrowUp className="h-4 w-4" />
                    ) : (
                      <ArrowDown className="h-4 w-4" />
                    )
                  ) : (
                    <ArrowUpDown className="h-4 w-4 text-gray-400" />
                  )}
                </div>
              </TableHead>

              <TableHead
                className="cursor-pointer hover:bg-gray-50"
                onClick={() => handleSort("banner_title")}
              >
                <div className="flex items-center gap-2">
                  Page
                  {sortField === "banner_title" ? (
                    sortOrder === "asc" ? (
                      <ArrowUp className="h-4 w-4" />
                    ) : (
                      <ArrowDown className="h-4 w-4" />
                    )
                  ) : (
                    <ArrowUpDown className="h-4 w-4 text-gray-400" />
                  )}
                </div>
              </TableHead>

              <TableHead>Banner</TableHead>

              {/* Status Column with Sort */}
              <TableHead
                className="cursor-pointer hover:bg-gray-50"
                onClick={() => handleSort("status")}
              >
                <div className="flex items-center gap-2">
                  Status
                  {sortField === "status" ? (
                    sortOrder === "asc" ? (
                      <ArrowUp className="h-4 w-4" />
                    ) : (
                      <ArrowDown className="h-4 w-4" />
                    )
                  ) : (
                    <ArrowUpDown className="h-4 w-4 text-gray-400" />
                  )}
                </div>
              </TableHead>

              <TableHead>Created</TableHead>
              <TableHead>Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading ? (
              <TableRow className="bg-white hover:bg-gray-50 dark:bg-gray-900 dark:hover:bg-gray-800">
                <TableCell colSpan={6} className="px-4 py-8 text-center">
                  <div className="flex items-center justify-center">
                    <div className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"></div>
                    <span className="ml-2">Loading...</span>
                  </div>
                </TableCell>
              </TableRow>
            ) : banners.length === 0 ? (
              <TableRow>
                <TableCell
                  colSpan={6}
                  className="px-4 py-8 text-center text-gray-500"
                >
                  No banners found
                </TableCell>
              </TableRow>
            ) : (
              banners.map((banner, index) => (
                <TableRow
                  key={banner._id}
                  className="bg-white hover:bg-gray-50 dark:bg-gray-900 dark:hover:bg-gray-800"
                >
                  <TableCell className="dark:border-strokedark border-b border-[#eee] px-4 py-5 text-center">
                    {sortField === "createdAt" && sortOrder === "asc"
                      ? pagination.total -
                        (pagination.page - 1) * pagination.limit -
                        index
                      : (pagination.page - 1) * pagination.limit + index + 1}
                  </TableCell>
                  <TableCell className="dark:border-strokedark border-b border-[#eee] px-4 py-5">
                    <p className="text-black dark:text-white">
                      {banner.banner_title}
                    </p>
                  </TableCell>
                  <TableCell className="dark:border-strokedark border-b border-[#eee] px-4 py-5 pl-9 xl:pl-11">
                    <div className="flex items-center gap-3">
                      <div className="h-12 w-12 overflow-hidden rounded-lg">
                        <img
                          src={banner.banner_image}
                          alt={banner.banner_title}
                          width={48}
                          height={48}
                          className="h-full w-full cursor-pointer object-cover"
                          onClick={() => openPreview(index)}
                        />
                      </div>
                    </div>
                  </TableCell>

                  <TableCell className="dark:border-strokedark border-b border-[#eee] px-4 py-5">
                    <Badge variant={banner.status ? "default" : "outline"}>
                      {banner.status ? "Active" : "Inactive"}
                    </Badge>
                  </TableCell>
                  <TableCell className="dark:border-strokedark border-b border-[#eee] px-4 py-5">
                    <p className="text-black dark:text-white">
                      {new Date(banner.createdAt).toLocaleDateString()}
                    </p>
                  </TableCell>
                  <TableCell className="dark:border-strokedark border-b border-[#eee] px-4 py-5">
                    <div className="flex items-center space-x-3.5">
                      <Tooltip text="View">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleView(banner)}
                        >
                          <Eye className="h-4 w-4" />
                        </Button>
                      </Tooltip>
                      <Tooltip text="Edit">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => openEditModal(banner)}
                          className="hover:text-primary"
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                      </Tooltip>
                      <Tooltip text="Delete">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => openDeleteModal(banner)}
                          className="hover:text-red-500"
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </Tooltip>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {open && (
        <ImagePreviewModal
          images={previewImages}
          activeIndex={activeIndex}
          setActiveIndex={setActiveIndex}
          onClose={() => setOpen(false)}
        />
      )}

      {/* Pagination */}
      {pagination.pages > 1 && (
        <div className="mt-4 flex items-center justify-between">
          <div className="text-sm text-gray-500">
            Showing {(pagination.page - 1) * pagination.limit + 1} to{" "}
            {Math.min(pagination.page * pagination.limit, pagination.total)} of{" "}
            {pagination.total} entries
          </div>
          <div className="flex items-center space-x-2">
            <Button
              variant="default"
              onClick={() => handlePageChange(pagination.page - 1)}
              disabled={pagination.page === 1}
              className="dark:border-strokedark rounded-lg border border-stroke px-3 py-2 text-sm font-medium text-black hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-50 dark:text-white"
            >
              <ChevronLeft className="h-4 w-4" />
              Previous
            </Button>
            {Array.from({ length: pagination.pages }, (_, i) => i + 1).map(
              (page) => (
                <Button
                  variant="default"
                  key={page}
                  onClick={() => handlePageChange(page)}
                  className={`rounded-lg border px-3 py-2 text-sm font-medium ${
                    page === pagination.page
                      ? "border-primary bg-primary text-white"
                      : "dark:border-strokedark border-stroke text-black hover:bg-gray-50 dark:text-white"
                  }`}
                >
                  {page}
                </Button>
              ),
            )}
            <button
              onClick={() => handlePageChange(pagination.page + 1)}
              disabled={pagination.page === pagination.pages}
              className="dark:border-strokedark rounded-lg border border-stroke px-3 py-2 text-sm font-medium text-black hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-50 dark:text-white"
            >
              Next
              <ChevronRightIcon className="h-4 w-4" />
            </button>
          </div>
        </div>
      )}

      {/* Delete Modal */}
      {showDeleteModal &&
        selectedBanner &&
        createPortal(
          <div className="fixed inset-0 z-[9999] flex items-center justify-center bg-black bg-opacity-50">
            <div className="dark:bg-boxdark z-[10000] w-full max-w-md rounded-lg bg-white p-6">
              <div className="mb-4">
                <h3 className="text-lg font-semibold text-gray-600 dark:text-black">
                  Delete Banner
                </h3>
              </div>

              <p className="mb-6 text-sm text-gray-600 dark:text-black">
                Are you sure you want to delete the banner "
                {selectedBanner.banner_title}"? This action cannot be undone.
              </p>

              <div className="flex justify-end space-x-3">
                <button
                  onClick={() => {
                    setShowDeleteModal(false);
                    setSelectedBanner(null);
                  }}
                  className="dark:border-strokedark rounded-lg border border-stroke px-6 py-2 text-sm font-medium text-black hover:bg-gray-50 dark:text-black"
                >
                  Cancel
                </button>
                <button
                  onClick={handleDelete}
                  disabled={submitting}
                  className="rounded-lg bg-red-500 px-6 py-2 text-sm font-medium text-white hover:bg-red-600 disabled:cursor-not-allowed disabled:opacity-50"
                >
                  {submitting ? "Deleting..." : "Delete Banner"}
                </button>
              </div>
            </div>
          </div>,
          document.body,
        )}
    </div>
  );
};

export default BannerManagement;
