'use client';

import { useState, useEffect, useRef, useMemo } from 'react';
import { toast } from 'react-hot-toast';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "../../../../../src/components/ui/dialog";
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';

interface Slider {
  _id: string;
  title: string;
  sub_title: string;
  description: string;
  image: string;
  link: string;
  button_text: string;
  order: number;
  status: boolean;
  createdAt: string;
  updatedAt: string;
}

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

const ManageSlider = () => {
  const [sliders, setSliders] = useState<Slider[]>([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [sortField, setSortField] = useState<"order" | "createdAt" | "title" | "status">("order");
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("asc");
  const [pagination, setPagination] = useState<PaginationData>({
    page: 1,
    limit: 10,
    total: 0,
    pages: 0
  });
  const [viewingSlider, setViewingSlider] = useState<Slider | 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 [selectedSlider, setSelectedSlider] = useState<Slider | null>(null);
  const [activeIndex, setActiveIndex] = useState(0);
    const [open, setOpen] = useState(false);
  
    const openPreview = (index: number) => {
      setActiveIndex(index);
      setOpen(true);
    };
  
    const previewImages = useMemo(
      () =>
        sliders
          .map((item: any) => ({
            src: item.image,
            name: item.title,
          }))
          .filter((i) => typeof i.src === "string" && i.src.trim()),
      [sliders]
    );

  // Form states
  const [formData, setFormData] = useState({
    title: '',
    sub_title: '',
    description: '',
    link: '',
    button_text: 'Learn More',
    order: 0,
    status: true,
    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 sliders
  const fetchSliders = 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/sliders?${params}`);
      const data = await response.json();

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

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

  const handleSort = (field: "order" | "createdAt" | "title" | "status") => {
    const newOrder = sortField === field && sortOrder === "asc" ? "desc" : "asc";
    setSortField(field);
    setSortOrder(newOrder);
    // Fetch with new sort values
    fetchSliders(pagination.page, searchTerm, statusFilter, field, newOrder);
  };

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

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

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

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

  // Reset form
  const resetForm = () => {
    setFormData({
      title: '',
      sub_title: '',
      description: '',
      link: '',
      button_text: 'Learn More',
      order: 0,
      status: true,
      image: null
    });
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
    if (editFileInputRef.current) {
      editFileInputRef.current.value = '';
    }
  };

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

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

    if (!formData.sub_title.trim()) {
      toast.error('Sub title is required');
      return;
    }

    if (!formData.description.trim()) {
      toast.error('Description is required');
      return;
    }

    if (!formData.image) {
      toast.error('Slider image is required');
      return;
    }

    try {
      setSubmitting(true);

      const formDataToSend = new FormData();
      formDataToSend.append('title', formData.title);
      formDataToSend.append('sub_title', formData.sub_title);
      formDataToSend.append('description', formData.description);
      formDataToSend.append('link', formData.link);
      formDataToSend.append('button_text', formData.button_text);
      formDataToSend.append('order', formData.order.toString());
      formDataToSend.append('status', formData.status.toString());
      formDataToSend.append('image', formData.image);

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

      const data = await response.json();

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

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

    if (!selectedSlider) return;

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

    if (!formData.sub_title.trim()) {
      toast.error('Sub title is required');
      return;
    }

    if (!formData.description.trim()) {
      toast.error('Description is required');
      return;
    }

    try {
      setSubmitting(true);

      const formDataToSend = new FormData();
      formDataToSend.append('title', formData.title);
      formDataToSend.append('sub_title', formData.sub_title);
      formDataToSend.append('description', formData.description);
      formDataToSend.append('link', formData.link);
      formDataToSend.append('button_text', formData.button_text);
      formDataToSend.append('order', formData.order.toString());
      formDataToSend.append('status', formData.status.toString());

      if (formData.image) {
        formDataToSend.append('image', formData.image);
      }

      const response = await fetch(`/api/sliders/${selectedSlider._id}`, {
        method: 'PUT',
        body: formDataToSend
      });

      const data = await response.json();

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

  // Handle delete slider
  const handleDelete = async () => {
    if (!selectedSlider) return;

    try {
      setSubmitting(true);

      const response = await fetch(`/api/sliders/${selectedSlider._id}`, {
        method: 'DELETE'
      });

      const data = await response.json();

      if (data.success) {
        toast.success('Slider deleted successfully');
        setShowDeleteModal(false);
        setSelectedSlider(null);
        fetchSliders(pagination.page, searchTerm, statusFilter, sortField, sortOrder);
      } else {
        toast.error(data.error || 'Failed to delete slider');
      }
    } catch (error) {
      console.error('Error deleting slider:', error);
      toast.error('Failed to delete slider');
    } finally {
      setSubmitting(false);
    }
  };

  // Open edit modal
  const openEditModal = (slider: Slider) => {
    setSelectedSlider(slider);
    setFormData({
      title: slider.title,
      sub_title: slider.sub_title,
      description: slider.description,
      link: slider.link || '',
      button_text: slider.button_text || 'Learn More',
      order: slider.order,
      status: slider.status,
      image: null
    });
    setShowEditModal(true);
  };

  // Open delete modal
  const openDeleteModal = (slider: Slider) => {
    setSelectedSlider(slider);
    setShowDeleteModal(true);
  };

  const handleView = (slider: Slider) => {
    setViewingSlider(slider);
    setIsViewDialogOpen(true);
  };
  
  // Close modal
  const handleCloseModal = () => {
    setShowEditModal(false);
    setShowCreateModal(false);
    resetForm();
  };

  // Truncate text
  const truncateText = (text: string, maxLength: number) => {
    if (text.length <= maxLength) return text;
    return text.substring(0, maxLength) + '...';
  };

  return (
    <div className="p-0">
      {/* Header */}
      <div>
          {/* <h4 className="text-xl font-semibold text-black dark:text-white">
            Slider Management
          </h4> */}
          <div className="text-sm text-gray-500 mt-1">
            Total Sliders: {pagination.total}
          </div>
        </div>

      {/* View Dialog */}
      <Dialog open={isViewDialogOpen} onOpenChange={setIsViewDialogOpen}>
        <DialogContent className="max-w-2xl">
          <div className="flex items-center max-w-lg min-h-[calc(100%-0.5rem)] my-1 mx-auto">
            <div className="relative flex flex-col w-full rounded-lg gap-0 border-0 border-stroke bg-white p-0 shadow-lg text-dark-5 dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
              <DialogHeader className="flex-shrink-0">
                <DialogTitle>Slider Details</DialogTitle>
                <X className="h-6 w-6 p-1 text-white cursor-pointer"
                  onClick={() => {
                    setIsViewDialogOpen(false);
                  }}
                />  
              </DialogHeader>
              
              {viewingSlider && (
                <div className="p-4 pl-2 pr-2 pb-0 flex flex-col flex-1">
                  <div className="max-h-[60vh] min-h-[60vh] flex-1 pl-2 overflow-y-auto pr-2 pt-2 pb-4">
                    <div className="space-y-6 pb-4">
                      {/* Slider Image */}
                      {viewingSlider.image && (
                        <div className="flex justify-center">
                          <img
                            src={viewingSlider.image}
                            alt={viewingSlider.title}
                            className="w-full max-h-64 object-cover rounded-lg border-2 border-gray-200"
                          />
                        </div>
                      )}

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

                        <div className="space-y-0.5">
                          <Label className="text-xs text-gray-500">Sub Title</Label>
                          <p className="text-sm">{viewingSlider.sub_title}</p>
                        </div>

                        <div className="space-y-0.5">
                          <Label className="text-xs text-gray-500">Order: </Label>
                          {/* <Badge variant="outline" className="mt-1"> */}
                             {viewingSlider.order}
                          {/* </Badge> */}
                        </div>

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

                        {viewingSlider.link && (
                          <div className="space-y-0.5">
                            <Label className="text-xs text-gray-500">Link URL</Label>
                            <a 
                              href={viewingSlider.link}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="text-sm text-primary hover:underline break-all"
                            >
                              {viewingSlider.link}
                            </a>
                          </div>
                        )}

                        {viewingSlider.button_text && (
                          <div className="space-y-0.5">
                            <Label className="text-xs text-gray-500">Button Text</Label>
                            <p className="text-sm">{viewingSlider.button_text}</p>
                          </div>
                        )}

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

                        <div className="col-span-2 pt-2">
                          <div className="grid grid-cols-2 gap-3 pt-2 border-t">
                            <div className="space-y-0.5">
                              <Label className="text-xs text-gray-500">Created At</Label>
                              <p className="text-xs text-gray-500">{formatDate(viewingSlider.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(viewingSlider.updatedAt)}</p>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>

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

      {/* Filters */}
      <div className="flex flex-col gap-4 pt-0 py-1 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex gap-4 pt-0 py-1 flex-row sm:items-center w-full sm:max-w-[700px]">
          <div className="flex-1">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
              <Input
                type="text"
                placeholder="Search sliders..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10"
              />
            </div>
          </div>
          <div className="sm:w-48">
            <select
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
              className="p-3 rounded-md border border-input text-sm bg-transparent dark:bg-[#324153] dark:text-white focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50"
            >
              <option value="all">All Status</option>
              <option value="true">Active</option>
              <option value="false">Inactive</option>
            </select>
          </div>
          
          {/* PAGINATION LIMIT DROPDOWN */}
          <div className="flex items-center gap-2">
            <Label className="text-sm whitespace-nowrap">Show:</Label>
            <select
              value={pagination.limit.toString()}
              onChange={(e) => handleLimitChange(e.target.value)}
              className="p-3 rounded-md border border-input text-sm bg-transparent dark:bg-[#324153] dark:text-white focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50"
            >
              <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="mb-6 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="w-4 h-4" />
              Add Slider
            </Button>
            <DialogContent className="max-w-2xl">
              <div className="flex items-center max-w-lg min-h-[calc(100%-0.5rem)] my-1 mx-auto">
                <div className="relative flex flex-col w-full rounded-lg gap-0 border-0 border-stroke bg-white p-0 shadow-lg text-dark-5 dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
                  <DialogHeader>
                    <DialogTitle>{showEditModal ? 'Edit Slider' : 'Add New Slider'}</DialogTitle>   
                    <X className="h-6 w-6 p-1 text-white cursor-pointer"
                      onClick={() => {
                        handleCloseModal();
                      }}
                    />           
                  </DialogHeader>

                  <form onSubmit={showCreateModal ? handleCreate : handleEdit} className='p-4 pl-2 pr-2 pb-0 flex flex-col flex-1'>
                    <div className="max-h-[60vh] min-h-[60vh] flex-1 pl-2 overflow-y-auto pr-2 pt-2 space-y-4 pb-4">
                      <div className="mb-4">
                        <label className="mb-2.5 block font-medium text-black dark:text-white">
                          Title <span className='text-red-600 font-bold'>*</span>
                        </label>
                        <input
                          type="text"
                          value={formData.title}
                          onChange={(e) =>
                            setFormData({ ...formData, title: e.target.value })
                          }
                          className="w-full rounded-lg border-[1.5px] border-stroke bg-transparent px-5 py-3 text-black outline-none transition disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input 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">
                          Sub Title <span className='text-red-600 font-bold'>*</span>
                        </label>
                        <input
                          type="text"
                          value={formData.sub_title}
                          onChange={(e) =>
                            setFormData({ ...formData, sub_title: e.target.value })
                          }
                          className="w-full rounded-lg border-[1.5px] border-stroke bg-transparent px-5 py-3 text-black outline-none transition disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input 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 <span className='text-red-600 font-bold'>*</span>
                        </label>
                        <Editor
                          value={formData.description}
                          onChange={(value: any) =>
                            setFormData({ ...formData, description: value })
                          }
                          rows={4}
                          className="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 disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input 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">
                          Link (Optional)
                        </label>
                        <input
                          type="url"
                          value={formData.link}
                          onChange={(e) =>
                            setFormData({ ...formData, link: e.target.value })
                          }
                          placeholder="https://example.com"
                          className="w-full rounded-lg border-[1.5px] border-stroke bg-transparent px-5 py-3 text-black outline-none transition disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input 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">
                          Button Text
                        </label>
                        <input
                          type="text"
                          value={formData.button_text}
                          onChange={(e) =>
                            setFormData({ ...formData, button_text: e.target.value })
                          }
                          placeholder="Learn More"
                          className="w-full rounded-lg border-[1.5px] border-stroke bg-transparent px-5 py-3 text-black outline-none transition disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input 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">
                          Order
                        </label>
                        <input
                          type="number"
                          min={0}
                          value={formData.order}
                          onChange={(e) =>
                            setFormData({
                              ...formData,
                              order: Math.max(0, parseInt(e.target.value) || 0),
                            })
                          }
                          className="w-full rounded-lg border-[1.5px] border-stroke bg-transparent px-5 py-3 text-black outline-none transition disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:text-white dark:focus:border-primary"
                        />
                        <p className="text-xs text-gray-500 mt-1">Lower numbers appear first</p>
                      </div>

                      <div className="mb-4">
                        <label className="mb-2.5 block font-medium text-black dark:text-white">
                          Slider Image <span className='text-red-600 font-bold'>*</span> (Compulsory)
                        </label>
                        <input
                          ref={fileInputRef}
                          type="file"
                          accept="image/*"
                          onChange={(e) =>
                            setFormData({ ...formData, image: e.target.files?.[0] || null })
                          }
                          className="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 disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:text-white dark:focus:border-primary"
                          required={!showEditModal}
                        />
                        {showEditModal && selectedSlider?.image && !formData.image && (
                          <div className="mt-2">
                            <img
                              src={selectedSlider.image}
                              alt="Current slider"
                              className="h-20 rounded-lg object-cover border"
                            />
                            <p className="text-xs text-gray-500 mt-1">Current image</p>
                          </div>
                        )}
                        {formData.image && (
                          <img
                            src={
                              formData.image instanceof File
                                ? URL.createObjectURL(formData.image)
                                : formData.image
                            }
                            className="mt-3 h-28 rounded-lg object-cover border"
                            alt="Preview"
                          />
                        )}
                      </div>
                      <div className="mb-6">
                        <label className="flex cursor-pointer items-center">
                          <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-11 rounded-full transition-colors ${
                                formData.status
                                  ? "bg-primary"
                                  : "bg-gray-400 dark:bg-gray-600"
                              }`}
                            ></div>

                            <div
                              className={`absolute top-1 h-4 w-4 rounded-full bg-white transition-transform ${
                                formData.status
                                  ? "translate-x-6 left-0"
                                  : "translate-x-0 left-1"
                              }`}
                            ></div>
                          </div>

                          <span
                            className={`ml-3 text-sm font-medium ${
                              formData.status
                                ? "text-primary"
                                : "text-gray-500"
                            }`}
                          >
                            {formData.status ? "Active" : "Inactive"}
                          </span>
                        </label>
                      </div>
                    </div>
                    <div className="flex justify-end space-x-3 px-4 pb-3 pt-3 border-t -mx-2">
                      <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 Slider')
                        : (submitting ? 'Creating...' : 'Create Slider')}
                      </button>
                    </div>
                  </form>
                </div>
              </div>
            </DialogContent>
          </Dialog>
        </div>
      </div>

      {/* Table */}
      <div className="rounded-md border">
        <Table>
          <TableHeader className="bg-gray-100 dark:bg-gray-800">
            <TableRow className='bg-white dark:bg-gray-900 hover:bg-gray-50 dark:hover:bg-gray-800'>
              {/* ID Column with Sort */}
              <TableHead 
                className="text-center cursor-pointer 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>

              {/* Order Column with Sort */}
              <TableHead 
                className="text-center cursor-pointer hover:bg-gray-50 w-20" 
                onClick={() => handleSort("order")}
              >
                <div className="flex items-center justify-center gap-2">
                  Order
                  {sortField === "order" ? (
                    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("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>Sub Title</TableHead>
              <TableHead>Image</TableHead>
              <TableHead>Button</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" />
                    )
                  )}
                  {sortField !== "status" && (
                    <ArrowDown className="h-4 w-4 text-gray-400" />
                  )}
                </div>
              </TableHead>
              
              <TableHead className='text-center'>Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading ? (
              <TableRow className='bg-white dark:bg-gray-900 hover:bg-gray-50 dark:hover:bg-gray-800'>
                <TableCell colSpan={8} className="px-4 py-5 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>
            ) : sliders.length === 0 ? (
              <TableRow className="bg-white dark:bg-gray-900">
                <TableCell colSpan={8} className="px-4 py-8 text-center text-gray-500">
                  No sliders found
                </TableCell>
              </TableRow>
            ) : (
              sliders.map((slider, index) => (
                <TableRow key={slider._id} className='bg-white dark:bg-gray-900 hover:bg-gray-50 dark:hover:bg-gray-800'>
                  <TableCell className="text-center border-b border-[#eee] px-4 py-5 dark:border-strokedark">
                    {sortField === "createdAt" && sortOrder === "desc"
                      ? pagination.total - ((pagination.page - 1) * pagination.limit) - index
                      : ((pagination.page - 1) * pagination.limit) + index + 1
                    }
                  </TableCell>
                  <TableCell className="text-center border-b border-[#eee] px-4 py-5 dark:border-strokedark">
                    {slider.order}
                  </TableCell>
                  <TableCell className="border-b border-[#eee] px-4 py-5 dark:border-strokedark">
                    <p className="font-medium text-black dark:text-white">{truncateText(slider.title, 40)}</p>
                  </TableCell>
                  <TableCell className="border-b border-[#eee] px-4 py-5 dark:border-strokedark">
                    <p className="text-black dark:text-white">{truncateText(slider.sub_title, 30)}</p>
                  </TableCell>
                  <TableCell className="border-b border-[#eee] px-4 py-5 pl-9 dark:border-strokedark xl:pl-11">
                    <div className="flex items-center gap-3">
                      <div className="h-12 w-12 overflow-hidden rounded-lg">
                        <img
                          src={slider.image}
                          alt={slider.title}
                          width={48}
                          height={48}
                          className="h-full w-full object-cover cursor-pointer"
                          onClick={() => openPreview(index)}
                        />
                      </div>
                    </div>
                  </TableCell>
                  <TableCell className="border-b border-[#eee] px-4 py-5 dark:border-strokedark">
                    <p className="text-black dark:text-white">{slider.button_text || '-'}</p>
                  </TableCell>
                  <TableCell className="border-b border-[#eee] px-4 py-5 dark:border-strokedark">                    
                    <Badge variant={slider.status ? "default" : "outline"}>
                        {slider.status ? 'Active' : 'Inactive'}
                    </Badge>
                  </TableCell>
                  <TableCell className="border-b border-[#eee] px-4 py-5 dark:border-strokedark">
                    <div className="flex items-center space-x-3.5">
                      <Tooltip text='View'>
                        <Button size="sm" variant="outline" onClick={() => handleView(slider)}>
                          <Eye className="w-4 h-4" />
                        </Button>
                      </Tooltip>
                      <Tooltip text='Edit'>
                        <Button size="sm" variant="outline" 
                          onClick={() => openEditModal(slider)}
                          className="hover:text-primary"
                        >
                          <Edit className="w-4 h-4" />
                        </Button>
                      </Tooltip>
                      <Tooltip text='Delete'>
                        <Button size="sm" variant="outline" 
                          onClick={() => openDeleteModal(slider)}
                          className="hover:text-red-500"
                        >
                          <Trash2 className="w-4 h-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
              onClick={() => handlePageChange(pagination.page - 1)}
              disabled={pagination.page === 1}
              className="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:border-strokedark dark:text-white"
            >
              <ChevronLeft className="h-4 w-4" />
              Previous
            </button>
            {Array.from({ length: pagination.pages }, (_, i) => i + 1).map((page) => (
              <button
                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'
                    : 'border-stroke text-black hover:bg-gray-50 dark:border-strokedark dark:text-white'
                }`}
              >
                {page}
              </button>
            ))}
            <button
              onClick={() => handlePageChange(pagination.page + 1)}
              disabled={pagination.page === pagination.pages}
              className="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:border-strokedark dark:text-white"
            >
              Next
              <ChevronRightIcon className="h-4 w-4" />
            </button>
          </div>
        </div>
      )}

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

            <p className="mb-6 text-sm text-gray-600 dark:text-black">
              Are you sure you want to delete the slider "{selectedSlider.title}"?
              This action cannot be undone and will also delete the associated image.
            </p>

            <div className="flex justify-end space-x-3">
              <button
                onClick={() => {
                  setShowDeleteModal(false);
                  setSelectedSlider(null);
                }}
                className="rounded-lg border border-stroke px-6 py-2 text-sm font-medium text-black hover:bg-gray-50 dark:border-strokedark 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 Slider'}
              </button>
            </div>
          </div>
        </div>,
        document.body
      )}      
    </div>
  );
};

export default ManageSlider;