import AdminLayout from '@/Layouts/AdminLayout';
import { Head, Link } from '@inertiajs/react';
import { useState, useEffect } from 'react';
import { format } from 'date-fns';
import Pagination from '@/Components/Pagination';

export default function Index({ auth, eventBookings }) {
    const [searchTerm, setSearchTerm] = useState('');
    const [filterStatus, setFilterStatus] = useState('all');
    // Initialize with data or an empty array if data might be null/undefined
    const [filteredEventBookings, setFilteredEventBookings] = useState(eventBookings.data || []); 
    // const [activeTab, setActiveTab] = useState('upcoming'); // Removed as it was unused

    useEffect(() => {
        // Ensure eventBookings.data is treated as an array before filtering
        let filtered = Array.isArray(eventBookings.data) ? eventBookings.data : [];

        // Filter by search term
        if (searchTerm) {
            filtered = filtered.filter(booking =>
                booking.event_name.toLowerCase().includes(searchTerm.toLowerCase())
            );
        }

        // Filter by status
        if (filterStatus !== 'all') {
            filtered = filtered.filter(booking => booking.status === filterStatus);
        }

        setFilteredEventBookings(filtered);
    }, [searchTerm, filterStatus, eventBookings.data]);

    // Added to handle filtering logic when eventBookings data changes, which is common with Inertia.js updates
    // const rawBookings = eventBookings.data || [];
    // const totalConfirmed = rawBookings.filter(b => b.status === 'confirmed').length;
    // const totalPending = rawBookings.filter(b => b.status === 'pending').length;
    // const totalSpent = rawBookings.reduce((sum, booking) => sum + (booking.total_price || 0), 0).toFixed(2);


    const getStatusColor = (status) => {
        switch (status) {
            case 'confirmed':
                return 'bg-green-100 text-green-800';
            case 'pending':
            case 'upcoming': 
                return 'bg-yellow-100 text-yellow-800';
            case 'completed':
                return 'bg-blue-100 text-blue-800';
            case 'cancelled':
                return 'bg-red-100 text-red-800';
            default:
                return 'bg-gray-100 text-gray-800';
        }
    };

    const getStatusIcon = (status) => {
        switch (status) {
            case 'confirmed':
                return (
                    <svg className="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                    </svg>
                );
            case 'pending':
            case 'upcoming':
                return (
                    <svg className="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 00.293.707l2.828 2.829a1 1 0 101.415-1.415L11 9.586V6z" clipRule="evenodd" />
                    </svg>
                );
            case 'completed':
                return (
                    <svg className="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M6.267 3.455a3.066 3.066 0 001.745-.723 3.066 3.066 0 013.976 0 3.066 3.066 0 001.745.723 3.066 3.066 0 012.812 2.812c.051.643.304 1.254.723 1.745a3.066 3.066 0 010 3.976 3.066 3.066 0 00-.723 1.745 3.066 3.066 0 01-2.812 2.812 3.066 3.066 0 00-1.745.723 3.066 3.066 0 01-3.976 0 3.066 3.066 0 00-1.745-.723 3.066 3.066 0 01-2.812-2.812 3.066 3.066 0 00-.723-1.745 3.066 3.066 0 010-3.976 3.066 3.066 0 00.723-1.745 3.066 3.066 0 012.812-2.812zm7.44 5.252a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                    </svg>
                );
            case 'cancelled':
                return (
                    <svg className="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                    </svg>
                );
            default:
                return null;
        }
    };

    // Calculate totals directly inside the component for stats cards
    const rawBookings = eventBookings.data || [];
    const totalConfirmed = rawBookings.filter(b => b.status === 'confirmed').length;
    const totalPending = rawBookings.filter(b => b.status === 'pending').length;
    // Safely calculate total spent, defaulting to 0 if total_price is missing
    const totalSpent = rawBookings.reduce((sum, booking) => sum + (booking.total_price || 0), 0).toFixed(2);
    
    // Add logic for a dynamic Upcoming count for the card
    const now = new Date();
    const totalUpcoming = rawBookings.filter(b => b.status === 'confirmed' && new Date(b.booking_date) >= now).length;


    return (
        <AdminLayout>
            <Head title="My Event Bookings" />

            <div className="py-6">
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                    
                    {/* Header Section */}
                    <div className="mb-6">
                        <h1 className="text-2xl sm:text-3xl font-bold text-gray-900">My Event Bookings 🎫</h1>
                        <p className="mt-1 text-sm text-gray-600">Welcome back, **{auth.user.name}**. Here you can manage all your event bookings.</p>
                    </div>

                    {/* Stats Cards - REVISED: Added Upcoming count */}
                    <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
                        {/* Total Card */}
                        <div className="bg-white overflow-hidden shadow rounded-lg">
                            <div className="p-4 sm:p-5">
                                <div className="flex items-center">
                                    <div className="flex-shrink-0 bg-blue-500 rounded-md p-2">
                                        <svg className="h-5 w-5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" /></svg>
                                    </div>
                                    <div className="ml-3 w-0 flex-1">
                                        <dl>
                                            <dt className="text-sm font-medium text-gray-500 truncate">Total</dt>
                                            <dd className="text-lg font-bold text-gray-900">{eventBookings.total}</dd>
                                        </dl>
                                    </div>
                                </div>
                            </div>
                        </div>

                        {/* Confirmed Card */}
                        <div className="bg-white overflow-hidden shadow rounded-lg">
                            <div className="p-4 sm:p-5">
                                <div className="flex items-center">
                                    <div className="flex-shrink-0 bg-green-500 rounded-md p-2">
                                        <svg className="h-5 w-5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
                                    </div>
                                    <div className="ml-3 w-0 flex-1">
                                        <dl>
                                            <dt className="text-sm font-medium text-gray-500 truncate">Confirmed</dt>
                                            <dd className="text-lg font-bold text-gray-900">{totalConfirmed}</dd>
                                        </dl>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        {/* Upcoming Card (New/Replaced Pending) */}
                        <div className="bg-white overflow-hidden shadow rounded-lg">
                            <div className="p-4 sm:p-5">
                                <div className="flex items-center">
                                    <div className="flex-shrink-0 bg-yellow-500 rounded-md p-2">
                                        <svg className="h-5 w-5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
                                    </div>
                                    <div className="ml-3 w-0 flex-1">
                                        <dl>
                                            <dt className="text-sm font-medium text-gray-500 truncate">Upcoming</dt>
                                            <dd className="text-lg font-bold text-gray-900">{totalUpcoming}</dd>
                                        </dl>
                                    </div>
                                </div>
                            </div>
                        </div>

                        {/* Total Spent Card */}
                        <div className="bg-white overflow-hidden shadow rounded-lg">
                            <div className="p-4 sm:p-5">
                                <div className="flex items-center">
                                    <div className="flex-shrink-0 bg-purple-500 rounded-md p-2">
                                        <svg className="h-5 w-5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m0 0l.953.57a3 3 0 002.954 0L12 15h3m-6 3a3 3 0 11-6 0 3 3 0 016 0z" /></svg>
                                    </div>
                                    <div className="ml-3 w-0 flex-1">
                                        <dl>
                                            <dt className="text-sm font-medium text-gray-500 truncate">Total Spent</dt>
                                            <dd className="text-lg font-bold text-gray-900">GH₵{totalSpent}</dd>
                                        </dl>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <hr className="my-4 border-gray-200" />

                    {/* Search and Filter Section - Simplified Layout */}
                    <div className="bg-white shadow rounded-lg mb-6 p-4">
                        <div className="flex flex-col sm:flex-row gap-4">
                            
                            <div className="relative w-full sm:w-2/3"> {/* Give search a bit more room on sm+ */}
                                <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 border border-gray-300 rounded-md leading-5 bg-white placeholder-gray-500 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 text-sm"
                                    placeholder="Search by event name..."
                                    value={searchTerm}
                                    onChange={(e) => setSearchTerm(e.target.value)}
                                />
                            </div>
                            
                            <div className="w-full sm:w-1/3">
                                <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 Statuses ({eventBookings.total})</option>
                                    <option value="confirmed">Confirmed ({totalConfirmed})</option>
                                    <option value="pending">Pending ({totalPending})</option>
                                    <option value="completed">Completed</option>
                                    <option value="cancelled">Cancelled</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    {/* Event Bookings List */}
                    <div className="bg-white shadow overflow-hidden sm:rounded-lg">
                        {filteredEventBookings.length > 0 ? (
                            <ul className="divide-y divide-gray-200">
                                {filteredEventBookings.map((booking) => (
                                    <li key={booking.id}>
                                        <div className="px-4 py-4 sm:px-6 hover:bg-gray-50 transition-colors">
                                            <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between">
                                                
                                                {/* Event Info (Left/Top) */}
                                                <div className="flex items-start min-w-0 flex-1">
                                                    <div className="flex-shrink-0 h-10 w-10 sm:h-12 sm:w-12 rounded-full bg-blue-100 flex items-center justify-center">
                                                        <svg className="h-5 w-5 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" /></svg>
                                                    </div>
                                                    <div className="ml-3 sm:ml-4 flex-1">
                                                        {/* Event Name & Status Badge */}
                                                        <div className="flex flex-col sm:flex-row sm:items-center">
                                                            <p className="text-base font-semibold text-gray-900 truncate mr-2">{booking.event_name}</p>
                                                            <span className={`mt-1 sm:mt-0 inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${getStatusColor(booking.status)}`}>
                                                                {getStatusIcon(booking.status)}
                                                                {booking.status.charAt(0).toUpperCase() + booking.status.slice(1)}
                                                            </span>
                                                        </div>
                                                        
                                                        {/* Details Grid - Responsive stacking on mobile, side-by-side on sm+ */}
                                                        <div className="mt-2 grid grid-cols-2 sm:grid-cols-3 gap-y-1 gap-x-4 text-xs sm:text-sm">
                                                            <p className="text-gray-500 col-span-2 sm:col-span-1">
                                                                <span className="font-medium text-gray-700">Date:</span> {format(new Date(booking.booking_date), 'MMM dd, yyyy')}
                                                            </p>
                                                            <p className="text-gray-500">
                                                                <span className="font-medium text-gray-700">Qty:</span> {booking.quantity}
                                                            </p>
                                                            <p className="text-gray-500">
                                                                <span className="font-medium text-gray-700">Total:</span> GH₵{booking.total_price.toFixed(2)}
                                                            </p>
                                                        </div>
                                                    </div>
                                                </div>
                                                
                                                {/* Action Buttons (Right/Bottom) */}
                                                <div className="flex flex-row space-x-2 mt-4 sm:mt-0 sm:space-x-0 sm:space-y-2 sm:flex-col sm:ml-4 justify-end">
                                                    <Link 
                                                        href={route('event.booking.details', booking.id)} // Assuming an Inertia route for details
                                                        className="inline-flex items-center justify-center px-3 py-1.5 border border-gray-300 shadow-sm text-xs 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"
                                                    >
                                                        View Details
                                                    </Link>
                                                    {booking.status === 'pending' && (
                                                        <button 
                                                            className="inline-flex items-center justify-center px-3 py-1.5 border border-red-300 shadow-sm text-xs sm:text-sm leading-4 font-medium rounded-md text-red-700 bg-white hover:bg-red-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500"
                                                            // onClick={() => handleCancel(booking.id)} // Placeholder for cancellation logic
                                                        >
                                                            Cancel
                                                        </button>
                                                    )}
                                                </div>
                                            </div>
                                        </div>
                                    </li>
                                ))}
                            </ul>
                        ) : (
                            <div className="text-center py-8 sm:py-12">
                                <svg className="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                                </svg>
                                <h3 className="mt-2 text-base font-medium text-gray-900">No event bookings found</h3>
                                <p className="mt-1 text-sm text-gray-500">Get started by booking an event.</p>
                                <div className="mt-6">
                                    <Link
                                        href={route('events.index')}
                                        className="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                                    >
                                        Browse Events
                                    </Link>
                                </div>
                            </div>
                        )}
                    </div>

                    {/* Pagination */}
                    <div className="mt-6">
                        {/* Assuming Pagination component handles null/empty links prop */}
                        <Pagination links={eventBookings.links} from={eventBookings.from} to={eventBookings.to} total={eventBookings.total} />
                    </div>
                </div>
            </div>
        </AdminLayout>
    );
}