"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,
  DialogTrigger,
} from "../../../../../../src/components/ui/dialog";
import {
  Plus,
  X,
  Edit,
  Trash2,
  Search,
  ChevronLeft,
  ChevronRight as ChevronRightIcon,
  Eye,
  ArrowUp,
  ArrowDown,
  ArrowUpDown,
} from "lucide-react";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "../../../../../../src/components/ui/table";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "../../../../../../src/components/ui/select";
import { Label } from "@radix-ui/react-label";
import { Input } from "../../../../../../src/components/ui/input";
import Editor from "../../../../../../src/app/admin/_components/editor/Editor";
import { Tooltip } from "../../../../../../src/components/ui/tooltip";
import { createPortal } from "react-dom";
import { Button } from "../../../../../../src/components/ui/button";
import ImagePreviewModal from "../../../../../../src/components/ImagePreview/ImagePreviewer";
import { Badge } from "@/components/ui/badge";
import DefaultImage from "@/app/admin/_components/Defaultimage";

interface CMSPage {
  _id: string;
  title: string;
  slug: string;
  content: string;
  featured_image?: string;
  meta_title?: string;
  meta_keywords?: string[];
  status: boolean;
  createdAt: string;
  updatedAt: string;
}

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

const CMSManagement = () => {
  const [cmsPages, setCmsPages] = useState<CMSPage[]>([]);
  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" | "title" | "status">(
    "createdAt",
  );
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");
  const [pagination, setPagination] = useState<PaginationData>({
    page: 1,
    limit: 10,
    total: 0,
    pages: 0,
  });
  const [showViewModal, setShowViewModal] = useState(false);

  // Modal states
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [selectedPage, setSelectedPage] = useState<CMSPage | 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({
    title: "",
    content: "",
    meta_title: "",
    meta_keywords: "",
    status: true,
    featured_image: null as File | null,
    existing_image: "", // Store existing image URL
  });

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

  // Fetch CMS pages
  const fetchCMSPages = 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/cms?${params}`);
      const data = await response.json();

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

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

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

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

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

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

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

  // Reset form
  const resetForm = () => {
    setFormData({
      title: "",
      content: "",
      meta_title: "",
      meta_keywords: "",
      status: true,
      featured_image: null,
      existing_image: "",
    });
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
    if (editFileInputRef.current) {
      editFileInputRef.current.value = "";
    }
  };

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

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

    if (!formData.content.trim()) {
      toast.error("Content is required");
      return;
    }

    try {
      setSubmitting(true);

      const formDataToSend = new FormData();
      formDataToSend.append("title", formData.title);
      formDataToSend.append("content", formData.content);
      formDataToSend.append("meta_title", formData.meta_title);
      formDataToSend.append("meta_keywords", formData.meta_keywords);
      formDataToSend.append("status", formData.status.toString());

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

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

      const data = await response.json();

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

  // Handle edit CMS page
  const handleEdit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!selectedPage) return;

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

    if (!formData.content.trim()) {
      toast.error("Content is required");
      return;
    }

    try {
      setSubmitting(true);

      const formDataToSend = new FormData();
      formDataToSend.append("title", formData.title);
      formDataToSend.append("content", formData.content);
      formDataToSend.append("meta_title", formData.meta_title);
      formDataToSend.append("meta_keywords", formData.meta_keywords);
      formDataToSend.append("status", formData.status.toString());

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

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

      const data = await response.json();

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

  // Handle delete CMS page
  const handleDelete = async () => {
    if (!selectedPage) return;

    try {
      setSubmitting(true);

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

      const data = await response.json();

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

  // Open edit modal - FIXED: Use setShowEditModal instead of setShowCreateModal
  const handleEditModal = (page: CMSPage | null) => {
    if (!page) return;
    setSelectedPage(page);
    setFormData({
      title: page.title,
      content: page.content,
      meta_title: page.meta_title || "",
      meta_keywords: page.meta_keywords?.join(", ") || "",
      status: page.status,
      featured_image: null,
      existing_image: page.featured_image || "",
    });
    setShowEditModal(true); // FIXED: Set edit modal, not create modal
    // setNoneditable(false);
  };

  // Open view modal (readonly)
  const handleViewModal = (page: CMSPage) => {
    setSelectedPage(page);
    setShowViewModal(true);
  };

  // Open create modal
  const handleCreateModal = () => {
    resetForm();
    setSelectedPage(null);
    setShowCreateModal(true);
    // setNoneditable(false);
  };

  // Open delete modal
  const openDeleteModal = (page: CMSPage) => {
    setSelectedPage(page);
    setShowDeleteModal(true);
  };

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

  return (
    <div className="rounded-sm">
      {/* 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 CMS: {pagination.total}
        </div>
      </div>
      {/* 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 CMS pages..."
                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>
          <div className="sm:w-48">
            <select
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
              className="dark:border-form-strokedark dark:bg-form-input w-full rounded-lg border-[1.5px] border-stroke bg-transparent px-3 py-2.5 text-black outline-none transition focus:border-primary active:border-primary dark:bg-[#3B3B3B] dark:text-white dark:focus:border-primary"
            >
              <option value="all">All Status</option>
              <option value="true">Published</option>
              <option value="false">Draft</option>
            </select>
          </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 px-3 py-2.5 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>
        <div className="flex items-center justify-between py-3">
          <Dialog open={showCreateModal} onOpenChange={setShowCreateModal}>
            <DialogTrigger asChild>
              <button
                onClick={handleCreateModal}
                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 CMS Page
              </button>
            </DialogTrigger>
            <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>Add New CMS Page</DialogTitle>
                    <X
                      className="h-6 w-6 cursor-pointer p-1 text-white"
                      onClick={() => {
                        setShowCreateModal(false);
                      }}
                    />
                  </DialogHeader>

                  <form
                    id="createForm"
                    onSubmit={handleCreate}
                    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-3">
                        <label className="mb-2 block font-medium">
                          Page Title{" "}
                          <span className="font-bold text-red-600">*</span>
                        </label>
                        <input
                          type="text"
                          value={formData.title}
                          onChange={(e) =>
                            setFormData({ ...formData, title: e.target.value })
                          }
                          className="w-full rounded-lg border px-4 py-2"
                          required
                        />
                      </div>

                      <div className="mb-3">
                        <label className="mb-2 block font-medium">
                          Content{" "}
                          <span className="font-bold text-red-600">*</span>
                        </label>
                        <Editor
                          value={formData.content}
                          onChange={(value: any) =>
                            setFormData({ ...formData, content: value })
                          }
                          rows={6}
                          className="w-full rounded-lg border px-4 py-2"
                        />
                      </div>

                      <div className="mb-3">
                        <label className="mb-2 block font-medium">
                          Featured Image
                        </label>
                        <input
                          type="file"
                          accept="image/*"
                          onChange={(e) => {
                            const file = e.target.files?.[0] || null;
                            setFormData({ ...formData, featured_image: file });
                          }}
                          className="w-full rounded-lg border px-4 py-2"
                        />
                        {formData.featured_image && (
                          <img
                            src={URL.createObjectURL(formData.featured_image)}
                            className="mt-3 h-32 rounded-lg border object-cover"
                            alt="Preview"
                          />
                        )}
                      </div>

                      <div className="mb-3 grid grid-cols-2 gap-4">
                        <input
                          type="text"
                          placeholder="Meta Title"
                          value={formData.meta_title}
                          onChange={(e) =>
                            setFormData({
                              ...formData,
                              meta_title: e.target.value,
                            })
                          }
                          className="rounded-lg border px-4 py-2"
                        />
                        <input
                          type="text"
                          placeholder="Meta Keywords (comma separated)"
                          value={formData.meta_keywords}
                          onChange={(e) =>
                            setFormData({
                              ...formData,
                              meta_keywords: e.target.value,
                            })
                          }
                          className="rounded-lg border px-4 py-2"
                        />
                      </div>
                      <div className="mb-3 flex items-center justify-between">
                        <span>Published</span>
                        <input
                          type="checkbox"
                          checked={formData.status}
                          onChange={(e) =>
                            setFormData({
                              ...formData,
                              status: e.target.checked,
                            })
                          }
                        />
                      </div>
                    </div>

                    <div className="-mx-2 flex justify-end space-x-3 border-t px-4 pb-3 pt-3">
                      <button
                        type="button"
                        onClick={() => {
                          setShowCreateModal(false);
                          resetForm();
                        }}
                        className="rounded-lg border px-5 py-2"
                      >
                        Cancel
                      </button>
                      <button
                        onClick={handleCreate}
                        disabled={submitting}
                        className="rounded-lg bg-primary px-5 py-2 text-white"
                      >
                        {submitting ? "Saving..." : "Save"}
                      </button>
                    </div>
                  </form>
                </div>
              </div>
            </DialogContent>
          </Dialog>

          {/* Edit Modal */}
          <Dialog open={showEditModal} onOpenChange={setShowEditModal}>
            <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>Edit CMS Page</DialogTitle>
                    <X
                      className="h-6 w-6 cursor-pointer p-1 text-white"
                      onClick={() => {
                        setShowEditModal(false);
                      }}
                    />
                  </DialogHeader>
                  <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">
                      <form
                        id="editForm"
                        onSubmit={handleEdit}
                        className="space-y-3"
                      >
                        <div>
                          <label className="mb-2 block font-medium">
                            Page Title{" "}
                            <span className="font-bold text-red-600">*</span>
                          </label>
                          <input
                            type="text"
                            value={formData.title}
                            onChange={(e) =>
                              setFormData({
                                ...formData,
                                title: e.target.value,
                              })
                            }
                            className="w-full rounded-lg border px-4 py-2"
                            required
                          />
                        </div>

                        <div>
                          <label className="mb-2 block font-medium">
                            Content{" "}
                            <span className="font-bold text-red-600">*</span>
                          </label>
                          <Editor
                            value={formData.content}
                            onChange={(value: any) =>
                              setFormData({ ...formData, content: value })
                            }
                            rows={6}
                            className="w-full rounded-lg border px-4 py-2"
                          />
                        </div>

                        <div>
                          <label className="mb-2 block font-medium">
                            Featured Image
                          </label>
                          {formData.existing_image &&
                            !formData.featured_image && (
                              <div className="mb-3">
                                <img
                                  src={formData.existing_image}
                                  alt="Current"
                                  className="h-32 rounded-lg border object-cover"
                                />
                                <p className="mt-1 text-xs text-gray-500">
                                  Current image
                                </p>
                              </div>
                            )}
                          <input
                            type="file"
                            accept="image/*"
                            onChange={(e) => {
                              const file = e.target.files?.[0] || null;
                              setFormData({
                                ...formData,
                                featured_image: file,
                              });
                            }}
                            className="w-full rounded-lg border px-4 py-2"
                          />
                          {formData.featured_image && (
                            <img
                              src={URL.createObjectURL(formData.featured_image)}
                              className="mt-3 h-32 rounded-lg border object-cover"
                              alt="Preview"
                            />
                          )}
                        </div>

                        <div className="grid grid-cols-2 gap-4">
                          <input
                            type="text"
                            placeholder="Meta Title"
                            value={formData.meta_title}
                            onChange={(e) =>
                              setFormData({
                                ...formData,
                                meta_title: e.target.value,
                              })
                            }
                            className="rounded-lg border px-4 py-2"
                          />
                          <input
                            type="text"
                            placeholder="Meta Keywords (comma separated)"
                            value={formData.meta_keywords}
                            onChange={(e) =>
                              setFormData({
                                ...formData,
                                meta_keywords: e.target.value,
                              })
                            }
                            className="rounded-lg border px-4 py-2"
                          />
                        </div>

                        <div className="flex items-center justify-between">
                          <span>Published</span>
                          <input
                            type="checkbox"
                            checked={formData.status}
                            onChange={(e) =>
                              setFormData({
                                ...formData,
                                status: e.target.checked,
                              })
                            }
                          />
                        </div>
                      </form>
                    </div>

                    <div className="-mx-2 flex justify-end space-x-3 border-t px-4 pb-3 pt-3">
                      {/* {noneditable && <Button
                      variant="outline"
                      onClick={() => {
                        setNoneditable(true);
                        handleEditModal(selectedPage);
                      }}
                    >
                      <Edit className="w-4 h-4" />
                      Edit
                    </Button>} */}
                      <button
                        type="button"
                        onClick={() => {
                          setShowEditModal(false);
                          resetForm();
                          setSelectedPage(null);
                        }}
                        className="rounded-lg border px-4 py-1.5"
                      >
                        Cancel
                      </button>

                      <button
                        onClick={handleEdit}
                        disabled={submitting}
                        className="rounded-lg bg-primary px-4 py-1.5 text-white"
                      >
                        {submitting ? "Updating..." : "Update"}
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </DialogContent>
          </Dialog>
          {/* View Modal */}
          <Dialog open={showViewModal} onOpenChange={setShowViewModal}>
            <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>CMS Page Details</DialogTitle>

                    <X
                      className="h-6 w-6 cursor-pointer p-1 text-white"
                      onClick={() => {
                        setShowViewModal(false);
                      }}
                    />
                  </DialogHeader>

                  {selectedPage && (
                    <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">
                        {/* Featured Image */}
                        {selectedPage.featured_image && (
                          <div className="flex justify-center">
                            <img
                              src={selectedPage.featured_image}
                              alt={selectedPage.title}
                              className="max-h-64 w-full rounded-lg border-2 border-gray-200 object-cover"
                            />
                          </div>
                        )}

                        <div className="grid grid-cols-2 gap-4">
                          <div className="space-y-1">
                            <Label className="text-xs text-gray-500">
                              Title
                            </Label>

                            <p className="text-sm font-medium">
                              {selectedPage.title}
                            </p>
                          </div>

                          <div className="space-y-1">
                            <Label className="text-xs text-gray-500">
                              Slug
                            </Label>

                            <p className="break-all text-sm">
                              {selectedPage.slug}
                            </p>
                          </div>

                          <div className="space-y-1">
                            <Label className="text-xs text-gray-500">
                              Status
                            </Label>

                            <span
                              className={`inline-flex rounded-full px-3 py-1 text-sm font-medium ${
                                selectedPage.status
                                  ? "bg-green-100 text-green-800"
                                  : "bg-yellow-100 text-yellow-800"
                              }`}
                            >
                              {selectedPage.status ? "Published" : "Draft"}
                            </span>
                          </div>

                          {selectedPage.meta_title && (
                            <div className="space-y-1">
                              <Label className="text-xs text-gray-500">
                                Meta Title
                              </Label>

                              <p className="text-sm">
                                {selectedPage.meta_title}
                              </p>
                            </div>
                          )}

                          {selectedPage &&
                            selectedPage.meta_keywords &&
                            selectedPage.meta_keywords.length > 0 && (
                              <div className="col-span-2 space-y-1">
                                <Label className="text-xs text-gray-500">
                                  Meta Keywords
                                </Label>

                                <p className="text-sm">
                                  {selectedPage?.meta_keywords?.join(", ")}
                                </p>
                              </div>
                            )}

                          <div className="col-span-2 space-y-1">
                            <Label className="text-xs text-gray-500">
                              Content
                            </Label>

                            <div
                              className="prose prose-sm max-h-72 max-w-none 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: selectedPage.content,
                              }}
                            />
                          </div>

                          <div className="col-span-2 border-t pt-2">
                            <div className="grid grid-cols-2 gap-4">
                              <div className="space-y-1">
                                <Label className="text-xs text-gray-500">
                                  Created At
                                </Label>

                                <p className="text-xs text-gray-500">
                                  {new Date(
                                    selectedPage.createdAt,
                                  ).toLocaleString()}
                                </p>
                              </div>

                              <div className="space-y-1">
                                <Label className="text-xs text-gray-500">
                                  Updated At
                                </Label>

                                <p className="text-xs text-gray-500">
                                  {new Date(
                                    selectedPage.updatedAt,
                                  ).toLocaleString()}
                                </p>
                              </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={() => {
                            setShowViewModal(false);
                            handleEditModal(selectedPage);
                          }}
                        >
                          <Edit className="h-4 w-4" />
                          Edit
                        </Button>

                        <Button
                          variant="destructive"
                          size="sm"
                          onClick={() => {
                            setShowViewModal(false);
                            openDeleteModal(selectedPage);
                          }}
                        >
                          <Trash2 className="h-4 w-4" />
                          Delete
                        </Button>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </DialogContent>
          </Dialog>
        </div>
      </div>

      {/* Table */}
      <div className="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">
              <TableHead
                className="cursor-pointer px-4 py-4 text-center font-medium 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="min-w-[220px] px-4 py-4 font-medium">
                Image
              </TableHead>
              <TableHead
                className="min-w-[150px] cursor-pointer px-4 py-4 font-medium hover:bg-gray-50"
                onClick={() => handleSort("title")}
              >
                <div className="flex items-center gap-2">
                  Title
                  {sortField === "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 
                  className="min-w-[150px] px-4 py-4 font-medium cursor-pointer hover:bg-gray-50"
                >
                <div className="flex items-center gap-2">
                  Slug
                  
                </div>
              </TableHead> */}
              <TableHead
                className="min-w-[120px] cursor-pointer px-4 py-4 font-medium 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 className="min-w-[120px] px-4 py-4 font-medium">
                Created
              </TableHead>
              <TableHead className="px-4 py-4 font-medium">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody className="bg-gray-100 dark:bg-gray-800">
            {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>
            ) : cmsPages.length === 0 ? (
              <TableRow>
                <TableCell
                  colSpan={6}
                  className="px-4 py-8 text-center text-gray-500"
                >
                  No CMS pages found
                </TableCell>
              </TableRow>
            ) : (
              cmsPages.map((page, index) => (
                <tr
                  key={page._id}
                  className="bg-white hover:bg-gray-50 dark:bg-gray-900 dark:hover:bg-gray-800"
                >
                  <td 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 // desc
                        : (pagination.page - 1) * pagination.limit + index + 1 // asc
                    }
                  </td>
                  <td className="dark:border-strokedark border-b border-[#eee] px-4 py-5 pl-9 xl:pl-11">
                    <div className="flex items-center gap-3">
                      {page.featured_image ? (
                        <div className="h-12 w-12 overflow-hidden rounded-lg">
                          <img
                            src={
                              page.featured_image || "/placeholder-image.png"
                            }
                            alt={page.title}
                            onError={(e) => {
                              e.currentTarget.src = "/placeholder-image.png";
                            }}
                            className="h-full w-full cursor-pointer object-cover"
                            onClick={() => openPreview(index)}
                          />
                        </div>
                      ) : (
                        <DefaultImage />
                      )}
                    </div>
                  </td>
                  <td className="dark:border-strokedark border-b border-[#eee] px-4 py-5">
                    <p className="text-black dark:text-white">{page.title}</p>
                  </td>
                  {/* <td className="border-b border-[#eee] px-4 py-5 dark:border-strokedark">
                    <p className="text-xs text-gray-500">{page.slug}</p>
                   </td> */}
                  <td className="dark:border-strokedark border-b border-[#eee] px-4 py-5">
                    <Badge variant={page.status ? "default" : "outline"}>
                      {page.status ? "Published" : "Draft"}
                    </Badge>
                  </td>
                  <td className="dark:border-strokedark border-b border-[#eee] px-4 py-5">
                    <p className="text-black dark:text-white">
                      {new Date(page.createdAt).toLocaleDateString()}
                    </p>
                  </td>
                  <td 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={() => handleViewModal(page)}
                          className="hover:text-primary"
                        >
                          <Eye className="h-4 w-4" />
                        </Button>
                      </Tooltip>
                      <Tooltip text="Edit">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleEditModal(page)}
                          className="hover:text-primary"
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                      </Tooltip>
                      <Tooltip text="Delete">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => openDeleteModal(page)}
                          className="hover:text-red-500"
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </Tooltip>
                    </div>
                  </td>
                </tr>
              ))
            )}
          </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 &&
        selectedPage &&
        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 CMS Page
                </h3>
              </div>

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

              <div className="flex justify-end space-x-3">
                <button
                  onClick={() => {
                    setShowDeleteModal(false);
                    setSelectedPage(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 Page"}
                </button>
              </div>
            </div>
          </div>,
          document.body,
        )}
    </div>
  );
};

export default CMSManagement;
