import { useState, useMemo } from "react";
import Col from "@admin/ui/Col";
import Row from "@admin/ui/Row";
import Card from "@admin/ui/Card";
import { format, startOfMonth, endOfMonth, eachDayOfInterval, isSameMonth, isSameDay, addMonths, subMonths, startOfWeek, endOfWeek, isBefore, startOfDay } from "date-fns";
import { formatDate, formatDateShort } from "@/utils/dateFormatter";

export default function Calendar({ bookings = [], rooms = [] }) {
    const [currentDate, setCurrentDate] = useState(new Date());
    const [selectedRoomFilter, setSelectedRoomFilter] = useState('all');
    const [selectedBookings, setSelectedBookings] = useState([]);
    const [showBookingModal, setShowBookingModal] = useState(false);
    const today = startOfDay(new Date());

    // Get unique room categories for filter
    const roomCategories = useMemo(() => {
        const categories = [...new Set(rooms.map(room => room.category))];
        return categories.sort();
    }, [rooms]);

    // Filter rooms by selected category
    const filteredRooms = useMemo(() => {
        if (selectedRoomFilter === 'all') {
            return rooms;
        }
        return rooms.filter(room => room.category === selectedRoomFilter);
    }, [rooms, selectedRoomFilter]);

    // Get month start and end
    const monthStart = startOfMonth(currentDate);
    const monthEnd = endOfMonth(currentDate);
    const calendarStart = startOfWeek(monthStart);
    const calendarEnd = endOfWeek(monthEnd);

    // Get all days in calendar view, but filter out past dates when viewing current month
    const calendarDays = useMemo(() => {
        const allCalendarDays = eachDayOfInterval({ start: calendarStart, end: calendarEnd });
        // If viewing the current month, filter out past dates
        if (isSameMonth(currentDate, today)) {
            return allCalendarDays.filter(day => !isBefore(startOfDay(day), today));
        }
        return allCalendarDays;
    }, [calendarStart, calendarEnd, currentDate, today]);

    // Group bookings by room and date
    const bookingsByRoomAndDate = useMemo(() => {
        const grouped = {};
        
        bookings.forEach(booking => {
            if (!booking.room_id || !booking.check_in || !booking.check_out) return;
            
            const roomId = booking.room_id;
            const checkIn = new Date(booking.check_in);
            const checkOut = new Date(booking.check_out);
            
            // Create date range for this booking (exclude check-out day as room is available then)
            // We subtract 1 day from check-out to exclude it from the range
            const checkOutExclusive = new Date(checkOut);
            checkOutExclusive.setDate(checkOutExclusive.getDate() - 1);
            
            const bookingDays = eachDayOfInterval({ start: checkIn, end: checkOutExclusive });
            
            bookingDays.forEach(day => {
                const dateKey = format(day, 'yyyy-MM-dd');
                if (!grouped[roomId]) {
                    grouped[roomId] = {};
                }
                if (!grouped[roomId][dateKey]) {
                    grouped[roomId][dateKey] = [];
                }
                grouped[roomId][dateKey].push(booking);
            });
        });
        
        return grouped;
    }, [bookings]);

    // Check if a room is booked on a specific date
    const isRoomBookedOnDate = (roomId, date) => {
        const dateKey = format(date, 'yyyy-MM-dd');
        return bookingsByRoomAndDate[roomId]?.[dateKey]?.length > 0;
    };

    // Get bookings for a room on a specific date
    const getBookingsForRoomOnDate = (roomId, date) => {
        const dateKey = format(date, 'yyyy-MM-dd');
        return bookingsByRoomAndDate[roomId]?.[dateKey] || [];
    };

    // Navigate months
    const previousMonth = () => {
        const prevDate = subMonths(currentDate, 1);
        // Don't allow navigating to past months
        if (!isBefore(prevDate, startOfMonth(today))) {
            setCurrentDate(prevDate);
        }
    };
    const nextMonth = () => setCurrentDate(addMonths(currentDate, 1));
    const goToToday = () => setCurrentDate(new Date());
    
    // Check if previous month button should be disabled
    const canGoPrevious = !isBefore(subMonths(currentDate, 1), startOfMonth(today));

    // Get day class for styling
    const getDayClass = (day, isCurrentMonth) => {
        const baseClass = 'calendar-day';
        const classes = [baseClass];
        
        if (!isCurrentMonth) {
            classes.push('text-muted');
        }
        
        if (isSameDay(day, new Date())) {
            classes.push('today');
        }
        
        return classes.join(' ');
    };

    // Get cell class for room availability
    const getCellClass = (roomId, day, isCurrentMonth) => {
        const classes = ['calendar-cell'];
        
        if (!isCurrentMonth) {
            classes.push('other-month');
        }
        
        // Check if date is in the past (for current month)
        const isPastDate = isBefore(startOfDay(day), today);
        if (isPastDate && isSameMonth(day, today)) {
            classes.push('past-date');
        }
        
        const roomBookings = getBookingsForRoomOnDate(roomId, day);
        if (roomBookings.length > 0) {
            classes.push('booked');
        } else if (isCurrentMonth && !isPastDate) {
            classes.push('available');
        }
        
        return classes.join(' ');
    };
    
    // Check if a day should be displayed (not in past when viewing current month)
    const shouldDisplayDay = (day) => {
        if (isSameMonth(currentDate, today)) {
            return !isBefore(startOfDay(day), today);
        }
        return true;
    };

    return (
        <>
            <Row md="12">
                <Col lg="12">
                    <div className="d-flex flex-column flex-md-row justify-content-between align-items-start align-items-md-center mb-4">
                        <div className="mb-3 mb-md-0">
                            <h2 className="page-title mb-1">Booking Calendar</h2>
                            <p className="text-muted mb-0">View room availability and bookings by date</p>
                        </div>
                    </div>

                    {/* Calendar Controls */}
                    <Card md="12" title="Calendar Controls">
                        <Row className="mb-3 align-items-center">
                            <Col xs="12" md="4">
                                <div className="d-flex align-items-center gap-2 flex-wrap">
                                    <button 
                                        className="btn btn-outline-primary btn-sm"
                                        onClick={previousMonth}
                                        disabled={!canGoPrevious}
                                        title={!canGoPrevious ? "Cannot navigate to past months" : "Previous month"}
                                    >
                                        <i className="fe fe-chevron-left fe-16"></i>
                                    </button>
                                    <button 
                                        className="btn btn-primary btn-sm"
                                        onClick={goToToday}
                                        title="Go to today"
                                    >
                                        <i className="fe fe-calendar fe-12 mr-1"></i>
                                        Today
                                    </button>
                                    <button 
                                        className="btn btn-outline-primary btn-sm"
                                        onClick={nextMonth}
                                        title="Next month"
                                    >
                                        <i className="fe fe-chevron-right fe-16"></i>
                                    </button>
                                    <h4 className="mb-0 ml-2" style={{ minWidth: '140px' }}>
                                        {format(currentDate, 'MMMM yyyy')}
                                    </h4>
                                </div>
                            </Col>
                            <Col xs="12" md="4">
                                <select
                                    className="form-control"
                                    value={selectedRoomFilter}
                                    onChange={(e) => setSelectedRoomFilter(e.target.value)}
                                >
                                    <option value="all">All Categories</option>
                                    {roomCategories.map((category) => (
                                        <option key={category} value={category}>
                                            {category}
                                        </option>
                                    ))}
                                </select>
                            </Col>
                            <Col xs="12" md="4">
                                <div className="d-flex align-items-center gap-3">
                                    <div className="d-flex align-items-center">
                                        <div 
                                            className="legend-box available"
                                            style={{
                                                width: '20px',
                                                height: '20px',
                                                backgroundColor: '#d4edda',
                                                border: '1px solid #c3e6cb',
                                                marginRight: '8px'
                                            }}
                                        ></div>
                                        <span className="small">Available</span>
                                    </div>
                                    <div className="d-flex align-items-center">
                                        <div 
                                            className="legend-box booked"
                                            style={{
                                                width: '20px',
                                                height: '20px',
                                                backgroundColor: '#f8d7da',
                                                border: '1px solid #f5c6cb',
                                                marginRight: '8px'
                                            }}
                                        ></div>
                                        <span className="small">Booked</span>
                                    </div>
                                </div>
                            </Col>
                        </Row>
                    </Card>

                    {/* Calendar Grid */}
                    <Card md="12" title={`Calendar - ${format(currentDate, 'MMMM yyyy')}`}>
                        <div className="table-responsive" style={{ overflowX: 'auto' }}>
                            <table className="table table-bordered calendar-table" style={{ minWidth: '100%', fontSize: '0.85rem' }}>
                                <thead>
                                    <tr>
                                        <th className="calendar-room-header" style={{ minWidth: '150px', position: 'sticky', left: 0, backgroundColor: '#fff', zIndex: 10 }}>
                                            Room / Date
                                        </th>
                                        {calendarDays.map((day, index) => {
                                            const isCurrentMonthDay = isSameMonth(day, currentDate);
                                            const isToday = isSameDay(day, today);
                                            return (
                                                <th 
                                                    key={`header-${index}-${format(day, 'yyyy-MM-dd')}`}
                                                    className={getDayClass(day, isCurrentMonthDay)}
                                                    style={{ 
                                                        minWidth: '50px',
                                                        textAlign: 'center',
                                                        padding: '8px 4px',
                                                        backgroundColor: isToday ? '#e3f2fd' : '#fff',
                                                        borderLeft: index === 0 ? '2px solid #dee2e6' : 'none'
                                                    }}
                                                >
                                                    <div className="font-weight-bold" style={{ fontSize: '0.75rem' }}>{format(day, 'EEE')}</div>
                                                    <div className="small" style={{ fontSize: '0.875rem', fontWeight: isToday ? 'bold' : 'normal' }}>{format(day, 'd')}</div>
                                                </th>
                                            );
                                        })}
                                    </tr>
                                </thead>
                                <tbody>
                                    {filteredRooms.map((room) => (
                                        <tr key={room.id}>
                                            <td 
                                                className="calendar-room-cell"
                                                style={{ 
                                                    position: 'sticky', 
                                                    left: 0, 
                                                    backgroundColor: '#fff', 
                                                    zIndex: 9,
                                                    fontWeight: 'bold',
                                                    padding: '8px',
                                                    borderRight: '2px solid #dee2e6'
                                                }}
                                            >
                                                {room.display_name}
                                            </td>
                                            {calendarDays.map((day, index) => {
                                                const isCurrentMonthDay = isSameMonth(day, currentDate);
                                                const roomBookings = getBookingsForRoomOnDate(room.id, day);
                                                const cellClass = getCellClass(room.id, day, isCurrentMonthDay);
                                                const isToday = isSameDay(day, today);
                                                const isPastDate = isBefore(startOfDay(day), today);
                                                
                                                return (
                                                    <td
                                                        key={`cell-${room.id}-${index}-${format(day, 'yyyy-MM-dd')}`}
                                                        className={cellClass}
                                                        style={{
                                                            padding: '4px',
                                                            textAlign: 'center',
                                                            cursor: roomBookings.length > 0 ? 'pointer' : 'default',
                                                            position: 'relative',
                                                            borderLeft: index === 0 ? '2px solid #dee2e6' : 'none',
                                                            borderRight: isToday ? '2px solid #2196F3' : 'none'
                                                        }}
                                                        title={roomBookings.length > 0 ? 
                                                            roomBookings.map(b => `${b.full_name} (${formatDateShort(b.check_in)} - ${formatDateShort(b.check_out)})`).join(', ')
                                                            : isPastDate ? 'Past date' : 'Available'
                                                        }
                                                        onClick={() => {
                                                            if (roomBookings.length > 0) {
                                                                setSelectedBookings(roomBookings);
                                                                setShowBookingModal(true);
                                                            }
                                                        }}
                                                    >
                                                        {isToday && (
                                                            <div 
                                                                style={{
                                                                    position: 'absolute',
                                                                    top: '2px',
                                                                    right: '2px',
                                                                    width: '6px',
                                                                    height: '6px',
                                                                    backgroundColor: '#2196F3',
                                                                    borderRadius: '50%'
                                                                }}
                                                                title="Today"
                                                            />
                                                        )}
                                                        {roomBookings.length > 0 && (
                                                            <div 
                                                                className="booking-indicator"
                                                                style={{
                                                                    backgroundColor: '#dc3545',
                                                                    color: '#fff',
                                                                    borderRadius: '4px',
                                                                    padding: '3px 6px',
                                                                    fontSize: '0.75rem',
                                                                    fontWeight: 'bold',
                                                                    display: 'inline-block',
                                                                    minWidth: '20px',
                                                                    boxShadow: '0 1px 3px rgba(0,0,0,0.2)'
                                                                }}
                                                                title={`${roomBookings.length} booking${roomBookings.length > 1 ? 's' : ''}`}
                                                            >
                                                                {roomBookings.length}
                                                            </div>
                                                        )}
                                                    </td>
                                                );
                                            })}
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </Card>

                    {/* Booking Details */}
                    {bookings.length > 0 && (
                        <Card md="12" title="Bookings Summary">
                            <div className="table-responsive">
                                <table className="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>Booking Ref</th>
                                            <th>Guest Name</th>
                                            <th>Room</th>
                                            <th>Check-in</th>
                                            <th>Check-out</th>
                                            <th>Guests</th>
                                            <th>Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {bookings.map((booking) => (
                                            <tr key={booking.id}>
                                                <td>{booking.booking_reference}</td>
                                                <td>{booking.full_name}</td>
                                                <td>{booking.room_display || 'N/A'}</td>
                                                <td>{booking.check_in ? formatDate(booking.check_in) : 'N/A'}</td>
                                                <td>{booking.check_out ? formatDate(booking.check_out) : 'N/A'}</td>
                                                <td>
                                                    {booking.number_of_adults} Adult{booking.number_of_adults !== 1 ? 's' : ''}
                                                    {booking.number_of_children > 0 && `, ${booking.number_of_children} Child${booking.number_of_children !== 1 ? 'ren' : ''}`}
                                                </td>
                                                <td>
                                                    <span className={`badge badge-${booking.status === 'confirmed' ? 'success' : 'warning'}`}>
                                                        {booking.status}
                                                    </span>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        </Card>
                    )}
                </Col>
            </Row>

            {/* Booking Details Modal */}
            {showBookingModal && selectedBookings.length > 0 && (
                <div 
                    className="modal show d-block" 
                    style={{ backgroundColor: 'rgba(0,0,0,0.5)' }}
                    onClick={() => setShowBookingModal(false)}
                >
                    <div 
                        className="modal-dialog modal-lg modal-dialog-centered"
                        onClick={(e) => e.stopPropagation()}
                    >
                        <div className="modal-content">
                            <div className="modal-header">
                                <h5 className="modal-title">
                                    Booking Details - {formatDate(selectedBookings[0].check_in)}
                                </h5>
                                <button 
                                    type="button" 
                                    className="close" 
                                    onClick={() => setShowBookingModal(false)}
                                >
                                    <span>&times;</span>
                                </button>
                            </div>
                            <div className="modal-body">
                                {selectedBookings.length === 1 ? (
                                    <div>
                                        <table className="table table-bordered">
                                            <tbody>
                                                <tr>
                                                    <th style={{ width: '30%' }}>Booking Reference</th>
                                                    <td><strong>{selectedBookings[0].booking_reference}</strong></td>
                                                </tr>
                                                <tr>
                                                    <th>Guest Name</th>
                                                    <td>{selectedBookings[0].full_name}</td>
                                                </tr>
                                                <tr>
                                                    <th>Email</th>
                                                    <td>{selectedBookings[0].email || 'N/A'}</td>
                                                </tr>
                                                <tr>
                                                    <th>Phone</th>
                                                    <td>{selectedBookings[0].phone || 'N/A'}</td>
                                                </tr>
                                                <tr>
                                                    <th>Room</th>
                                                    <td>{selectedBookings[0].room_display || 'N/A'}</td>
                                                </tr>
                                                <tr>
                                                    <th>Check-in</th>
                                                    <td>{selectedBookings[0].check_in ? formatDate(selectedBookings[0].check_in) : 'N/A'}</td>
                                                </tr>
                                                <tr>
                                                    <th>Check-out</th>
                                                    <td>{selectedBookings[0].check_out ? formatDate(selectedBookings[0].check_out) : 'N/A'}</td>
                                                </tr>
                                                <tr>
                                                    <th>Guests</th>
                                                    <td>
                                                        {selectedBookings[0].number_of_adults || 0} Adult{(selectedBookings[0].number_of_adults || 0) !== 1 ? 's' : ''}
                                                        {(selectedBookings[0].number_of_children || 0) > 0 && `, ${selectedBookings[0].number_of_children} Child${selectedBookings[0].number_of_children !== 1 ? 'ren' : ''}`}
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <th>Price</th>
                                                    <td>${selectedBookings[0].price || 0}</td>
                                                </tr>
                                                <tr>
                                                    <th>Status</th>
                                                    <td>
                                                        <span className={`badge badge-${selectedBookings[0].status === 'confirmed' ? 'success' : selectedBookings[0].status === 'cancelled' ? 'danger' : 'warning'}`}>
                                                            {selectedBookings[0].status}
                                                        </span>
                                                    </td>
                                                </tr>
                                                {selectedBookings[0].special_request && (
                                                    <tr>
                                                        <th>Special Request</th>
                                                        <td>{selectedBookings[0].special_request}</td>
                                                    </tr>
                                                )}
                                            </tbody>
                                        </table>
                                    </div>
                                ) : (
                                    <div>
                                        <p className="mb-3">
                                            <strong>{selectedBookings.length} bookings</strong> on this date:
                                        </p>
                                        <div className="table-responsive">
                                            <table className="table table-hover">
                                                <thead>
                                                    <tr>
                                                        <th>Reference</th>
                                                        <th>Guest</th>
                                                        <th>Room</th>
                                                        <th>Check-in</th>
                                                        <th>Check-out</th>
                                                        <th>Status</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    {selectedBookings.map((booking) => (
                                                        <tr key={booking.id}>
                                                            <td>{booking.booking_reference}</td>
                                                            <td>{booking.full_name}</td>
                                                            <td>{booking.room_display || 'N/A'}</td>
                                                            <td>{booking.check_in ? formatDate(booking.check_in) : 'N/A'}</td>
                                                            <td>{booking.check_out ? formatDate(booking.check_out) : 'N/A'}</td>
                                                            <td>
                                                                <span className={`badge badge-${booking.status === 'confirmed' ? 'success' : booking.status === 'cancelled' ? 'danger' : 'warning'}`}>
                                                                    {booking.status}
                                                                </span>
                                                            </td>
                                                        </tr>
                                                    ))}
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                )}
                            </div>
                            <div className="modal-footer">
                                <button 
                                    type="button" 
                                    className="btn btn-secondary" 
                                    onClick={() => setShowBookingModal(false)}
                                >
                                    Close
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            <style>{`
                .calendar-table {
                    border-collapse: separate;
                    border-spacing: 0;
                }
                
                .calendar-day {
                    font-size: 0.75rem;
                }
                
                .calendar-day.today {
                    background-color: #e3f2fd !important;
                    font-weight: bold;
                }
                
                .calendar-cell {
                    height: 45px;
                    vertical-align: middle;
                    transition: all 0.2s ease;
                }
                
                .calendar-cell.available {
                    background-color: #d4edda;
                    border: 1px solid #c3e6cb;
                }
                
                .calendar-cell.available:hover {
                    background-color: #c3e6cb;
                    transform: scale(1.05);
                }
                
                .calendar-cell.booked {
                    background-color: #f8d7da;
                    border: 1px solid #f5c6cb;
                }
                
                .calendar-cell.booked:hover {
                    background-color: #f5c6cb;
                    transform: scale(1.05);
                }
                
                .calendar-cell.other-month {
                    background-color: #f8f9fa;
                    opacity: 0.4;
                }
                
                .calendar-cell.past-date {
                    background-color: #e9ecef !important;
                    opacity: 0.5;
                    cursor: not-allowed !important;
                }
                
                .calendar-room-header,
                .calendar-room-cell {
                    background-color: #fff !important;
                    box-shadow: 2px 0 4px rgba(0,0,0,0.05);
                }
                
                .booking-indicator {
                    display: inline-block;
                }
                
                .btn:disabled {
                    opacity: 0.5;
                    cursor: not-allowed;
                }
                
                @media (max-width: 768px) {
                    .calendar-table {
                        font-size: 0.7rem;
                    }
                    
                    .calendar-cell {
                        height: 35px;
                        padding: 2px !important;
                    }
                    
                    .booking-indicator {
                        font-size: 0.65rem;
                        padding: 2px 4px !important;
                    }
                }
            `}</style>
        </>
    );
}

