"use client"

import React, { useEffect, useState, useRef } from 'react'
import { Eye, Trash2, Pencil, Upload, Image as ImageIcon, X } from "lucide-react";
import Swal from 'sweetalert2'
import Pagination from '../../components/Pagination';
import dynamic from 'next/dynamic';

const SummernoteEditor = dynamic(() => import('../../../components/organisms/SummernoteEditor'), { 
  ssr: false,
  loading: () => <div className="p-4 border rounded-lg bg-gray-50 animate-pulse">Loading editor...</div>
});

const jobTypes = ['Full Time', 'Part Time', 'Contract'];
const locationTypes = ['onsite', 'remote'];

const JobList = () => {
    const [filteredJobs, setFilteredJobs] = useState([]);
    const [appliedSearchTerm, setAppliedSearchTerm] = useState('');
    const [appliedSiteType, setAppliedSiteType] = useState('');
    const [searchTerm, setSearchTerm] = useState("");
    const [siteType, setSiteType] = useState(""); // '' | 'onsite' | 'remote'
    const [isFilterOpen, setIsFilterOpen] = useState(false);
    const [selectedJob, setSelectedJob] = useState(null);

    const [currentPage, setCurrentPage] = useState(1);
    const [totalPages, setTotalPages] = useState(0);
    const [totalJobs, setTotalJobs] = useState(0);
    const [itemsPerPage, setItemsPerPage] = useState(5);

    const [isEditing, setIsEditing] = useState(false);
    const [editForm, setEditForm] = useState({
        title: '',
        job_type: '',
        city: '',
        province: '',
        country: '',
        site_based: 'onsite',
        skills: [],
        experience: '',
        requirements: '',
        responsibilities: '',
        description: '',
        image: '',
        active: true
    });
    const [editPreviewImage, setEditPreviewImage] = useState('');
    const [editImageUploading, setEditImageUploading] = useState(false);
    const editFileInputRef = useRef(null);
    
    const editTabs = ['BASIC INFO', 'SKILLS', 'REQUIREMENTS', 'RESPONSIBILITIES', 'DESCRIPTION'];
    const [editActiveTab, setEditActiveTab] = useState('BASIC INFO');
    const [newSkill, setNewSkill] = useState('');

    // Function to safely render HTML content
    const renderHTML = (html) => {
        if (!html) return '';
        return { __html: html };
    };

    const handleDelete = async (id) => {
        const result = 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!',
            cancelButtonText: 'Cancel'
        });
    
        if (result.isConfirmed) {
            try {
                const response = await fetch(`/api/internal/jobs/${id}`, {
                    method: "DELETE",
                });
                
                if (!response.ok) {
                    const data = await response.json();
                    throw new Error(`Failed to delete job: ${data.message}`);
                }

                const data = await response.json();
                Swal.fire({
                    title: 'Success',
                    text: data.message,
                    icon: 'success',
                    confirmButtonText: 'OK'
                });
                
                await fetchJobs();
                return true;
            } catch (error) {
                console.error("Error deleting job:", error);
                Swal.fire({
                    title: 'Error',
                    text: error.message,
                    icon: 'error',
                    confirmButtonText: 'OK'
                });
                return false;
            }
        }
    };

    const toggleActive = async (id, currentStatus) => {
        try {
            const response = await fetch(`/api/internal/jobs/${id}`, {
                method: "PATCH",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                    active: !currentStatus
                }),
            });
            
            if (!response.ok) {
                const data = await response.json();
                throw new Error(data.message || 'Failed to update job status');
            }

            await fetchJobs();
            Swal.fire({
                title: 'Success',
                text: 'Job status updated successfully',
                icon: 'success',
                confirmButtonText: 'OK'
            });
        } catch (error) {
            console.error("Error updating job status:", error);
            Swal.fire({
                title: 'Error',
                text: error.message,
                icon: 'error',
                confirmButtonText: 'OK'
            });
        }
    };

    const handleEditClick = (job) => {
        setSelectedJob(job);
        setEditForm({
            title: job.title,
            job_type: job.job_type,
            city: job.city,
            province: job.province,
            country: job.country,
            site_based: job.site_based || 'onsite',
            skills: job.skills ? [...job.skills] : [],
            experience: job.experience || '',
            requirements: job.requirements || '',
            responsibilities: job.responsibilities || '',
            description: job.description || '',
            image: job.image || '',
            active: job.post_status === 1
        });
        setEditPreviewImage(job.image || '');
        setNewSkill('');
        setIsEditing(true);
        setEditActiveTab('BASIC INFO');
    };

    const handleEditChange = (e) => {
        const { name, value, type, checked } = e.target;
        setEditForm(prev => ({
            ...prev,
            [name]: type === 'checkbox' ? checked : value
        }));
    };

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

        // Validate file type
        const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif'];
        if (!validTypes.includes(file.type)) {
            Swal.fire({
                title: 'Invalid File Type',
                text: 'Please upload an image file (JPEG, PNG, WebP, or GIF)',
                icon: 'error',
                confirmButtonText: 'OK'
            });
            return;
        }

        // Validate file size (max 5MB)
        if (file.size > 5 * 1024 * 1024) {
            Swal.fire({
                title: 'File Too Large',
                text: 'Please upload an image smaller than 5MB',
                icon: 'error',
                confirmButtonText: 'OK'
            });
            return;
        }

        try {
            setEditImageUploading(true);
            const formData = new FormData();
            formData.append('image', file);
            formData.append('uploadType', 'jobs');

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

            const data = await res.json();
            
            if (data.success && data.url) {
                setEditForm(prev => ({ 
                    ...prev, 
                    image: data.url 
                }));
                setEditPreviewImage(data.url);
                Swal.fire({
                    title: 'Success',
                    text: 'Image uploaded successfully',
                    icon: 'success',
                    confirmButtonText: 'OK'
                });
            } else {
                Swal.fire({
                    title: 'Upload Failed',
                    text: data.message || 'Image upload failed',
                    icon: 'error',
                    confirmButtonText: 'OK'
                });
            }
        } catch (error) {
            console.error('Upload error:', error);
            Swal.fire({
                title: 'Error',
                text: 'Image upload error. Please try again.',
                icon: 'error',
                confirmButtonText: 'OK'
            });
        } finally {
            setEditImageUploading(false);
            if (editFileInputRef.current) {
                editFileInputRef.current.value = '';
            }
        }
    };

    const removeEditImage = () => {
        setEditForm(prev => ({ ...prev, image: '' }));
        setEditPreviewImage('');
    };

    const addEditSkill = () => {
        if (newSkill.trim() && !editForm.skills.includes(newSkill.trim())) {
            setEditForm(prev => ({
                ...prev,
                skills: [...prev.skills, newSkill.trim()]
            }));
            setNewSkill('');
        }
    };

    const removeEditSkill = (skill) => {
        setEditForm(prev => ({
            ...prev,
            skills: prev.skills.filter((s) => s !== skill)
        }));
    };

    const fetchJobs = async () => {
        const params = new URLSearchParams();
        if (appliedSearchTerm) params.append('search', appliedSearchTerm);
        if (appliedSiteType) params.append('site_type', appliedSiteType);
        params.append('items_per_page', itemsPerPage);
        params.append('page', currentPage);
        
        try {
            const res = await fetch(`/api/internal/jobs?${params.toString()}`);
            if (!res.ok) {
                const data = await res.json();
                Swal.fire({
                    title: 'Error',
                    text: data.message,
                    icon: 'error',
                    confirmButtonText: 'OK'
                });
                return;
            }

            const data = await res.json();
            
            setFilteredJobs(
                data.jobs.map(job => ({
                    ...job,
                    skills: job.skills ? job.skills.split(',').map(s => s.trim()).filter(Boolean) : [],
                    active: job.post_status === 1,
                }))
            );

            setTotalPages(data.totalPages);
            setTotalJobs(data.totalJobs);
        } catch (e) {
            console.error(e);
            Swal.fire({
                title: 'Error',
                text: 'Something went wrong while fetching jobs.',
                icon: 'error',
                confirmButtonText: 'OK'
            });
        }
    };

    useEffect(() => {
        fetchJobs();
    }, [appliedSearchTerm, appliedSiteType, currentPage, itemsPerPage]);

    const handleEditSubmit = async (e) => {
        e.preventDefault();

        if (!selectedJob) return;

        try {
            const response = await fetch(`/api/internal/jobs/${selectedJob.id}`, {
                method: "PUT",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(editForm),
            });
            
            if (!response.ok) {
                const data = await response.json();
                Swal.fire({
                    title: 'Error',
                    text: data.message || 'Failed to update job',
                    icon: 'error',
                    confirmButtonText: 'OK'
                });
                return;
            }

            const data = await response.json();
            Swal.fire({
                title: 'Success',
                text: data.message || 'Job updated successfully',
                icon: 'success',
                confirmButtonText: 'OK'
            });

            setIsEditing(false);
            setSelectedJob(null);
            setEditPreviewImage('');
            await fetchJobs();
            
        } catch (error) {
            console.error("Error updating job:", error);
            Swal.fire({
                title: 'Error',
                text: 'An error occurred while updating the job',
                icon: 'error',
                confirmButtonText: 'OK'
            });
        }
    };

    const toggleFilter = () => setIsFilterOpen(!isFilterOpen);

    const handleSearch = () => {
        setAppliedSearchTerm(searchTerm);
        setAppliedSiteType(siteType);
        setIsFilterOpen(false);
        setCurrentPage(1);
    };

    const clearFilters = () => {
        setSearchTerm("");
        setSiteType("");
        setAppliedSearchTerm("");
        setAppliedSiteType("");
        setCurrentPage(1);
    };

    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;

    const renderEditContent = () => {
        switch (editActiveTab) {
            case 'BASIC INFO':
                return (
                    <div className="space-y-4">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">Job Title*</label>
                                <input
                                    type="text"
                                    name="title"
                                    value={editForm.title}
                                    onChange={handleEditChange}
                                    className="w-full p-2 border rounded"
                                    required
                                />
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">Job Type*</label>
                                <select
                                    name="job_type"
                                    value={editForm.job_type}
                                    onChange={handleEditChange}
                                    className="w-full p-2 border rounded"
                                    required
                                >
                                    <option value="">Select Job Type</option>
                                    {jobTypes.map((type) => (
                                        <option key={type} value={type}>{type}</option>
                                    ))}
                                </select>
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">Work Location*</label>
                                <select
                                    name="site_based"
                                    value={editForm.site_based}
                                    onChange={handleEditChange}
                                    className="w-full p-2 border rounded"
                                    required
                                >
                                    {locationTypes.map((type) => (
                                        <option key={type} value={type}>
                                            {type.charAt(0).toUpperCase() + type.slice(1)}
                                        </option>
                                    ))}
                                </select>
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">Experience Level</label>
                                <input
                                    type="text"
                                    name="experience"
                                    value={editForm.experience}
                                    onChange={handleEditChange}
                                    className="w-full p-2 border rounded"
                                />
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">City</label>
                                <input
                                    type="text"
                                    name="city"
                                    value={editForm.city}
                                    onChange={handleEditChange}
                                    className="w-full p-2 border rounded"
                                />
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">Province/State</label>
                                <input
                                    type="text"
                                    name="province"
                                    value={editForm.province}
                                    onChange={handleEditChange}
                                    className="w-full p-2 border rounded"
                                />
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">Country</label>
                                <input
                                    type="text"
                                    name="country"
                                    value={editForm.country}
                                    onChange={handleEditChange}
                                    className="w-full p-2 border rounded"
                                />
                            </div>
                            <div className="flex items-center">
                                <label className="flex items-center gap-2">
                                    <input
                                        type="checkbox"
                                        name="active"
                                        checked={editForm.active}
                                        onChange={handleEditChange}
                                        className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                                    />
                                    <span className="text-sm text-gray-700">Active Job Post</span>
                                </label>
                            </div>
                        </div>

                        {/* Image Upload Section */}
                        <div className="border-t pt-4">
                            <label className="block text-sm font-medium text-gray-700 mb-2">Job Image (Optional)</label>
                            <div className="space-y-3">
                                <div className="flex items-center gap-3">
                                    <input
                                        type="file"
                                        ref={editFileInputRef}
                                        accept="image/*"
                                        onChange={handleEditImageChange}
                                        className="hidden"
                                        id="edit-image-upload"
                                    />
                                    <label
                                        htmlFor="edit-image-upload"
                                        className="bg-gray-100 hover:bg-gray-200 text-gray-800 font-medium rounded-lg transition-colors border border-gray-300 px-4 py-2 cursor-pointer flex items-center gap-2"
                                    >
                                        <Upload size={16} />
                                        {editImageUploading ? 'Uploading...' : 'Choose Image'}
                                    </label>
                                    <span className="text-sm text-gray-500">
                                        JPEG, PNG, WebP, GIF (Max 5MB)
                                    </span>
                                </div>
                                
                                {editPreviewImage && (
                                    <div className="mt-2">
                                        <p className="text-sm text-gray-600 mb-1">Preview:</p>
                                        <div className="relative inline-block">
                                            <img
                                                src={editPreviewImage}
                                                alt="Preview"
                                                className="h-32 w-auto rounded-lg border object-cover"
                                            />
                                            <button
                                                type="button"
                                                onClick={removeEditImage}
                                                className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1 hover:bg-red-600"
                                            >
                                                <X size={14} />
                                            </button>
                                        </div>
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                );

            case 'SKILLS':
                return (
                    <div className="space-y-4">
                        <div className="flex flex-col sm:flex-row gap-2">
                            <div className="flex-1">
                                <input
                                    type="text"
                                    placeholder="Add required skill (e.g. React, Python)"
                                    value={newSkill}
                                    onChange={(e) => setNewSkill(e.target.value)}
                                    onKeyDown={(e) => e.key === 'Enter' && (e.preventDefault(), addEditSkill())}
                                    className="w-full p-2 border rounded"
                                />
                            </div>
                            <button
                                type="button"
                                onClick={addEditSkill}
                                className="bg-gray-100 hover:bg-gray-200 text-gray-800 font-medium rounded-lg transition-colors border border-gray-300 px-4 py-2 flex items-center gap-1"
                            >
                                <span className="text-lg">+</span> Add
                            </button>
                        </div>
                        <div className="flex flex-wrap gap-2">
                            {editForm.skills.map((skill, index) => (
                                <span
                                    key={index}
                                    className="inline-flex items-center bg-blue-100 text-blue-800 text-sm px-3 py-1 rounded-full"
                                >
                                    {skill}
                                    <button
                                        type="button"
                                        onClick={() => removeEditSkill(skill)}
                                        className="ml-1 text-blue-600 hover:text-blue-800"
                                    >
                                        <X size={14} />
                                    </button>
                                </span>
                            ))}
                        </div>
                    </div>
                );

            case 'REQUIREMENTS':
                return (
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">Requirements</label>
                        <SummernoteEditor
                            key="requirements-editor"
                            value={editForm.requirements}
                            onChange={(val) => setEditForm(prev => ({ ...prev, requirements: val }))}
                            placeholder="List the requirements for this position..."
                        />
                    </div>
                );

            case 'RESPONSIBILITIES':
                return (
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">Responsibilities</label>
                        <SummernoteEditor
                            key="responsibilities-editor"
                            value={editForm.responsibilities}
                            onChange={(val) => setEditForm(prev => ({ ...prev, responsibilities: val }))}
                            placeholder="Describe the responsibilities for this role..."
                        />
                    </div>
                );

            case 'DESCRIPTION':
                return (
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">Description</label>
                        <SummernoteEditor
                            key="description-editor"
                            value={editForm.description}
                            onChange={(val) => setEditForm(prev => ({ ...prev, description: val }))}
                            placeholder="Provide a detailed description of the job..."
                        />
                    </div>
                );

            default:
                return null;
        }
    };

    return (
        <>
            <title>Jobs List - University Page</title>
            <div className="p-4 sm:p-6 bg-gray-50">
                <div className="flex justify-between items-center mb-6">
                    <h1 className="text-2xl sm:text-3xl font-bold text-gray-800">
                        Job Listings
                    </h1>
                    <button
                        onClick={toggleFilter}
                        className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors flex items-center gap-2"
                    >
                        🔍 Filters
                    </button>
                </div>

                {/* Filter Section */}
                {isFilterOpen && (
                    <div className="bg-white rounded-lg shadow-md p-4 mb-6">
                        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">Search Jobs</label>
                                <input
                                    type="text"
                                    value={searchTerm}
                                    onChange={(e) => setSearchTerm(e.target.value)}
                                    onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
                                    placeholder="Search by title, type, location, skills..."
                                    className="w-full p-2 border rounded"
                                />
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">Site Type</label>
                                <select
                                    value={siteType}
                                    onChange={(e) => setSiteType(e.target.value)}
                                    className="w-full p-2 border rounded"
                                >
                                    <option value="">All</option>
                                    <option value="onsite">Onsite</option>
                                    <option value="remote">Remote</option>
                                </select>
                            </div>
                            <div className="flex items-end gap-2">
                                <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>

                        {/* Active Filters Display */}
                        {(appliedSearchTerm || appliedSiteType) && (
                            <div className="mt-4 pt-4 border-t border-gray-200">
                                <div className="text-sm text-gray-600">
                                    Active filters: 
                                    {appliedSearchTerm && <span className="ml-2 px-2 py-1 bg-blue-100 text-blue-800 rounded">Search: "{appliedSearchTerm}"</span>}
                                    {appliedSiteType && <span className="ml-2 px-2 py-1 bg-green-100 text-green-800 rounded">Site Type: {appliedSiteType === 'onsite' ? 'Onsite' : 'Remote'}</span>}
                                </div>
                            </div>
                        )}
                    </div>
                )}

                <div className="bg-white rounded-2xl shadow-lg p-4 sm:p-6">
                    <div className="overflow-x-auto">
                        <table className="w-full min-w-[900px]">
                            <thead className="sticky top-0 bg-gray-100 z-10">
                                <tr>
                                    <th className="py-3 px-4 text-left text-sm font-semibold text-gray-600 rounded-l-xl">Title</th>
                                    <th className="py-3 px-4 text-left text-sm font-semibold text-gray-600">Job Type</th>
                                    <th className="py-3 px-4 text-left text-sm font-semibold text-gray-600">Location</th>
                                    <th className="py-3 px-4 text-left text-sm font-semibold text-gray-600">Site Type</th>
                                    <th className="py-3 px-4 text-left text-sm font-semibold text-gray-600">Skills</th>
                                    <th className="py-3 px-4 text-left text-sm font-semibold text-gray-600">Status</th>
                                    <th className="py-3 px-4 text-center text-sm font-semibold text-gray-600 rounded-r-xl">Action</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-gray-200">
                                {filteredJobs.map((job) => (
                                    <tr key={job.id} className="hover:bg-gray-50 transition-colors">
                                        <td className="py-3 px-4 font-medium text-gray-800">{job.title}</td>
                                        <td className="py-3 px-4 text-gray-600">{job.job_type}</td>
                                        <td className="py-3 px-4 text-gray-600">{[job.city, job.province, job.country].filter(Boolean).join(", ")}</td>
                                        <td className="py-3 px-4 text-gray-600">
                                            {job.site_based === 'onsite' ? 'Onsite' : 
                                             job.site_based === 'remote' ? 'Remote' : 
                                             'Not specified'}
                                        </td>
                                        <td className="py-3 px-4 text-gray-600">
                                            <div className="flex flex-wrap gap-1">
                                                {(Array.isArray(job.skills) ? job.skills : []).slice(0, 2).map((skill, index) => (
                                                    <span key={index} className="bg-blue-100 text-blue-800 text-xs font-medium px-2 py-1 rounded-full">
                                                        {skill.trim()}
                                                    </span>
                                                ))}
                                                {job.skills && job.skills.length > 2 && (
                                                    <span className="text-xs font-medium p-1">
                                                        +{job.skills.length - 2} more
                                                    </span>
                                                )}
                                            </div>
                                        </td>
                                        <td className="py-3 px-4">
                                            <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                                                job.active ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                                            }`}>
                                                {job.active ? 'Active' : 'Inactive'}
                                            </span>
                                        </td>
                                        <td className="py-3 px-4 text-center">
                                            <div className="flex items-center justify-center gap-2 flex-wrap">
                                                <button
                                                    onClick={() => toggleActive(job.id, job.active)}
                                                    className={`px-3 py-1 text-xs font-medium rounded ${
                                                        job.active 
                                                            ? 'bg-red-100 text-red-700 hover:bg-red-200' 
                                                            : 'bg-green-100 text-green-700 hover:bg-green-200'
                                                    }`}
                                                >
                                                    {job.active ? 'Deactivate' : 'Activate'}
                                                </button>
                                                <button
                                                    onClick={() => setSelectedJob(job)}
                                                    className="text-blue-500 hover:text-blue-700 p-1"
                                                >
                                                    <Eye size={18} />
                                                </button>
                                                <button
                                                    onClick={() => handleEditClick(job)}
                                                    className="text-green-500 hover:text-green-700 p-1"
                                                >
                                                    <Pencil size={18} />
                                                </button>
                                                <button
                                                    onClick={() => handleDelete(job.id)}
                                                    className="text-red-500 hover:text-red-700 p-1"
                                                >
                                                    <Trash2 size={18} />
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                    {filteredJobs.length === 0 && (
                        <div className="text-center py-12">
                            <p className="text-gray-500 text-lg">No jobs found.</p>
                        </div>
                    )}
                    <Pagination
                        currentPage={currentPage}
                        totalPages={totalPages}
                        onPageChange={setCurrentPage}
                        totalItems={totalJobs}
                        startIndex={startIndex}
                        endIndex={endIndex > totalJobs ? totalJobs : endIndex}
                    />
                </div>

                {/* View Modal */}
                {selectedJob && !isEditing && (
                    <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
                        <div className="bg-white/90 backdrop-blur-md w-full max-w-4xl max-h-[90vh] rounded-xl shadow-xl p-6 overflow-y-auto">
                            <div className="flex justify-between items-start mb-4">
                                <h2 className="text-lg sm:text-xl font-bold">{selectedJob.title}</h2>
                                {selectedJob.image && (
                                    <img 
                                        src={selectedJob.image} 
                                        alt={selectedJob.title}
                                        className="h-20 w-20 object-cover rounded-lg border"
                                    />
                                )}
                            </div>
                            
                            {/* Basic Info Section */}
                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-6">
                                <div>
                                    <p><strong>Job Type:</strong> {selectedJob.job_type}</p>
                                    <p><strong>Location:</strong> {[selectedJob.city, selectedJob.province, selectedJob.country].filter(Boolean).join(", ")}</p>
                                    <p><strong>Site Type:</strong> {selectedJob.site_based === 'onsite' ? 'Onsite' : selectedJob.site_based === 'remote' ? 'Remote' : 'Not specified'}</p>
                                    <p><strong>Experience:</strong> {selectedJob.experience || 'Not specified'}</p>
                                </div>
                                <div>
                                    <p><strong>Status:</strong> <span className={selectedJob.active ? "text-green-600" : "text-red-600"}>{selectedJob.active ? "Active" : "Inactive"}</span></p>
                                    <div className="mt-2">
                                        <strong>Skills:</strong>
                                        <div className="flex flex-wrap gap-2 mt-2">
                                            {(selectedJob.skills || []).map((skill) => (
                                                <span key={skill} className="bg-gray-200 text-gray-800 text-sm font-medium px-3 py-1 rounded-full">
                                                    {skill}
                                                </span>
                                            ))}
                                        </div>
                                    </div>
                                </div>
                            </div>

                            {/* Rich Text Content Sections */}
                            {selectedJob.requirements && (
                                <div className="mb-6">
                                    <h3 className="text-lg font-semibold mb-2 text-gray-800">Requirements</h3>
                                    <div className="bg-gray-50 p-4 rounded-lg" dangerouslySetInnerHTML={renderHTML(selectedJob.requirements)} />
                                </div>
                            )}

                            {selectedJob.responsibilities && (
                                <div className="mb-6">
                                    <h3 className="text-lg font-semibold mb-2 text-gray-800">Responsibilities</h3>
                                    <div className="bg-gray-50 p-4 rounded-lg" dangerouslySetInnerHTML={renderHTML(selectedJob.responsibilities)} />
                                </div>
                            )}

                            {selectedJob.description && (
                                <div className="mb-6">
                                    <h3 className="text-lg font-semibold mb-2 text-gray-800">Description</h3>
                                    <div className="bg-gray-50 p-4 rounded-lg" dangerouslySetInnerHTML={renderHTML(selectedJob.description)} />
                                </div>
                            )}

                            <div className="flex justify-end gap-3 mt-6">
                                <button
                                    onClick={() => handleEditClick(selectedJob)}
                                    className="px-4 py-2 bg-teal-600 text-white rounded hover:bg-teal-700 flex items-center gap-2"
                                >
                                    <Pencil size={16} /> Edit
                                </button>
                                <button
                                    className="px-4 py-2 bg-gray-200 rounded hover:bg-gray-300"
                                    onClick={() => setSelectedJob(null)}
                                >
                                    Close
                                </button>
                            </div>
                        </div>
                    </div>
                )}

                {/* Edit Modal */}
                {selectedJob && isEditing && (
                    <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
                        <div className="bg-white/95 backdrop-blur rounded-xl shadow-xl p-4 w-full max-w-4xl max-h-[90vh] flex flex-col">
                            <div className="flex justify-between items-center mb-4">
                                <h2 className="text-lg sm:text-xl font-bold">Edit Job</h2>
                                <button
                                    onClick={() => {
                                        setIsEditing(false);
                                        setEditPreviewImage('');
                                    }}
                                    className="text-gray-500 hover:text-gray-700"
                                >
                                    <X size={20} />
                                </button>
                            </div>
                            
                            {/* Tabs */}
                            <div className="flex gap-2 mb-4 flex-wrap border-b pb-2">
                                {editTabs.map((tab) => (
                                    <button
                                        key={tab}
                                        type="button"
                                        onClick={() => setEditActiveTab(tab)}
                                        className={`px-3 py-1 rounded-lg text-sm font-medium ${editActiveTab === tab ? 'bg-teal-600 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'}`}
                                    >
                                        {tab}
                                    </button>
                                ))}
                            </div>
                            
                            <form onSubmit={handleEditSubmit} className="flex-1 overflow-y-auto">
                                <div className="space-y-4">
                                    {renderEditContent()}
                                </div>

                                {/* Navigation/Action Buttons */}
                                <div className="flex justify-between gap-3 mt-6 pt-4 border-t">
                                    <button
                                        type="button"
                                        onClick={() => {
                                            setIsEditing(false);
                                            setEditPreviewImage('');
                                        }}
                                        className="px-4 py-2 bg-gray-200 rounded hover:bg-gray-300"
                                    >
                                        Cancel
                                    </button>
                                    <div className="flex gap-2">
                                        {editActiveTab !== 'BASIC INFO' && (
                                            <button
                                                type="button"
                                                onClick={() => setEditActiveTab(editTabs[editTabs.indexOf(editActiveTab) - 1])}
                                                className="px-4 py-2 bg-gray-200 rounded hover:bg-gray-300"
                                            >
                                                Previous
                                            </button>
                                        )}
                                        {editActiveTab !== 'DESCRIPTION' ? (
                                            <button
                                                type="button"
                                                onClick={() => setEditActiveTab(editTabs[editTabs.indexOf(editActiveTab) + 1])}
                                                className="px-4 py-2 bg-teal-600 text-white rounded hover:bg-teal-700"
                                            >
                                                Next
                                            </button>
                                        ) : (
                                            <button
                                                type="submit"
                                                className="px-4 py-2 bg-teal-600 text-white rounded hover:bg-teal-700"
                                                disabled={editImageUploading}
                                            >
                                                {editImageUploading ? 'Saving...' : 'Save Changes'}
                                            </button>
                                        )}
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                )}
            </div>
        </>
    );
};

export default JobList;