import AdminLayout from '@/Layouts/AdminLayout';
import { Head, Link, router } from '@inertiajs/react';
import { useState, useEffect } from 'react';
import { 
    ClockIcon, 
    EyeIcon, 
    EnvelopeOpenIcon,
    CheckCircleIcon,
    XMarkIcon,
    BellIcon,
    FunnelIcon,
    ChevronDownIcon,
    UserIcon,
    InformationCircleIcon
} from '@heroicons/react/24/outline';
import { CheckIcon as CheckSolidIcon } from '@heroicons/react/24/solid';
import Modal from '@/Components/Modal';

// Helper function for date formatting
const formatDateTime = (dateString) => {
    if (!dateString) return 'N/A';
    
    const date = new Date(dateString);
    const options = { 
        year: 'numeric', 
        month: 'short', 
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    };
    return date.toLocaleDateString('en-US', options);
};

export default function Index({ notifications }) {
    const [searchTerm, setSearchTerm] = useState('');
    const [filterStatus, setFilterStatus] = useState('all');
    const [filteredNotifications, setFilteredNotifications] = useState(notifications?.data || []);
    const [showModal, setShowModal] = useState(false);
    const [selectedNotification, setSelectedNotification] = useState(null);
    const [isFilterExpanded, setIsFilterExpanded] = useState(false);
    const [isMobileView, setIsMobileView] = useState(false);

    // Detect screen size
    useEffect(() => {
        const handleResize = () => {
            setIsMobileView(window.innerWidth < 768);
        };
        
        handleResize(); // Initial check
        window.addEventListener('resize', handleResize);
        
        return () => window.removeEventListener('resize', handleResize);
    }, []);

    useEffect(() => {
        let filtered = notifications?.data || [];

        // Filter by search term
        if (searchTerm) {
            filtered = filtered.filter(notification =>
                notification.data.message.toLowerCase().includes(searchTerm.toLowerCase())
            );
        }

        // Filter by status
        if (filterStatus !== 'all') {
            if (filterStatus === 'read') {
                filtered = filtered.filter(notification => notification.read_at);
            } else if (filterStatus === 'unread') {
                filtered = filtered.filter(notification => !notification.read_at);
            }
        }

        setFilteredNotifications(filtered);
    }, [searchTerm, filterStatus, notifications?.data]);

    const markAsRead = (id) => {
        router.post(route('admin.notifications.markAsRead', id), {}, {
            preserveScroll: true,
        });
    };

    const viewDetails = (notification) => {
        setSelectedNotification(notification);
        setShowModal(true);
        
        // Mark as read if not already read
        if (!notification.read_at) {
            markAsRead(notification.id);
        }
    };

    const closeModal = () => {
        setShowModal(false);
        setSelectedNotification(null);
    };

    const getStatusColor = (isRead) => {
        return isRead 
            ? 'bg-gray-100 text-gray-800 border-gray-200' 
            : 'bg-blue-100 text-blue-800 border-blue-200';
    };

    const hasNotifications = notifications && notifications.data && notifications.data.length > 0;
    const unreadCount = notifications?.data ? notifications.data.filter(n => !n.read_at).length : 0;
    const readCount = notifications?.data ? notifications.data.filter(n => n.read_at).length : 0;

    return (
        <AdminLayout>
            <Head title="My Notifications" />

            <div className="py-4 sm:py-6 bg-gray-50 min-h-screen">
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                    
                    {/* Header Section with Gradient Background */}
                    <div className="bg-gradient-to-r from-blue-600 to-indigo-700 rounded-xl shadow-xl p-4 sm:p-6 mb-6 sm:mb-8 text-white">
                        <h1 className="text-2xl sm:text-3xl font-bold mb-2">Notifications Center 🔔</h1>
                        <p className="text-blue-100 text-sm sm:text-base">Welcome back. Here you can manage all your administrative notifications.</p>
                    </div>

                    {/* Stats Cards with Enhanced Design */}
                    <div className="grid grid-cols-2 sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 mb-6 sm:mb-8">
                        <div className="bg-white overflow-hidden shadow-lg rounded-xl border border-gray-100 hover:shadow-xl transition-all duration-300 transform hover:-translate-y-1">
                            <div className="p-3 sm:p-5">
                                <div className="flex items-center">
                                    <div className="bg-blue-600 rounded-xl p-2 sm:p-3 flex-shrink-0">
                                        <BellIcon className="h-5 w-5 sm:h-6 sm:w-6 text-white" />
                                    </div>
                                    <div className="ml-3 sm:ml-5 w-0 flex-1">
                                        <dl>
                                            <dt className="text-xs sm:text-sm font-medium text-gray-500 truncate">Total</dt>
                                            <dd className="text-lg sm:text-xl font-bold text-gray-900">{notifications?.total || 0}</dd>
                                        </dl>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div className="bg-white overflow-hidden shadow-lg rounded-xl border border-gray-100 hover:shadow-xl transition-all duration-300 transform hover:-translate-y-1">
                            <div className="p-3 sm:p-5">
                                <div className="flex items-center">
                                    <div className="bg-indigo-600 rounded-xl p-2 sm:p-3 flex-shrink-0">
                                        <EyeIcon className="h-5 w-5 sm:h-6 sm:w-6 text-white" />
                                    </div>
                                    <div className="ml-3 sm:ml-5 w-0 flex-1">
                                        <dl>
                                            <dt className="text-xs sm:text-sm font-medium text-gray-500 truncate">Read</dt>
                                            <dd className="text-lg sm:text-xl font-bold text-gray-900">{readCount}</dd>
                                        </dl>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div className="bg-white overflow-hidden shadow-lg rounded-xl border border-gray-100 hover:shadow-xl transition-all duration-300 transform hover:-translate-y-1">
                            <div className="p-3 sm:p-5">
                                <div className="flex items-center">
                                    <div className="bg-yellow-500 rounded-xl p-2 sm:p-3 flex-shrink-0">
                                        <EnvelopeOpenIcon className="h-5 w-5 sm:h-6 sm:w-6 text-white" />
                                    </div>
                                    <div className="ml-3 sm:ml-5 w-0 flex-1">
                                        <dl>
                                            <dt className="text-xs sm:text-sm font-medium text-gray-500 truncate">Unread</dt>
                                            <dd className="text-lg sm:text-xl font-bold text-gray-900">{unreadCount}</dd>
                                        </dl>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div className="bg-white overflow-hidden shadow-lg rounded-xl border border-gray-100 hover:shadow-xl transition-all duration-300 transform hover:-translate-y-1">
                            <div className="p-3 sm:p-5">
                                <div className="flex items-center">
                                    <div className="bg-purple-600 rounded-xl p-2 sm:p-3 flex-shrink-0">
                                        <ClockIcon className="h-5 w-5 sm:h-6 sm:w-6 text-white" />
                                    </div>
                                    <div className="ml-3 sm:ml-5 w-0 flex-1">
                                        <dl>
                                            <dt className="text-xs sm:text-sm font-medium text-gray-500 truncate">Latest</dt>
                                            <dd className="text-lg sm:text-xl font-bold text-gray-900">
                                                {notifications?.data && notifications.data.length > 0 
                                                    ? formatDateTime(notifications.data[0].created_at) 
                                                    : 'N/A'}
                                            </dd>
                                        </dl>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Main Content Card */}
                    <div className="bg-white shadow-xl rounded-xl overflow-hidden border border-gray-100">
                        <div className="p-4 sm:p-6 border-b border-gray-100">
                            <h2 className="text-xl font-semibold text-gray-800">Notification Management</h2>
                        </div>
                        
                        {/* Search and Filter Section */}
                        <div className="p-4 sm:p-6">
                            <div className="flex flex-col gap-3 sm:gap-4">
                                <div className="relative w-full">
                                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                        <svg className="h-5 w-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                                        </svg>
                                    </div>
                                    <input
                                        type="text"
                                        className="block w-full pl-10 pr-3 py-2 sm:py-3 border border-gray-300 rounded-lg leading-5 bg-white placeholder-gray-500 focus:outline-none focus:placeholder-gray-400 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm transition"
                                        placeholder="Search notifications..."
                                        value={searchTerm}
                                        onChange={(e) => setSearchTerm(e.target.value)}
                                    />
                                </div>
                                <div className="flex justify-between items-center">
                                    <button
                                        onClick={() => setIsFilterExpanded(!isFilterExpanded)}
                                        className="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                                    >
                                        <FunnelIcon className="h-4 w-4 mr-2" />
                                        Filters
                                        <ChevronDownIcon className={`ml-2 h-4 w-4 transform transition-transform ${isFilterExpanded ? 'rotate-180' : ''}`} />
                                    </button>
                                </div>
                            </div>
                            
                            {isFilterExpanded && (
                                <div className="mt-4 pt-4 border-t border-gray-200">
                                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700 mb-1">Status</label>
                                            <select
                                                className="block w-full px-3 py-2 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 text-sm"
                                                value={filterStatus}
                                                onChange={(e) => setFilterStatus(e.target.value)}
                                            >
                                                <option value="all">All Notifications</option>
                                                <option value="read">Read</option>
                                                <option value="unread">Unread</option>
                                            </select>
                                        </div>
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700 mb-1">Date Range</label>
                                            <select
                                                className="block w-full px-3 py-2 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 text-sm"
                                            >
                                                <option value="all">All Time</option>
                                                <option value="today">Today</option>
                                                <option value="week">This Week</option>
                                                <option value="month">This Month</option>
                                                <option value="year">This Year</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            )}
                        </div>

                        {/* Notifications List with Enhanced Design - Responsive */}
                        <div className="bg-white shadow-xl rounded-xl overflow-hidden border border-gray-100">
                            {filteredNotifications.length > 0 ? (
                                <>
                                    {/* Desktop Table View */}
                                    <div className="hidden md:block overflow-x-auto">
                                        <table className="min-w-full divide-y divide-gray-200">
                                            <thead className="bg-gray-50">
                                                <tr>
                                                    <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                        Status
                                                    </th>
                                                    <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                        Message
                                                    </th>
                                                    <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                        Date
                                                    </th>
                                                    <th scope="col" className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                        Actions
                                                    </th>
                                                </tr>
                                            </thead>
                                            <tbody className="bg-white divide-y divide-gray-200">
                                                {filteredNotifications.map((notification) => (
                                                    <tr key={notification.id} className="hover:bg-gray-50 transition-colors">
                                                        <td className="px-6 py-4 whitespace-nowrap">
                                                            <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium border ${getStatusColor(notification.read_at)}`}>
                                                                {notification.read_at ? (
                                                                    <CheckSolidIcon className="h-3 w-3 mr-1" />
                                                                ) : (
                                                                    <EyeIcon className="h-3 w-3 mr-1" />
                                                                )}
                                                                {notification.read_at ? 'Read' : 'Unread'}
                                                            </span>
                                                        </td>
                                                        <td className="px-6 py-4">
                                                            <div className="text-sm text-gray-900 max-w-xs truncate">{notification.data.message}</div>
                                                        </td>
                                                        <td className="px-6 py-4 whitespace-nowrap">
                                                            <div className="text-sm text-gray-900">{formatDateTime(notification.created_at)}</div>
                                                        </td>
                                                        <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                                            <button 
                                                                onClick={() => viewDetails(notification)}
                                                                className="text-blue-600 hover:text-blue-900"
                                                            >
                                                                View Details
                                                            </button>
                                                        </td>
                                                    </tr>
                                                ))}
                                            </tbody>
                                        </table>
                                    </div>

                                    {/* Mobile Card View */}
                                    <div className="md:hidden">
                                        <ul className="divide-y divide-gray-200">
                                            {filteredNotifications.map((notification) => (
                                                <li key={notification.id} className="p-4 hover:bg-gray-50 transition-colors">
                                                    <div className="flex items-start justify-between">
                                                        <div className="flex items-center">
                                                            <div className="flex-shrink-0 h-10 w-10 bg-blue-100 rounded-full flex items-center justify-center">
                                                                {notification.read_at ? (
                                                                    <CheckSolidIcon className="h-6 w-6 text-blue-600" />
                                                                ) : (
                                                                    <EyeIcon className="h-6 w-6 text-blue-600" />
                                                                )}
                                                            </div>
                                                            <div className="ml-3">
                                                                <p className="text-sm font-medium text-gray-900">{notification.data.message}</p>
                                                                <p className="text-xs text-gray-500 mt-1">{formatDateTime(notification.created_at)}</p>
                                                            </div>
                                                        </div>
                                                        <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium border ${getStatusColor(notification.read_at)}`}>
                                                            {notification.read_at ? 'Read' : 'Unread'}
                                                        </span>
                                                    </div>
                                                    <div className="mt-3 flex justify-end">
                                                        <button 
                                                            onClick={() => viewDetails(notification)}
                                                            className="text-blue-600 hover:text-blue-900 text-sm font-medium"
                                                        >
                                                            View Details
                                                        </button>
                                                    </div>
                                                </li>
                                            ))}
                                        </ul>
                                    </div>
                                </>
                            ) : (
                                <div className="text-center py-12">
                                    <BellIcon className="mx-auto h-12 w-12 text-gray-400" />
                                    <h3 className="mt-2 text-sm font-medium text-gray-900">No notifications found</h3>
                                    <p className="mt-1 text-sm text-gray-500">
                                        Try adjusting your search term or filter selection.
                                    </p>
                                </div>
                            )}
                        </div>
                        
                        {/* Pagination */}
                        <div className="p-4 sm:p-6 border-t border-gray-100">
                            {notifications?.links && (
                                <div className="flex justify-center">
                                    {notifications.links.map((link, index) => (
                                        <Link
                                            key={index}
                                            href={link.url || '#'}
                                            className={`mx-1 px-3 py-1 text-sm rounded-md transition duration-150 ease-in-out ${
                                                link.active 
                                                    ? 'bg-blue-600 text-white font-semibold' 
                                                    : 'text-gray-600 hover:bg-gray-100'
                                            }`}
                                            dangerouslySetInnerHTML={{ __html: link.label }}
                                        />
                                    ))}
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            </div>

            {/* Enhanced Modal with Modern Design - Responsive */}
            <Modal show={showModal} onClose={closeModal} maxWidth="lg">
                <div className="bg-white rounded-xl shadow-2xl overflow-hidden max-h-[90vh] overflow-y-auto">
                    {/* Modal Header with Gradient Background */}
                    <div className="bg-gradient-to-r from-blue-600 to-indigo-700 px-4 sm:px-6 py-3 sm:py-4">
                        <div className="flex items-center justify-between">
                            <div className="flex items-center">
                                <div className="flex-shrink-0 bg-white/20 p-2 rounded-lg backdrop-blur-sm">
                                    <BellIcon className="h-5 w-5 sm:h-6 sm:w-6 text-white" />
                                </div>
                                <div className="ml-3 sm:ml-4">
                                    <h2 className="text-lg sm:text-xl font-bold text-white">Notification Details</h2>
                                    <p className="text-blue-100 text-xs sm:text-sm">ID: #{selectedNotification?.id}</p>
                                </div>
                            </div>
                            <button
                                type="button"
                                className="text-white/80 hover:text-white transition-colors p-1 rounded-md hover:bg-white/10"
                                onClick={closeModal}
                            >
                                <XMarkIcon className="h-5 w-5 sm:h-6 sm:w-6" />
                            </button>
                        </div>
                    </div>

                    {/* Modal Body */}
                    <div className="px-4 sm:px-6 py-4 sm:py-5">
                        {selectedNotification ? (
                            <div className="space-y-4 sm:space-y-6">
                                {/* Status Badge */}
                                <div className="bg-gray-50 rounded-lg p-3 sm:p-4">
                                    <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-3 sm:mb-4">
                                        <h3 className="text-base font-semibold text-gray-900 mb-2 sm:mb-0">Current Status</h3>
                                        <span className={`inline-flex items-center px-3 py-1 rounded-full text-sm font-medium border ${getStatusColor(selectedNotification.read_at)}`}>
                                            {selectedNotification.read_at ? (
                                                <CheckSolidIcon className="h-4 w-4 mr-2" />
                                            ) : (
                                                <EyeIcon className="h-4 w-4 mr-2" />
                                            )}
                                            {selectedNotification.read_at ? 'Read' : 'Unread'}
                                        </span>
                                    </div>
                                </div>

                                {/* Notification Information */}
                                <div className="bg-white border border-gray-200 rounded-lg p-3 sm:p-4">
                                    <h3 className="text-sm font-semibold text-gray-900 mb-2 sm:mb-3 flex items-center">
                                        <InformationCircleIcon className="h-4 w-4 sm:h-5 sm:w-5 mr-2 text-blue-600" />
                                        Message Details
                                    </h3>
                                    <div className="space-y-2 sm:space-y-3">
                                        <div className="flex justify-between">
                                            <dt className="text-xs sm:text-sm text-gray-500">Message:</dt>
                                            <dd className="text-xs sm:text-sm font-medium text-gray-900 max-w-xs truncate">{selectedNotification.data.message}</dd>
                                        </div>
                                        <div className="flex justify-between">
                                            <dt className="text-xs sm:text-sm text-gray-500">Created:</dt>
                                            <dd className="text-xs sm:text-sm font-medium text-gray-900">{formatDateTime(selectedNotification.created_at)}</dd>
                                        </div>
                                        {selectedNotification.read_at && (
                                            <div className="flex justify-between">
                                                <dt className="text-xs sm:text-sm text-gray-500">Read At:</dt>
                                                <dd className="text-xs sm:text-sm font-medium text-gray-900">{formatDateTime(selectedNotification.read_at)}</dd>
                                            </div>
                                        )}
                                    </div>
                                </div>

                                {/* Action Buttons */}
                                <div className="flex flex-col sm:flex-row sm:justify-between sm:items-center pt-3 sm:pt-4 border-t border-gray-200">
                                    <div className="flex flex-col sm:flex-row space-y-2 sm:space-y-0 sm:space-x-2 mb-3 sm:mb-0">
                                        {!selectedNotification.read_at && (
                                            <button 
                                                onClick={() => markAsRead(selectedNotification.id)}
                                                className="w-full sm:w-auto inline-flex justify-center items-center px-3 sm:px-4 py-2 border border-transparent rounded-md shadow-sm text-xs sm:text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors"
                                            >
                                                <CheckSolidIcon className="w-4 h-4 mr-2" />
                                                Mark as Read
                                            </button>
                                        )}
                                    </div>
                                    <button
                                        type="button"
                                        className="w-full sm:w-auto px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500 transition-colors text-sm font-medium"
                                        onClick={closeModal}
                                    >
                                        Close
                                    </button>
                                </div>
                            </div>
                        ) : (
                            <div className="text-center py-8">
                                <InformationCircleIcon className="mx-auto h-10 w-10 text-gray-400" />
                                <p className="mt-2 text-sm text-gray-500">Unable to load notification details</p>
                            </div>
                        )}
                    </div>
                </div>
            </Modal>
        </AdminLayout>
    );
}