'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, ImagePlus, 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 { Interweave } from 'interweave';

interface Blog {
  _id: string;
  title: string;
  sub_title: string;
  images: string[];
  description: string;
  short_description: string;
  createdAt: string;
  updatedAt: string;
}

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

const ManageBlogs = () => {
  const [blogs, setBlogs] = useState<Blog[]>([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [sortField, setSortField] = useState<"createdAt" | "title">("createdAt");
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");
  const [pagination, setPagination] = useState<PaginationData>({
    page: 1,
    limit: 10,
    total: 0,
    pages: 0
  });
  const [viewingBlog, setViewingBlog] = useState<Blog | 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 [selectedBlog, setSelectedBlog] = useState<Blog | null>(null);
  const [activeIndex, setActiveIndex] = useState(0);
  const [open, setOpen] = useState(false);
  const [validationErrors, setValidationErrors] = useState<{
    title?: string;
    sub_title?: string;
    short_description?: string;
    description?: string;
    images?: string;
  }>({});

  const openPreview = (index: number) => {
    setActiveIndex(index);
    setOpen(true);
  };

  // Form states
  const [formData, setFormData] = useState({
    title: '',
    sub_title: '',
    description: '',
    short_description: '',
    images: [] as File[],
    existingImages: [] as string[],
    removeImages: [] as string[]
  });

  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'
    });
  };

  // Validate form data
  const validateForm = (): boolean => {
    const errors: {
      title?: string;
      sub_title?: string;
      short_description?: string;
      description?: string;
      images?: string;
    } = {};

    // Validate title
    if (!formData.title.trim()) {
      errors.title = 'Blog title is required';
    } else if (formData.title.length < 3) {
      errors.title = 'Title must be at least 3 characters';
    } else if (formData.title.length > 200) {
      errors.title = 'Title must not exceed 200 characters';
    }

    // Validate sub title
    if (!formData.sub_title.trim()) {
      errors.sub_title = 'Sub title is required';
    } else if (formData.sub_title.length < 3) {
      errors.sub_title = 'Sub title must be at least 3 characters';
    } else if (formData.sub_title.length > 200) {
      errors.sub_title = 'Sub title must not exceed 200 characters';
    }

    // Validate short description
    if (!formData.short_description.trim()) {
      errors.short_description = 'Short description is required';
    } else if (formData.short_description.length < 10) {
      errors.short_description = 'Short description must be at least 10 characters';
    } else if (formData.short_description.length > 500) {
      errors.short_description = 'Short description must not exceed 500 characters';
    }

    // Validate description (rich text)
    const cleanDescription = formData.description.replace(/<[^>]*>/g, '').trim();
    if (!cleanDescription) {
      errors.description = 'Description is required';
    } else if (cleanDescription.length < 20) {
      errors.description = 'Description must be at least 20 characters';
    }

    // Validate images
    if (showEditModal) {
      if (formData.existingImages.length === 0 && formData.images.length === 0) {
        errors.images = 'At least one image is required';
      }
    } else {
      if (formData.images.length === 0) {
        errors.images = 'At least one image is required';
      }
    }

    setValidationErrors(errors);
    return Object.keys(errors).length === 0;
  };

  // Clear validation errors when form data changes
  useEffect(() => {
    if (Object.keys(validationErrors).length > 0) {
      setValidationErrors({});
    }
  }, [formData.title, formData.sub_title, formData.short_description, formData.description, formData.images.length]);

  // Fetch blogs
  const fetchBlogs = async (page = 1, search = '', sort = sortField, order = sortOrder) => {
    try {
      setLoading(true);
      const params = new URLSearchParams({
        page: page.toString(),
        limit: pagination.limit.toString(),
        sort: sort,
        order: order,
        ...(search && { search })
      });

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

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

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

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

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

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

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

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

  // Reset form
  const resetForm = () => {
    setFormData({
      title: '',
      sub_title: '',
      description: '',
      short_description: '',
      images: [],
      existingImages: [],
      removeImages: []
    });
    setValidationErrors({});
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
    if (editFileInputRef.current) {
      editFileInputRef.current.value = '';
    }
  };

  // Handle image selection
  const handleImageSelect = (files: FileList | null, isEdit = false) => {
    if (!files) return;
    
    const newFiles = Array.from(files);
    const validFiles = newFiles.filter(file => {
      const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif'];
      const maxSize = 5 * 1024 * 1024; // 5MB
      
      if (!allowedTypes.includes(file.type)) {
        toast.error(`${file.name}: Invalid file type. Only JPEG, PNG, WebP, and GIF are allowed.`);
        return false;
      }
      if (file.size > maxSize) {
        toast.error(`${file.name}: File too large. Maximum size is 5MB.`);
        return false;
      }
      return true;
    });
    
    setFormData(prev => ({ ...prev, images: [...prev.images, ...validFiles] }));
  };

  // Handle remove image (for new uploads)
  const handleRemoveNewImage = (index: number) => {
    setFormData(prev => ({
      ...prev,
      images: prev.images.filter((_, i) => i !== index)
    }));
  };

  // Handle remove existing image (for edit mode)
  const handleRemoveExistingImage = (imageUrl: string) => {
    setFormData(prev => ({
      ...prev,
      removeImages: [...prev.removeImages, imageUrl],
      existingImages: prev.existingImages.filter(img => img !== imageUrl)
    }));
  };

  // Handle create blog
  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // Validate form before submission
    if (!validateForm()) {
      // Scroll to first error
      const firstError = document.querySelector('.error-message');
      if (firstError) {
        firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
      }
      toast.error('Please fix all validation errors');
      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('short_description', formData.short_description);
      
      formData.images.forEach(image => {
        formDataToSend.append('images', image);
      });

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

      const data = await response.json();

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

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

    if (!selectedBlog) return;
    
    // Validate form before submission
    if (!validateForm()) {
      const firstError = document.querySelector('.error-message');
      if (firstError) {
        firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
      }
      toast.error('Please fix all validation errors');
      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('short_description', formData.short_description);
      
      // Send existing images as JSON string
      if (formData.existingImages.length > 0) {
        formDataToSend.append('existingImages', JSON.stringify(formData.existingImages));
      }
      
      // Send images to remove as JSON string
      if (formData.removeImages.length > 0) {
        formDataToSend.append('removeImages', JSON.stringify(formData.removeImages));
      }
      
      // Append new images
      formData.images.forEach(image => {
        formDataToSend.append('images', image);
      });

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

      const data = await response.json();

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

  // Handle delete blog
  const handleDelete = async () => {
    if (!selectedBlog) return;

    try {
      setSubmitting(true);

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

      const data = await response.json();

      if (data.success) {
        toast.success('Blog deleted successfully');
        setShowDeleteModal(false);
        setSelectedBlog(null);
        fetchBlogs(pagination.page, searchTerm, sortField, sortOrder);
      } else {
        toast.error(data.error || 'Failed to delete blog');
      }
    } catch (error) {
      console.error('Error deleting blog:', error);
      toast.error('Failed to delete blog');
    } finally {
      setSubmitting(false);
    }
  };

  // Open edit modal
  const openEditModal = (blog: Blog) => {
    setSelectedBlog(blog);
    setFormData({
      title: blog.title,
      sub_title: blog.sub_title,
      description: blog.description,
      short_description: blog.short_description,
      images: [],
      existingImages: blog.images,
      removeImages: []
    });
    setValidationErrors({});
    setShowEditModal(true);
  };

  // Open delete modal
  const openDeleteModal = (blog: Blog) => {
    setSelectedBlog(blog);
    setShowDeleteModal(true);
  };

  const handleView = (blog: Blog) => {
    setViewingBlog(blog);
    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) + '...';
  };

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

  return (
    <div className="p-0">
      {/* Header */}      
      <div>
          <div className="text-sm text-gray-500 mt-1">
            Total Blogs: {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>Blog Details</DialogTitle>
                <X className="h-6 w-6 p-1 text-white cursor-pointer"
                  onClick={() => {
                    setIsViewDialogOpen(false);
                  }}
                />    
              </DialogHeader>
              
              {viewingBlog && (
                <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 space-y-4 pb-4">
                    <div className="space-y-6 pb-4">
                      {/* Blog Images */}
                      {viewingBlog.images && viewingBlog.images.length > 0 && (
                        <div>
                          <Label className="text-xs text-gray-500">Images</Label>
                          <div className="grid grid-cols-2 gap-3 mt-2">
                            {viewingBlog.images.slice(0, 4).map((image, index) => (
                              <img
                                key={index}
                                src={image}
                                alt={`Blog image ${index + 1}`}
                                className="w-full h-32 object-cover rounded-lg border-2 border-gray-200 cursor-pointer"
                                onClick={() => openPreview(index)}
                              />
                            ))}
                            {viewingBlog.images.length > 4 && (
                              <div className="relative w-full h-32 rounded-lg border-2 border-gray-200 bg-gray-100 flex items-center justify-center">
                                <p className="text-sm text-gray-600">
                                  +{viewingBlog.images.length - 4} more
                                </p>
                              </div>
                            )}
                          </div>
                        </div>
                      )}

                      <div className="grid 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">{viewingBlog.title}</p>
                        </div>

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

                        <div className="col-span-2 space-y-0.5">
                          <Label className="text-xs text-gray-500">Short Description</Label>
                          <p className="text-sm text-gray-700 bg-gray-50 dark:bg-[#324153] dark:text-white p-2 rounded">
                            {viewingBlog.short_description}
                          </p>
                        </div>

                        <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-96 overflow-y-auto bg-gray-50 text-gray-800 dark:bg-[#324153] dark:text-white p-3 rounded-md prose prose-sm"
                            dangerouslySetInnerHTML={{ __html: viewingBlog.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(viewingBlog.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(viewingBlog.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(viewingBlog);
                      }}
                    >
                      <Edit className="w-4 h-4 mr-1" />
                      Edit
                    </Button>
                    <Button
                      variant="destructive"
                      size="sm"
                      onClick={() => {
                        setIsViewDialogOpen(false);
                        openDeleteModal(viewingBlog);
                      }}
                    >
                      <Trash2 className="w-4 h-4 mr-1" />
                      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 blogs..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10"
              />
            </div>
          </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-[#3B3B3B] 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 mt-2"
            >
              <Plus className="w-4 h-4" />
              Add Blog
            </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 Blog' : 'Add New Blog'}</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">
                      {/* Title Field */}
                      <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] ${
                            validationErrors.title ? 'border-red-500' : '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
                        />
                        {validationErrors.title && (
                          <p className="error-message mt-1 text-xs text-red-500">{validationErrors.title}</p>
                        )}
                      </div>

                      {/* Sub Title Field */}
                      <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] ${
                            validationErrors.sub_title ? 'border-red-500' : '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
                        />
                        {validationErrors.sub_title && (
                          <p className="error-message mt-1 text-xs text-red-500">{validationErrors.sub_title}</p>
                        )}
                      </div>

                      {/* Short Description Field */}
                      <div className="mb-4">
                        <label className="mb-2.5 block font-medium text-black dark:text-white">
                          Short Description <span className='text-red-600 font-bold'>*</span> (Max 500 characters)
                        </label>
                        <Editor
                          value={formData.short_description}
                        
                          onChange={(value: any) =>
                              setFormData({ ...formData, short_description: value })
                            }
                          className={`w-full rounded-lg border-[1.5px] ${
                            validationErrors.short_description ? 'border-red-500' : '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`}
                        
                        />
                        {validationErrors.short_description && (
                          <p className="error-message mt-1 text-xs text-red-500">{validationErrors.short_description}</p>
                        )}
                        <div className="text-right text-xs text-gray-500 mt-1">
                          {formData.short_description.length}/500 characters
                        </div>
                      </div>

                      {/* Description Field (Rich Text Editor) */}
                      <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>
                        <div className={`rounded-lg border-[1.5px] ${
                          validationErrors.description ? 'border-red-500' : 'border-stroke'
                        } overflow-hidden`}>
                          <Editor
                            value={formData.description}
                            onChange={(value: any) =>
                              setFormData({ ...formData, description: value })
                            }
                            rows={5}
                            className="w-full rounded-lg 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>
                        {validationErrors.description && (
                          <p className="error-message mt-1 text-xs text-red-500">{validationErrors.description}</p>
                        )}
                      </div>

                      {/* Images Field */}
                      <div className="mb-4">
                        <label className="mb-2.5 block font-medium text-black dark:text-white">
                          Images <span className='text-red-600 font-bold'>*</span> (At least one image)
                        </label>
                        
                        {/* Existing Images (Edit Mode) */}
                        {showEditModal && formData.existingImages.length > 0 && (
                          <div className="mb-4">
                            <p className="text-sm text-gray-600 mb-2">Current Images:</p>
                            <div className="flex flex-wrap gap-3">
                              {formData.existingImages.map((image, index) => (
                                <div key={index} className="relative">
                                  <img
                                    src={image}
                                    alt={`Blog image ${index + 1}`}
                                    className="h-20 w-20 rounded-lg object-cover border"
                                  />
                                  <button
                                    type="button"
                                    onClick={() => handleRemoveExistingImage(image)}
                                    className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1 hover:bg-red-600"
                                  >
                                    <X className="w-3 h-3" />
                                  </button>
                                </div>
                              ))}
                            </div>
                          </div>
                        )}

                        {/* New Images Preview */}
                        {formData.images.length > 0 && (
                          <div className="mb-4">
                            <p className="text-sm text-gray-600 mb-2">New Images:</p>
                            <div className="flex flex-wrap gap-3">
                              {formData.images.map((image, index) => (
                                <div key={index} className="relative">
                                  <img
                                    src={URL.createObjectURL(image)}
                                    alt={`Preview ${index + 1}`}
                                    className="h-20 w-20 rounded-lg object-cover border"
                                  />
                                  <button
                                    type="button"
                                    onClick={() => handleRemoveNewImage(index)}
                                    className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1 hover:bg-red-600"
                                  >
                                    <X className="w-3 h-3" />
                                  </button>
                                </div>
                              ))}
                            </div>
                          </div>
                        )}

                        <input
                          ref={fileInputRef}
                          type="file"
                          accept="image/*"
                          multiple
                          onChange={(e) => handleImageSelect(e.target.files, showEditModal)}
                          className={`w-full rounded-lg border-[1.5px] ${
                            validationErrors.images ? 'border-red-500' : '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`}
                        />
                        {validationErrors.images && (
                          <p className="error-message mt-1 text-xs text-red-500">{validationErrors.images}</p>
                        )}
                        <p className="text-xs text-gray-500 mt-1">
                          You can select multiple images. Supported formats: JPEG, PNG, WebP, GIF. Max size per image: 5MB
                        </p>
                      </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"
                        size="sm"
                        disabled={submitting}
                      >
                        {showEditModal ? (submitting ? 'Updating...' : 'Update Blog')
                        : (submitting ? 'Creating...' : 'Create Blog')}
                      </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>

              <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>Images</TableHead>
              <TableHead>Short Description</TableHead>
              <TableHead>Created</TableHead>
              <TableHead>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={7} 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>
            ) : blogs.length === 0 ? (
              <TableRow className='bg-white dark:bg-gray-900'>
                <TableCell colSpan={7} className="px-4 py-8 text-center text-gray-500">
                  No blogs found
                </TableCell>
              </TableRow>
            ) : (
              blogs.map((blog, index) => (
                <TableRow key={blog._id} className='bg-white dark:bg-gray-900 hover:bg-gray-50 dark:hover:bg-gray-800'>
                  <TableCell className="text-center">
                    {sortField === "createdAt" && sortOrder === "asc"
                      ? pagination.total - ((pagination.page - 1) * pagination.limit) - index
                      : ((pagination.page - 1) * pagination.limit) + index + 1
                    }
                  </TableCell>
                  <TableCell className="border-b border-[#eee] px-4 py-5 dark:border-strokedark">
                    <p className="font-medium text-black dark:text-white">{blog.title}</p>
                  </TableCell>
                  <TableCell className="border-b border-[#eee] px-4 py-5 dark:border-strokedark">
                    <p className="text-black dark:text-white">{truncateText(blog.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-2">
                      {blog.images && blog.images.length > 0 && (
                        <>
                          <div className="h-12 w-12 overflow-hidden rounded-lg cursor-pointer" onClick={() => {
                            const blogIndex = blogs.findIndex(b => b._id === blog._id);
                            openPreview(blogIndex);
                          }}>
                            <img
                              src={blog.images[0]}
                              alt={blog.title}
                              width={48}
                              height={48}
                              className="h-full w-full object-cover"
                            />
                          </div>
                          {blog.images.length > 1 && (
                            <Badge variant="secondary" className="text-xs">
                              +{blog.images.length - 1}
                            </Badge>
                          )}
                        </>
                      )}
                    </div>
                  </TableCell>
                  <TableCell className="border-b border-[#eee] px-4 py-5 dark:border-strokedark">
                    <p className="text-sm text-black dark:text-white">
                      {/* {truncateText(blog.short_description, 50)} */}
                      <Interweave content={blog.short_description} />
                    </p>
                  </TableCell>
                  <TableCell className="border-b border-[#eee] px-4 py-5 dark:border-strokedark">
                    <p className="text-black dark:text-white">
                      {new Date(blog.createdAt).toLocaleDateString()}
                    </p>
                  </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(blog)}>
                          <Eye className="w-4 h-4" />
                        </Button>
                      </Tooltip>
                      <Tooltip text='Edit'>
                        <Button size="sm" variant="outline" 
                          onClick={() => openEditModal(blog)}
                          className="hover:text-primary"
                        >
                          <Edit className="w-4 h-4" />
                        </Button>
                      </Tooltip>
                      <Tooltip text='Delete'>
                        <Button size="sm" variant="outline" 
                          onClick={() => openDeleteModal(blog)}
                          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 && selectedBlog && 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 Blog
              </h3>
            </div>

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

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

export default ManageBlogs;