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';
import Modal from '@/Components/Modal';
import axios from 'axios';
import { 
    CalendarIcon, 
    TicketIcon, 
    CurrencyDollarIcon,
    MagnifyingGlassIcon,
    XMarkIcon,
    CheckCircleIcon,
    ClockIcon,
    ExclamationTriangleIcon,
    UserIcon,
    CreditCardIcon,
    InformationCircleIcon
} from '@heroicons/react/24/outline';
import { CheckIcon, XCircleIcon } from '@heroicons/react/24/solid';

// Helper function for currency formatting
const formatCurrency = (price) => {
    if (price === undefined || price === null) return 'N/A';
    return new Intl.NumberFormat('en-GH', {
        style: 'currency',
        currency: 'GHS',
        minimumFractionDigits: 2,
    }).format(price);
};

export default function Index({ auth, eventBookings }) {
    const [searchTerm, setSearchTerm] = useState('');
    const [filterStatus, setFilterStatus] = useState('all');
    const [filteredEventBookings, setFilteredEventBookings] = useState(eventBookings.data || []);
    const [activeTab, setActiveTab] = useState('upcoming');
    const [showModal, setShowModal] = useState(false);
    const [selectedBooking, setSelectedBooking] = useState(null);

    useEffect(() => {
        let filtered = 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, activeTab, eventBookings.data]);

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

    const getStatusIcon = (status) => {
        switch (status) {
            case 'confirmed':
                return <CheckCircleIcon className="h-5 w-5" />;
            case 'pending':
                return <ClockIcon className="h-5 w-5" />;
            case 'completed':
                return <CheckIcon className="h-5 w-5" />;
            case 'cancelled':
                return <XCircleIcon className="h-5 w-5" />;
            default:
                return <ExclamationTriangleIcon className="h-5 w-5" />;
        }
    };

    const viewDetails = (booking) => {
        axios.get(route('user.tickets.show', booking.id)).then((response) => {
            setSelectedBooking(response.data.booking);
            setShowModal(true);
        });
    };

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

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

            <div className="py-6">
                <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-6 mb-8 text-white">
                        <h1 className="text-3xl font-bold mb-2">My Event Tickets</h1>
                        <p className="text-blue-100">Welcome back, {auth.user.name}. Here you can manage all your event tickets.</p>
                    </div>

                    {/* Stats Cards with improved design */}
                    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
                        <div className="bg-white overflow-hidden shadow-lg rounded-xl border border-gray-100 hover:shadow-xl transition-shadow duration-300">
                            <div className="p-5">
                                <div className="flex items-center">
                                    <div className="flex-shrink-0 bg-blue-500 rounded-lg p-3">
                                        <TicketIcon className="h-6 w-6 text-white" />
                                    </div>
                                    <div className="ml-5 w-0 flex-1">
                                        <dl>
                                            <dt className="text-sm font-medium text-gray-500 truncate">Total Tickets</dt>
                                            <dd className="text-lg font-semibold text-gray-900">{eventBookings.total}</dd>
                                        </dl>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div className="bg-white overflow-hidden shadow-lg rounded-xl border border-gray-100 hover:shadow-xl transition-shadow duration-300">
                            <div className="p-5">
                                <div className="flex items-center">
                                    <div className="flex-shrink-0 bg-green-500 rounded-lg p-3">
                                        <CheckCircleIcon className="h-6 w-6 text-white" />
                                    </div>
                                    <div className="ml-5 w-0 flex-1">
                                        <dl>
                                            <dt className="text-sm font-medium text-gray-500 truncate">Confirmed</dt>
                                            <dd className="text-lg font-semibold text-gray-900">{eventBookings.data.filter(b => b.status === 'confirmed').length}</dd>
                                        </dl>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div className="bg-white overflow-hidden shadow-lg rounded-xl border border-gray-100 hover:shadow-xl transition-shadow duration-300">
                            <div className="p-5">
                                <div className="flex items-center">
                                    <div className="flex-shrink-0 bg-yellow-500 rounded-lg p-3">
                                        <ClockIcon className="h-6 w-6 text-white" />
                                    </div>
                                    <div className="ml-5 w-0 flex-1">
                                        <dl>
                                            <dt className="text-sm font-medium text-gray-500 truncate">Pending</dt>
                                            <dd className="text-lg font-semibold text-gray-900">{eventBookings.data.filter(b => b.status === 'pending').length}</dd>
                                        </dl>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div className="bg-white overflow-hidden shadow-lg rounded-xl border border-gray-100 hover:shadow-xl transition-shadow duration-300">
                            <div className="p-5">
                                <div className="flex items-center">
                                    <div className="flex-shrink-0 bg-purple-500 rounded-lg p-3">
                                        <CurrencyDollarIcon className="h-6 w-6 text-white" />
                                    </div>
                                    <div className="ml-5 w-0 flex-1">
                                        <dl>
                                            <dt className="text-sm font-medium text-gray-500 truncate">Total Spent</dt>
                                            <dd className="text-lg font-semibold text-gray-900">{formatCurrency(eventBookings.data.reduce((sum, booking) => sum + booking.total_price, 0))}</dd>
                                        </dl>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Search and Filter Section with improved design */}
                    <div className="bg-white shadow-lg rounded-xl mb-8 p-6 border border-gray-100">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div className="relative">
                                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                    <MagnifyingGlassIcon className="h-5 w-5 text-gray-400" />
                                </div>
                                <input
                                    type="text"
                                    className="block w-full pl-10 pr-3 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"
                                    placeholder="Search event tickets..."
                                    value={searchTerm}
                                    onChange={(e) => setSearchTerm(e.target.value)}
                                />
                            </div>
                            <div>
                                <select
                                    className="block w-full px-3 py-3 border border-gray-300 bg-white rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm"
                                    value={filterStatus}
                                    onChange={(e) => setFilterStatus(e.target.value)}
                                >
                                    <option value="all">All Status</option>
                                    <option value="confirmed">Confirmed</option>
                                    <option value="pending">Pending</option>
                                    <option value="completed">Completed</option>
                                    <option value="cancelled">Cancelled</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    {/* Event Bookings List with improved design */}
                    <div className="bg-white shadow-xl rounded-xl overflow-hidden border border-gray-100">
                        {filteredEventBookings.length > 0 ? (
                            <div className="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">
                                                Event Details
                                            </th>
                                            <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                Date & Time
                                            </th>
                                            <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                Quantity
                                            </th>
                                            <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                Total Price
                                            </th>
                                            <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-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                Actions
                                            </th>
                                        </tr>
                                    </thead>
                                    <tbody className="bg-white divide-y divide-gray-200">
                                        {filteredEventBookings.map((booking) => (
                                            <tr key={booking.id} className="hover:bg-gray-50 transition-colors">
                                                <td className="px-6 py-4 whitespace-nowrap">
                                                    <div className="flex items-center">
                                                        <div className="flex-shrink-0 h-10 w-10 bg-blue-100 rounded-full flex items-center justify-center">
                                                            <TicketIcon className="h-6 w-6 text-blue-600" />
                                                        </div>
                                                        <div className="ml-4">
                                                            <div className="text-sm font-medium text-gray-900">{booking.event_name}</div>
                                                        </div>
                                                    </div>
                                                </td>
                                                <td className="px-6 py-4 whitespace-nowrap">
                                                    <div className="text-sm text-gray-900">{format(new Date(booking.booking_date), 'MMM dd, yyyy')}</div>
                                                </td>
                                                <td className="px-6 py-4 whitespace-nowrap">
                                                    <div className="text-sm text-gray-900">{booking.quantity}</div>
                                                </td>
                                                <td className="px-6 py-4 whitespace-nowrap">
                                                    <div className="text-sm font-medium text-gray-900">{formatCurrency(booking.total_price)}</div>
                                                </td>
                                                <td className="px-6 py-4 whitespace-nowrap">
                                                    <span className={`inline-flex items-center px-3 py-1 rounded-full text-xs font-medium border ${getStatusColor(booking.status || 'default')}`}>
                                                        {getStatusIcon(booking.status || 'default')}
                                                        <span className="ml-1">{booking.status ? booking.status.charAt(0).toUpperCase() + booking.status.slice(1) : 'N/A'}</span>
                                                    </span>
                                                </td>
                                                <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                                    <button 
                                                        onClick={() => viewDetails(booking)}
                                                        className="text-blue-600 hover:text-blue-900 mr-3"
                                                    >
                                                        View Details
                                                    </button>
                                                    {booking.status === 'pending' && (
                                                        <button className="text-red-600 hover:text-red-900">
                                                            Cancel
                                                        </button>
                                                    )}
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        ) : (
                            <div className="text-center py-12">
                                <TicketIcon className="mx-auto h-12 w-12 text-gray-400" />
                                <h3 className="mt-2 text-sm font-medium text-gray-900">No event tickets found</h3>
                                <p className="mt-1 text-sm text-gray-500">Get started by booking an event.</p>
                            </div>
                        )}
                    </div>

                    <div className="mt-6">
                        <Pagination links={eventBookings.links} from={eventBookings.from} to={eventBookings.to} total={eventBookings.total} />
                    </div>
                </div>
            </div>

            {/* Redesigned Modal */}
            <Modal show={showModal} onClose={closeModal} maxWidth="lg">
                {selectedBooking && (
                    <div className="bg-white rounded-xl shadow-2xl overflow-hidden">
                        {/* Modal Header */}
                        <div className="bg-gradient-to-r from-blue-600 to-indigo-700 px-6 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">
                                        <TicketIcon className="h-6 w-6 text-white" />
                                    </div>
                                    <div className="ml-4">
                                        <h2 className="text-xl font-bold text-white">Event Booking Details</h2>
                                        <p className="text-blue-100 text-sm">Booking ID: #{selectedBooking.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-6 w-6" />
                                </button>
                            </div>
                        </div>

                        {/* Modal Body */}
                        <div className="px-6 py-5">
                            {/* Status Badge */}
                            <div className="mb-6">
                                <span className={`inline-flex items-center px-4 py-2 rounded-full text-sm font-medium border ${getStatusColor(selectedBooking.status || 'default')}`}>
                                    {getStatusIcon(selectedBooking.status || 'default')}
                                    <span className="ml-2">{selectedBooking.status ? selectedBooking.status.charAt(0).toUpperCase() + selectedBooking.status.slice(1) : 'N/A'}</span>
                                </span>
                            </div>

                            {/* Event Information */}
                            <div className="bg-gray-50 rounded-lg p-4 mb-6">
                                <h3 className="text-sm font-semibold text-gray-700 mb-3 flex items-center">
                                    <TicketIcon className="h-5 w-5 mr-2 text-blue-600" />
                                    Event Information
                                </h3>
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div>
                                        <p className="text-sm text-gray-500">Event Name</p>
                                        <p className="text-sm font-medium text-gray-900">{selectedBooking.event_name}</p>
                                    </div>
                                    <div>
                                        <p className="text-sm text-gray-500">Booking Date</p>
                                        <p className="text-sm font-medium text-gray-900">{format(new Date(selectedBooking.booking_date), 'MMM dd, yyyy')}</p>
                                    </div>
                                    <div>
                                        <p className="text-sm text-gray-500">Quantity</p>
                                        <p className="text-sm font-medium text-gray-900">{selectedBooking.quantity}</p>
                                    </div>
                                    <div>
                                        <p className="text-sm text-gray-500">Total Price</p>
                                        <p className="text-sm font-medium text-gray-900">{formatCurrency(selectedBooking.total_price)}</p>
                                    </div>
                                </div>
                            </div>

                            {/* Customer Information */}
                            <div className="bg-gray-50 rounded-lg p-4 mb-6">
                                <h3 className="text-sm font-semibold text-gray-700 mb-3 flex items-center">
                                    <UserIcon className="h-5 w-5 mr-2 text-blue-600" />
                                    Customer Information
                                </h3>
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div>
                                        <p className="text-sm text-gray-500">Name</p>
                                        <p className="text-sm font-medium text-gray-900">{auth.user.name}</p>
                                    </div>
                                    <div>
                                        <p className="text-sm text-gray-500">Email</p>
                                        <p className="text-sm font-medium text-gray-900">{auth.user.email}</p>
                                    </div>
                                </div>
                            </div>

                            {/* Notes Section */}
                            {selectedBooking.notes && (
                                <div className="bg-blue-50 rounded-lg p-4 mb-6">
                                    <h3 className="text-sm font-semibold text-gray-700 mb-2 flex items-center">
                                        <InformationCircleIcon className="h-5 w-5 mr-2 text-blue-600" />
                                        Additional Notes
                                    </h3>
                                    <p className="text-sm text-gray-700">{selectedBooking.notes}</p>
                                </div>
                            )}
                        </div>

                        {/* Modal Footer */}
                        <div className="bg-gray-50 px-6 py-4 flex flex-col sm:flex-row-reverse gap-3">
                            {selectedBooking.status === 'pending' && (
                                <button className="w-full sm:w-auto inline-flex justify-center items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 transition-colors">
                                    <XCircleIcon className="h-4 w-4 mr-2" />
                                    Cancel Booking
                                </button>
                            )}
                            <button
                                type="button"
                                className="w-full sm:w-auto inline-flex justify-center items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors"
                                onClick={closeModal}
                            >
                                Close
                            </button>
                        </div>
                    </div>
                )}
            </Modal>
        </AdminLayout>
    );
}