"use client";
import React, { useState, useEffect } from "react";
import Swal from 'sweetalert2';
import { Eye, Pencil, Trash2, X, User, Globe, ExternalLink, Edit2, Plus } from "lucide-react";
import SummernoteEditor from "../../../app/components/organisms/SummernoteEditor";
import Pagination from "../components/Pagination";
import Link from "next/link";
import { useRouter } from 'next/navigation';

const GuideList = () => {
  const [guides, setGuides] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selected, setSelected] = useState(null);
  const [showModal, setShowModal] = useState(false);
  const [editMode, setEditMode] = useState(false);
  const [page, setPage] = useState(1);
  const [limit] = useState(15);
  const [totalItems, setTotalItems] = useState(0);
  const [totalPages, setTotalPages] = useState(1);
  
  const [searchTerm, setSearchTerm] = useState("");
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [featuredFilter, setFeaturedFilter] = useState("");
  const [activeFilter, setActiveFilter] = useState("");
  const [authorFilter, setAuthorFilter] = useState("");
  
  const [appliedSearchTerm, setAppliedSearchTerm] = useState("");
  const [appliedStartDate, setAppliedStartDate] = useState("");
  const [appliedEndDate, setAppliedEndDate] = useState("");
  const [appliedFeaturedFilter, setAppliedFeaturedFilter] = useState("");
  const [appliedActiveFilter, setAppliedActiveFilter] = useState("");
  const [appliedAuthorFilter, setAppliedAuthorFilter] = useState("");
  
  const [isFilterOpen, setIsFilterOpen] = useState(false);
  const [universities, setUniversities] = useState([]);
  const [subjects, setSubjects] = useState([]);
  const [authors, setAuthors] = useState([]);
  const [isUploading, setIsUploading] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [uploadedImages, setUploadedImages] = useState("");
  
  const [formData, setFormData] = useState({
    type: "University",
    university_id: "",
    subject_id: "",
    title: "",
    slug: "",
    description: "",
    featuredImage: null,
    show_meta: false,
    meta_title: "",
    meta_description: "",
    meta_keywords: "",
    active: true,
    is_featured: false,
    author_id: "",
  });

  const router = useRouter();

  const generateSlug = (title) => {
    return title
      .toLowerCase()
      .trim()
      .replace(/[^\w\s-]/g, '')
      .replace(/\s+/g, '-')
      .replace(/-+/g, '-')
      .replace(/^-+|-+$/g, '');
  };

  const fetchGuides = async (p = 1) => {
    try {
      setLoading(true);
      const params = new URLSearchParams({
        page: p.toString(),
        limit: limit.toString()
      });
      
      if (appliedSearchTerm) {
        params.append('search', appliedSearchTerm);
      }
      if (appliedStartDate) {
        params.append('start_date', appliedStartDate);
      }
      if (appliedEndDate) {
        params.append('end_date', appliedEndDate);
      }
      if (appliedFeaturedFilter !== '') {
        params.append('featured', appliedFeaturedFilter);
      }
      if (appliedActiveFilter !== '') {
        params.append('active', appliedActiveFilter);
      }
      if (appliedAuthorFilter !== '') {
        params.append('author', appliedAuthorFilter);
      }

      const apiUrl = `/api/internal/guides?${params.toString()}`;
      const response = await fetch(apiUrl);
      
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`API Error: ${response.status} - ${errorText}`);
      }
      
      const data = await response.json();
      
      if (data.success) {
        const guidesData = data.data || [];
        const totalItems = data.meta?.totalItems || data.total || guidesData.length || 0;
        const totalPages = data.meta?.totalPages || Math.ceil(totalItems / limit) || 1;
        
        setGuides(guidesData);
        setTotalItems(totalItems);
        setTotalPages(totalPages);
      } else {
        const items = Array.isArray(data) ? data : data.data;
        if (items) {
          const totalItems = items.length;
          const totalPages = Math.ceil(totalItems / limit);
          
          setGuides(items);
          setTotalItems(totalItems);
          setTotalPages(totalPages);
        } else {
          setGuides([]);
          setTotalItems(0);
          setTotalPages(1);
        }
      }
    } catch (error) {
      console.error("❌ Error fetching guides:", error);
      setGuides([]);
      setTotalItems(0);
      setTotalPages(1);
    } finally {
      setLoading(false);
    }
  };

  const fetchdata = async () => {
    try {
      const [universitiesResponse, subjectsResponse, authorsResponse] = await Promise.all([
        fetch('/api/internal/new/getuniversity', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' }
        }),
        fetch('/api/internal/new/getsubject', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' }
        }),
        fetch('/api/internal/authors?status=active', {
          method: 'GET',
          headers: { 'Content-Type': 'application/json' }
        })
      ]);

      if (!universitiesResponse.ok || !subjectsResponse.ok || !authorsResponse.ok) {
        throw new Error('Failed to fetch data');
      }

      const universityData = await universitiesResponse.json();
      const subjectsData = await subjectsResponse.json();
      const authorsData = await authorsResponse.json();

      setUniversities(universityData.data);
      setSubjects(subjectsData.data);
      setAuthors(authorsData.data || []);
    } catch (error) {
      console.error('Error fetching data:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'Failed to load data',
        confirmButtonColor: '#0B6D76'
      });
    }
  };

  const uploadImage = async (file, uploadType = 'university-logo') => {
    try {
      const formData = new FormData();
      formData.append('image', file);
      formData.append('uploadType', uploadType);

      const response = await fetch('/api/internal/upload', {
        method: 'POST',
        body: formData,
      });

      if (!response.ok) {
        throw new Error('Failed to upload image');
      }

      const data = await response.json();
      return data.url;
    } catch (error) {
      console.error('Error uploading image:', error);
      throw error;
    }
  };

  const handleFileUpload = async (e, field) => {
    const file = e.target.files[0];
    if (!file) return;

    try {
      setIsUploading(true);
      let uploadType = 'university-logo';
      if (field === 'featured_image') uploadType = 'university-feature';
      
      const imageUrl = await uploadImage(file, uploadType);
      setUploadedImages(imageUrl);
    } catch (error) {
      Swal.fire({
        icon: 'error',
        title: 'Upload Error',
        text: error.message || 'Failed to upload image',
        confirmButtonColor: '#0B6D76'
      });
    } finally {
      setIsUploading(false);
    }
  };

  const removeImage = () => {
    setUploadedImages("");
  };

  useEffect(() => { 
    fetchGuides(page);
    fetchdata();
  }, [page, appliedSearchTerm, appliedStartDate, appliedEndDate, appliedFeaturedFilter, appliedActiveFilter, appliedAuthorFilter]);

  const handleSearch = () => {
    setAppliedSearchTerm(searchTerm);
    setAppliedStartDate(startDate);
    setAppliedEndDate(endDate);
    setAppliedFeaturedFilter(featuredFilter);
    setAppliedActiveFilter(activeFilter);
    setAppliedAuthorFilter(authorFilter);
    setPage(1);
  };

  const clearFilters = () => {
    setSearchTerm('');
    setStartDate('');
    setEndDate('');
    setFeaturedFilter('');
    setActiveFilter('');
    setAuthorFilter('');
    setAppliedSearchTerm('');
    setAppliedStartDate('');
    setAppliedEndDate('');
    setAppliedFeaturedFilter('');
    setAppliedActiveFilter('');
    setAppliedAuthorFilter('');
    setPage(1);
  };

  const hasActiveFilters = appliedSearchTerm || appliedStartDate || appliedEndDate || appliedFeaturedFilter !== '' || appliedActiveFilter !== '' || appliedAuthorFilter !== '';

  const parseSEOFromDatabase = (seo) => {
    try {
      if (seo) {
        const seoData = typeof seo === 'string' ? JSON.parse(seo) : seo;
        return {
          show_meta: !!(seoData && (seoData.meta_title || seoData.meta_description || seoData.meta_keywords)),
          meta_title: seoData?.meta_title || "",
          meta_description: seoData?.meta_description || "",
          meta_keywords: seoData?.meta_keywords || ""
        };
      }
      return {
        show_meta: false,
        meta_title: "",
        meta_description: "",
        meta_keywords: ""
      };
    } catch (error) {
      console.warn('Failed to parse SEO from database:', error);
      return {
        show_meta: false,
        meta_title: "",
        meta_description: "",
        meta_keywords: ""
      };
    }
  };

  const formatDate = (dateString) => {
    if (!dateString) return 'N/A';
    try {
      const date = new Date(dateString);
      return date.toLocaleDateString('en-US', {
        year: 'numeric',
        month: 'short',
        day: 'numeric'
      });
    } catch (e) {
      return 'N/A';
    }
  };

  const toggleFeatured = async (id) => {
    try {
      const currentGuide = guides.find((g) => g.id === id);
      const newFeaturedValue = !currentGuide?.is_featured;
      
      const response = await fetch(`/api/internal/guides?id=${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          is_featured: newFeaturedValue,
        }),
      });

      if (response.ok) {
        setGuides((prev) =>
          prev.map((g) =>
            g.id === id ? { ...g, is_featured: newFeaturedValue } : g
          )
        );
        await Swal.fire({ 
          icon: 'success', 
          title: 'Updated', 
          text: `Guide ${newFeaturedValue ? 'featured' : 'unfeatured'} successfully` 
        });
      }
    } catch (error) {
      console.error("Error updating guide:", error);
      await Swal.fire({ icon: 'error', title: 'Error', text: 'Failed to update guide' });
    }
  };

  const handleAssignAuthor = async (guideId, currentAuthorId) => {
    try {
      const selectedAuthorId = prompt(
        'Enter Author ID to assign (or leave empty to remove author):\n' +
        'Available Authors:\n' +
        authors.map(a => `${a.id}: ${a.full_name}`).join('\n'),
        currentAuthorId || ''
      );

      if (selectedAuthorId === null) return;

      const authorId = selectedAuthorId.trim() || null;

      if (authorId && !authors.find(a => a.id == authorId)) {
        alert('Invalid Author ID');
        return;
      }

      const res = await fetch(`/api/internal/guides?id=${guideId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ author_id: authorId })
      });

      if (!res.ok) {
        throw new Error('Failed to update author');
      }

      setGuides(prev => prev.map(guide => 
        guide.id === guideId 
          ? { 
              ...guide, 
              author_id: authorId,
              author_name: authorId ? authors.find(a => a.id == authorId)?.full_name : null,
              author_image: authorId ? authors.find(a => a.id == authorId)?.profile_image : null
            } 
          : guide
      ));

      alert('Author updated successfully');
    } catch (err) {
      console.error('Assign author error:', err);
      alert('Failed to update author');
    }
  };

  const handleEditClick = (guide) => {
    setSelected(guide);
    setUploadedImages(guide.image);
    
    const seoData = parseSEOFromDatabase(guide.seo);
    
    setFormData({
      type: guide.guide_type || "University",
      university_id: guide.university_id || "",
      subject_id: guide.subject_id || "",
      title: guide.title || "",
      slug: guide.slug || "",
      description: guide.description || "",
      featuredImage: null,
      show_meta: seoData.show_meta,
      meta_title: seoData.meta_title,
      meta_description: seoData.meta_description,
      meta_keywords: seoData.meta_keywords,
      active: guide.is_active === 1,
      is_featured: guide.is_featured === 1,
      author_id: guide.author_id || "",
    });
   
    setEditMode(true);
    setShowModal(true);
    fetchdata();
  };

  const handleInputChange = (e) => {
    const { name, value, type, checked } = e.target;
    
    if (name === 'type') {
      setFormData(prev => ({
        ...prev,
        [name]: value,
        university_id: "",
        subject_id: ""
      }));
      return;
    }
    
    if (name === 'title') {
      setFormData(prev => ({
        ...prev,
        [name]: value
      }));
    } else if (type === "checkbox") {
      setFormData(prev => ({
        ...prev,
        [name]: checked,
      }));
    } else {
      setFormData(prev => ({
        ...prev,
        [name]: value,
      }));
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      setIsLoading(true);

      let seo = null;
      if (formData.show_meta) {
        seo = {
          meta_title: formData.meta_title,
          meta_description: formData.meta_description,
          meta_keywords: formData.meta_keywords
        };
      }

      const updateData = {
        guide_type: formData.type,
        title: formData.title,
        slug: formData.slug,
        description: formData.description,
        image: uploadedImages || selected.image,
        is_active: formData.active,
        is_featured: formData.is_featured,
        show_meta: formData.show_meta ? "on" : "off",
        meta_title: formData.meta_title,
        meta_description: formData.meta_description,
        meta_keywords: formData.meta_keywords,
        university_id: formData.university_id || null,
        subject_id: formData.subject_id || null,
        author_id: formData.author_id || null,
        seo: seo
      };

      console.log('Updating guide with data:', updateData);

      const response = await fetch(`/api/internal/guides?id=${selected.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(updateData),
      });

      const responseData = await response.json();

      if (response.ok && responseData.success) {
        fetchGuides(page);
        setEditMode(false);
        setShowModal(false);
        setSelected(null);
        
        await Swal.fire({ 
          icon: 'success', 
          title: 'Success!', 
          text: 'Guide updated successfully!',
          confirmButtonColor: '#10b981'
        });
      } else {
        await Swal.fire({ 
          icon: 'error', 
          title: 'Update Failed', 
          text: responseData.message || 'Failed to update guide. Please try again.',
          confirmButtonColor: '#ef4444'
        });
      }
    } catch (error) {
      console.error("Error updating guide:", error);
      await Swal.fire({ 
        icon: 'error', 
        title: 'Network Error', 
        text: 'Failed to update guide. Please check your connection and try again.',
        confirmButtonColor: '#ef4444'
      });
    } finally{
      setIsLoading(false);
    }
  };

  const handleDelete = async (id) => {
    const confirmed = await Swal.fire({
      title: 'Are you sure?',
      text: "You won't be able to revert this!",
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#d33',
      cancelButtonColor: '#3085d6',
      confirmButtonText: 'Yes, delete it!'
    });

    if (confirmed.isConfirmed) {
      try {
        const res = await fetch(`/api/internal/guides?id=${id}`, { method: 'DELETE' });
        const data = await res.json();

        if (res.ok && data.success) {
          fetchGuides(page);
          await Swal.fire('Deleted!', 'Guide has been deleted.', 'success');
        } else {
          await Swal.fire('Error!', data.message || 'Failed to delete guide', 'error');
        }
      } catch (error) {
        console.error('Delete error:', error);
        await Swal.fire('Error!', 'Network error, please try again.', 'error');
      }
    }
  };

  const getAuthorName = (authorId) => {
    if (!authorId) return 'No Author';
    const author = authors.find(a => a.id == authorId);
    return author ? author.full_name : `Author ID: ${authorId}`;
  };

  if (loading) {
    return (
      <div className="p-6 bg-gray-50 min-h-screen flex items-center justify-center">
        <div className="text-gray-500 text-lg">Loading guides...</div>
      </div>
    );
  }

  const startIndex = (page - 1) * limit;
  const endIndex = startIndex + guides.length;

  return (
    <div className="p-4 sm:p-6 bg-gray-50 min-h-screen">
      <div className="bg-white rounded-2xl shadow-lg p-4 sm:p-6">
        <div className="flex flex-col md:flex-row justify-between md:items-center gap-4 mb-6 sm:mb-8">
          <div>
            <h1 className="text-2xl sm:text-3xl font-bold text-gray-800 mb-1">Guide List</h1>
            <p className="text-gray-600 text-sm sm:text-base">Manage and organize your guides</p>
          </div>
          <div className="flex gap-3">
            <button
              onClick={() => setIsFilterOpen(!isFilterOpen)}
              className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors flex items-center gap-2"
            >
              🔍 Filters {hasActiveFilters && `(${hasActiveFilters})`}
            </button>
            <button
              onClick={() => router.push("/admin/authors")}
              className="px-4 py-2 bg-purple-500 text-white rounded-lg hover:bg-purple-600 transition-colors flex items-center gap-2"
            >
              <User size={16} />
              Manage Authors
            </button>
            <button
              onClick={() => router.push("/admin/guide/add")}
              className="px-4 py-2 bg-gradient-to-b from-[#0B6D76] to-[#094F56] text-white rounded-md flex items-center gap-2"
            >
              <Plus size={16} />
              Add Guide
            </button>
          </div>
        </div>

        {isFilterOpen && (
          <div className="bg-gray-50 rounded-lg p-4 mb-6">
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Search Guides</label>
                <input
                  type="text"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
                  placeholder="Search by title, type, subtitle..."
                  className="w-full p-2 border rounded"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Start Date</label>
                <input
                  type="date"
                  value={startDate}
                  onChange={(e) => setStartDate(e.target.value)}
                  className="w-full p-2 border rounded"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">End Date</label>
                <input
                  type="date"
                  value={endDate}
                  onChange={(e) => setEndDate(e.target.value)}
                  className="w-full p-2 border rounded"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Written By (Author)</label>
                <select
                  value={authorFilter}
                  onChange={(e) => setAuthorFilter(e.target.value)}
                  className="w-full p-2 border rounded"
                >
                  <option value="">All Authors</option>
                  {authors.map((author) => (
                    <option key={author.id} value={author.id}>
                      {author.full_name}
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Featured</label>
                <select
                  value={featuredFilter}
                  onChange={(e) => setFeaturedFilter(e.target.value)}
                  className="w-full p-2 border rounded"
                >
                  <option value="">All</option>
                  <option value="true">Featured</option>
                  <option value="false">Not Featured</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Active</label>
                <select
                  value={activeFilter}
                  onChange={(e) => setActiveFilter(e.target.value)}
                  className="w-full p-2 border rounded"
                >
                  <option value="">All</option>
                  <option value="true">Active</option>
                  <option value="false">Inactive</option>
                </select>
              </div>
              <div className="flex items-end gap-2 sm:col-span-2 lg:col-span-5">
                <button 
                  onClick={handleSearch} 
                  className="px-4 py-2 bg-teal-600 text-white rounded hover:bg-teal-700 flex items-center gap-2"
                >
                  🔍 Search
                </button>
                <button 
                  onClick={clearFilters} 
                  className="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600"
                >
                  Clear Filters
                </button>
              </div>
            </div>

            {(appliedSearchTerm || appliedStartDate || appliedEndDate || appliedFeaturedFilter !== '' || appliedActiveFilter !== '' || appliedAuthorFilter !== '') && (
              <div className="mt-4 pt-4 border-t border-gray-200">
                <div className="text-sm text-gray-600 flex flex-wrap gap-2">
                  Active filters: 
                  {appliedSearchTerm && <span className="px-2 py-1 bg-blue-100 text-blue-800 rounded">Search: "{appliedSearchTerm}"</span>}
                  {appliedStartDate && <span className="px-2 py-1 bg-orange-100 text-orange-800 rounded">From: {formatDate(appliedStartDate)}</span>}
                  {appliedEndDate && <span className="px-2 py-1 bg-yellow-100 text-yellow-800 rounded">To: {formatDate(appliedEndDate)}</span>}
                  {appliedAuthorFilter !== '' && <span className="px-2 py-1 bg-purple-100 text-purple-800 rounded">Author: {getAuthorName(appliedAuthorFilter)}</span>}
                  {appliedFeaturedFilter !== '' && <span className="px-2 py-1 bg-pink-100 text-pink-800 rounded">Featured: {appliedFeaturedFilter === 'true' ? 'Yes' : 'No'}</span>}
                  {appliedActiveFilter !== '' && <span className="px-2 py-1 bg-green-100 text-green-800 rounded">Active: {appliedActiveFilter === 'true' ? 'Yes' : 'No'}</span>}
                </div>
              </div>
            )}
          </div>
        )}

        <div className="overflow-x-auto">
          <table className="min-w-[1400px] w-full text-xs sm:text-sm">
            <thead className="bg-gray-100">
              <tr>
                <th className="py-3 px-4 text-left font-semibold text-gray-600 rounded-l-xl">Image</th>
                <th className="py-3 px-4 text-left font-semibold text-gray-600">Title</th>
                <th className="py-3 px-4 text-left font-semibold text-gray-600">Created By</th>
                <th className="py-3 px-4 text-left font-semibold text-gray-600">Written By</th>
                <th className="py-3 px-4 text-left font-semibold text-gray-600">Type</th>
                <th className="py-3 px-4 text-center font-semibold text-gray-600">Active</th>
                <th className="py-3 px-4 text-center font-semibold text-gray-600">Featured</th>
                <th className="py-3 px-4 text-left font-semibold text-gray-600">Created At</th>
                <th className="py-3 px-4 text-center font-semibold text-gray-600 rounded-r-xl">Action</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {guides.map((guide) => (
                <tr key={guide.id} className="hover:bg-gray-50">
                  <td className="py-3 px-4">
                    {guide.image ? (
                      <img
                        src={guide.image && guide.image.startsWith('/')
                          ? `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com${guide.image}`
                          : `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${guide.image}` || "/default-image.jpg"
                        } 
                        alt={guide.title}
                        className="w-10 h-10 sm:w-12 sm:h-12 object-cover rounded"
                      />
                    ) : (
                      <div className="w-10 h-10 sm:w-12 sm:h-12 bg-gray-200 rounded flex items-center justify-center text-gray-500 text-xs">
                        No Image
                      </div>
                    )}
                  </td>
                  <td className="py-3 px-4 font-medium text-gray-800">
                    <Link href={`/guides/${guide.slug}`} className="hover:text-teal-600 flex items-center gap-1">
                      {guide.title}
                      <ExternalLink size={14} className="opacity-70" />
                    </Link>
                  </td>
                  
                  <td className="py-3 px-4">
                    <div className="flex items-center gap-3">
                      <div className="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center">
                        <User size={14} className="text-gray-500" />
                      </div>
                      <div>
                        <div className="font-medium text-gray-800 text-sm">
                          {guide.created_by_name || `User ${guide.user_id}`}
                        </div>
                        {guide.created_by_email && (
                          <div className="text-xs text-gray-500 truncate max-w-[120px]">
                            {guide.created_by_email}
                          </div>
                        )}
                      </div>
                    </div>
                  </td>
                  
                  <td className="py-3 px-4">
                    {guide.author_id ? (
                      <div className="flex items-center gap-3">
                        {guide.author_image ? (
                          <img 
                            src={guide.author_image} 
                            alt={guide.author_name}
                            className="w-8 h-8 rounded-full object-cover border border-gray-300"
                          />
                        ) : (
                          <div className="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center">
                            <User size={14} className="text-gray-500" />
                          </div>
                        )}
                        <div>
                          <div className="font-medium text-gray-800 text-sm flex items-center gap-1">
                            {guide.author_name}
                            
                          </div>
                          {guide.author_slug && (
                            <div className="text-xs text-gray-500 font-mono">@{guide.author_slug}</div>
                          )}
                        </div>
                      </div>
                    ) : (
                      <div className="flex flex-col gap-1">
                        <div className="text-gray-500 italic text-xs">No Author</div>
                        
                      </div>
                    )}
                  </td>
                  
                  <td className="py-3 px-4 text-gray-600">{guide.guide_type}</td>
                  <td className="py-3 px-4 text-center">
                    <span
                      className={
                        guide.is_active
                          ? "text-green-600 font-semibold"
                          : "text-red-600 font-semibold"
                      }
                    >
                      {guide.is_active ? "Yes" : "No"}
                    </span>
                  </td>
                  <td className="py-3 px-4 text-center">
                    <input
                      type="checkbox"
                      checked={guide.is_featured || false}
                      onChange={() => toggleFeatured(guide.id)}
                      className="w-4 h-4 accent-teal-600"
                    />
                  </td>
                  <td className="py-3 px-4 text-gray-600">
                    {formatDate(guide.created_at)}
                  </td>
                  <td className="py-3 px-4 text-center">
                    <div className="flex justify-center gap-2">
                      <button
                        onClick={() => {
                          setSelected(guide);
                          setShowModal(true);
                          setEditMode(false);
                        }}
                        className="text-blue-600 hover:text-blue-800"
                        title="View"
                      >
                        <Eye className="w-4 h-4 sm:w-5 sm:h-5" />
                      </button>
                      <button
                        onClick={() => handleEditClick(guide)}
                        className="text-green-600 hover:text-green-800"
                        title="Edit"
                      >
                        <Pencil className="w-4 h-4 sm:w-5 sm:h-5" />
                      </button>
                      <button
                        onClick={() => handleDelete(guide.id)}
                        className="text-red-600 hover:text-red-800"
                        title="Delete"
                      >
                        <Trash2 className="w-4 h-4 sm:w-5 sm:h-5" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>

          {guides.length === 0 && !loading && (
            <div className="text-center py-12 text-gray-500 text-lg">
              {hasActiveFilters ? 'No guides found matching your filters.' : 'No guides available.'}
            </div>
          )}

          {(totalPages > 1 || totalItems > limit) && (
            <Pagination
              currentPage={page}
              totalPages={totalPages}
              onPageChange={setPage}
              totalItems={totalItems}
              startIndex={startIndex}
              endIndex={endIndex}
            />
          )}
        </div>
      </div>

      {showModal && selected && (
        <div className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="bg-white/95 backdrop-blur rounded-xl p-4 sm:p-6 w-full max-w-4xl relative max-h-[90vh] overflow-y-auto shadow-xl">
            <button
              onClick={() => {
                setShowModal(false);
                setSelected(null);
                setEditMode(false);
              }}
              className="absolute top-2 right-3 text-gray-500 hover:text-black"
            >
              <X className="w-5 h-5" />
            </button>
            
            <h2 className="text-lg sm:text-xl font-bold mb-4">
              {editMode ? "Edit Guide" : "Guide Details"}
            </h2>

            {editMode ? (
              <form onSubmit={handleSubmit} className="space-y-6">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium">Guide Type</label>
                    <select
                      name="type"
                      value={formData.type}
                      onChange={handleInputChange}
                      className="w-full border px-3 py-2 rounded"
                    >
                      <option value="University">University</option>
                      <option value="Subject">Subject</option>
                    </select>
                  </div>
                  {formData.type === "University" && (
                    <div>
                      <label className="block text-sm font-medium">University</label>
                      <select
                        name="university_id"
                        value={formData.university_id}
                        onChange={handleInputChange}
                        className="w-full border px-3 py-2 rounded"
                      >
                        <option value="">Select University</option>
                        {universities.map((uni) => (
                          <option key={uni.id} value={uni.id}>
                            {uni.name}
                          </option>
                        ))}
                      </select>
                    </div>
                  )}
                  {formData.type === "Subject" && (
                    <div>
                      <label className="block text-sm font-medium">Subject</label>
                      <select
                        name="subject_id"
                        value={formData.subject_id}
                        onChange={handleInputChange}
                        className="w-full border px-3 py-2 rounded"
                      >
                        <option value="">Select Subject</option>
                        {subjects.map((sub) => (
                          <option key={sub.id} value={sub.id}>
                            {sub.name}
                          </option>
                        ))}
                      </select>
                    </div>
                  )}
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium">Title *</label>
                    <input
                      type="text"
                      name="title"
                      value={formData.title}
                      onChange={handleInputChange}
                      className="w-full border px-3 py-2 rounded"
                      required
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium">Slug (Auto-generated)</label>
                    <input
                      type="text"
                      name="slug"
                      value={formData.slug}
                      onChange={handleInputChange}
                      className="w-full border px-3 py-2 rounded bg-gray-50"
                      placeholder="Auto-generated from title"
                    />
                    <p className="text-xs text-gray-500 mt-1">
                      Slug is automatically generated from the title. You can edit it manually if needed.
                    </p>
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium">Written By (Author)</label>
                  <select
                    name="author_id"
                    value={formData.author_id}
                    onChange={handleInputChange}
                    className="w-full border px-3 py-2 rounded"
                  >
                    <option value="">Select Author (Optional)</option>
                    {authors.map((author) => (
                      <option key={author.id} value={author.id}>
                        {author.full_name}
                      </option>
                    ))}
                  </select>
                  <p className="text-xs text-gray-500 mt-1">
                    Select the author who wrote this guide
                  </p>
                </div>

                <div>
                  <label className="block text-sm font-medium">Description</label>
                  <SummernoteEditor
                    value={formData.description}
                    onChange={(val) => setFormData({ ...formData, description: val })}
                  />
                </div>

                <div>
                  <div className="space-y-6">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">Featured Image</label>
                      <input
                        type="file"
                        accept="image/*"
                        onChange={(e) => handleFileUpload(e, 'featured')}
                        className="block w-full text-sm text-gray-500
                          file:mr-4 file:py-2 file:px-4
                          file:rounded-md file:border-0
                          file:text-sm file:font-semibold
                          file:bg-blue-50 file:text-blue-700
                          hover:file:bg-blue-100"
                        disabled={isUploading}
                      />
                      {uploadedImages && (
                        <div className="mt-2">
                          <img
                            src={uploadedImages}
                            alt="Logo preview"
                            className="h-20 object-contain"
                          />
                          <button
                            type="button"
                            onClick={() => removeImage()}
                            className="mt-1 text-red-600 text-sm"
                            disabled={isUploading}
                          >
                            Remove
                          </button>
                        </div>
                      )}
                      {isUploading && !uploadedImages && (
                        <div className="mt-2 text-sm text-gray-500">Uploading Image...</div>
                      )}
                    </div>
                  </div>
                </div>

                <div>
                  <label className="flex items-center space-x-2 text-sm">
                    <input
                      type="checkbox"
                      name="show_meta"
                      checked={formData.show_meta}
                      onChange={handleInputChange}
                    />
                    <span>Enable Meta Tags</span>
                  </label>
                </div>
                {formData.show_meta && (
                  <div className="space-y-4 p-4 border rounded-lg">
                    <div>
                      <label className="block text-sm font-medium mb-1">Meta Title</label>
                      <input
                        type="text"
                        name="meta_title"
                        value={formData.meta_title}
                        onChange={handleInputChange}
                        placeholder="Meta Title"
                        className="w-full border px-3 py-2 rounded"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium mb-1">Meta Description</label>
                      <textarea
                        name="meta_description"
                        value={formData.meta_description}
                        onChange={handleInputChange}
                        placeholder="Meta Description"
                        className="w-full border px-3 py-2 rounded"
                        rows="3"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium mb-1">Meta Keywords</label>
                      <input
                        type="text"
                        name="meta_keywords"
                        value={formData.meta_keywords}
                        onChange={handleInputChange}
                        placeholder="Meta Keywords (comma separated)"
                        className="w-full border px-3 py-2 rounded"
                      />
                      <p className="text-xs text-gray-500 mt-1">
                        Separate keywords with commas (e.g., "keyword1, keyword2, keyword3")
                      </p>
                    </div>
                  </div>
                )}

                <div className="flex items-center gap-4">
                  <label className="flex items-center space-x-2 text-sm">
                    <input
                      type="checkbox"
                      name="active"
                      checked={formData.active}
                      onChange={handleInputChange}
                    />
                    <span>Active</span>
                  </label>
                  <label className="flex items-center space-x-2 text-sm">
                    <input
                      type="checkbox"
                      name="is_featured"
                      checked={formData.is_featured}
                      onChange={handleInputChange}
                    />
                    <span>Featured</span>
                  </label>
                </div>

                <div className="flex justify-end gap-3 pt-4">
                  <button
                    type="button"
                    onClick={() => {
                      setEditMode(false);
                      setShowModal(false);
                      setSelected(null);
                    }}
                    className="px-4 py-2 border rounded hover:bg-gray-100"
                  >
                    Cancel
                  </button>
                  <button
                    type="submit"
                    className="px-4 py-2 bg-teal-600 text-white rounded hover:bg-teal-700"
                    disabled={isLoading}
                  >
                    {isLoading ? "Updating..." : "Save Changes"}
                  </button>
                </div>
              </form>
            ) : (
              <div className="space-y-4">
                {selected.image && (
                  <img
                    src={selected.image}
                    alt={selected.title}
                    className="w-full h-40 object-cover rounded mb-4"
                  />
                )}
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div>
                    <p className="font-medium">Title:</p>
                    <p className="text-gray-700">{selected.title}</p>
                  </div>
                  <div>
                    <p className="font-medium">Type:</p>
                    <p className="text-gray-700">{selected.guide_type}</p>
                  </div>
                  <div>
                    <p className="font-medium">Created By:</p>
                    <div className="flex items-center gap-2 mt-1">
                      <User size={14} className="text-gray-500" />
                      <span className="text-gray-700">
                        {selected.created_by_name || `User ${selected.user_id}`}
                      </span>
                    </div>
                  </div>
                  <div>
                    <p className="font-medium">Written By:</p>
                    {selected.author_id ? (
                      <div className="flex items-center gap-2 mt-1">
                        {selected.author_image ? (
                          <img 
                            src={selected.author_image} 
                            alt={selected.author_name}
                            className="w-6 h-6 rounded-full object-cover"
                          />
                        ) : (
                          <User size={14} className="text-gray-500" />
                        )}
                        <span className="text-gray-700">{selected.author_name}</span>
                      </div>
                    ) : (
                      <span className="text-gray-500 italic">No Author Assigned</span>
                    )}
                  </div>
                  <div>
                    <p className="font-medium">Slug:</p>
                    <p className="text-gray-700">{selected.slug || "N/A"}</p>
                  </div>
                  <div>
                    <p className="font-medium">Status:</p>
                    <span className={`px-2 py-1 rounded text-xs ${selected.is_active ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
                      {selected.is_active ? "Active" : "Inactive"}
                    </span>
                    <span className={`ml-2 px-2 py-1 rounded text-xs ${selected.is_featured ? 'bg-purple-100 text-purple-800' : 'bg-gray-100 text-gray-800'}`}>
                      {selected.is_featured ? "Featured" : "Not Featured"}
                    </span>
                  </div>
                  <div>
                    <p className="font-medium">Created:</p>
                    <p className="text-gray-700">{formatDate(selected.created_at)}</p>
                  </div>
                </div>
                
                {selected.seo && (
                  <div className="mt-4 pt-4 border-t">
                    <h3 className="font-medium mb-2">SEO Data:</h3>
                    <div className="bg-gray-50 p-3 rounded">
                      {(() => {
                        try {
                          const seoData = typeof selected.seo === 'string' ? JSON.parse(selected.seo) : selected.seo;
                          return (
                            <>
                              {seoData.meta_title && (
                                <p className="mb-1"><span className="font-medium">Meta Title:</span> {seoData.meta_title}</p>
                              )}
                              {seoData.meta_description && (
                                <p className="mb-1"><span className="font-medium">Meta Description:</span> {seoData.meta_description}</p>
                              )}
                              {seoData.meta_keywords && (
                                <p className="mb-0"><span className="font-medium">Meta Keywords:</span> {seoData.meta_keywords}</p>
                              )}
                            </>
                          );
                        } catch (e) {
                          return <p className="text-gray-500">SEO data format error</p>;
                        }
                      })()}
                    </div>
                  </div>
                )}
                
                {selected.description && (
                  <div className="mt-4 pt-4 border-t">
                    <h3 className="font-medium mb-2">Description:</h3>
                    <div 
                      className="prose max-w-none text-gray-700 max-h-40 overflow-y-auto"
                      dangerouslySetInnerHTML={{ __html: selected.description }}
                    />
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

export default GuideList;