"use client";
import { useState, useEffect } from "react";
import moment from "moment";
import { useRouter } from "next/navigation";

const EventCalendar = () => {
    const [currentMonth, setCurrentMonth] = useState(moment());
    const router = useRouter();

    // Sample event data with ID, date, title, and description
    const events = [
        { id: 1, date: "2025-03-20", title: "Event 1", description: "This is a detailed description for Event 1" },
        { id: 2, date: "2025-03-22", title: "Event 2", description: "This is a detailed description for Event 2" },
        { id: 3, date: "2025-03-25", title: "Event 3", description: "This is a detailed description for Event 3" },
    ];

    // Get the start and end of the current month
    const startOfMonth = currentMonth.clone().startOf("month");
    const endOfMonth = currentMonth.clone().endOf("month");

    // Generate the calendar days
    const daysInMonth = [];
    for (let i = 0; i < startOfMonth.day(); i++) {
        daysInMonth.push(null); // Adding null for empty days before the start of the month
    }
    for (let i = 1; i <= endOfMonth.date(); i++) {
        daysInMonth.push(moment(currentMonth).date(i));
    }

    // Function to check if a date has an event
    const getEventForDate = (date) => {
        const dateString = date.format("YYYY-MM-DD");
        return events.filter(event => event.date === dateString);
    };

    // Function to navigate to the next/previous month
    const handleMonthChange = (direction) => {
        setCurrentMonth(currentMonth.clone().add(direction, "months"));
    };

    // Function to handle event title click
    const handleEventClick = (eventId) => {
        // Redirect to the event details page using the event ID
        router.push(`/event-details/${eventId}`);
    };

    // Initialize Bootstrap tooltips after the component mounts
    // useEffect(() => {
    //     // Initialize all tooltips on render
    //     const tooltipTriggerList = Array.from(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    //     tooltipTriggerList.forEach((tooltipTriggerEl) => new window.bootstrap.Tooltip(tooltipTriggerEl));
    // }, []);

    return (
        <div className="service-area-2 space overflow-hidden">
            <div className="container">
                <div className="row justify-content-center">
                    <div className="col-12 col-md-12">
                        <h2 className="text-center mb-4">Event Calendar</h2>

                        <div className="d-flex justify-content-between align-items-center">
                            <button
                                className="btn style2"
                                onClick={() => handleMonthChange(-1)}
                            >
                                Previous
                            </button>
                            <span className="mx-3">
                                {currentMonth.format("MMMM YYYY")}
                            </span>
                            <button
                                className="btn style2"
                                onClick={() => handleMonthChange(1)}
                            >
                                Next
                            </button>
                        </div>

                        <table className="table table-bordered mt-4" style={{ tableLayout: "fixed" }}>
                            <thead>
                                <tr>
                                    {["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].map((day, index) => (
                                        <th key={index} className="text-center">
                                            {day}
                                        </th>
                                    ))}
                                </tr>
                            </thead>
                            <tbody>
                                {Array.from({ length: Math.ceil(daysInMonth.length / 7) }, (_, rowIndex) => (
                                    <tr key={rowIndex}>
                                        {daysInMonth.slice(rowIndex * 7, (rowIndex + 1) * 7).map((day, index) => (
                                            <td
                                                key={index}
                                                style={{
                                                    cursor: day ? "default" : "not-allowed",
                                                    height: "120px", // Fixed height for each cell
                                                }}
                                            >
                                                {day ? (
                                                    <div style={{ width: "100%", height: "100%" }}>
                                                        {/* Align day number to the right */}
                                                        <span className="text-end d-block">{day.date()}</span>

                                                        {/* Display event names if present */}
                                                        {getEventForDate(day).map((event, eventIndex) => (
                                                            <div
                                                                key={eventIndex}
                                                                style={{ background: "#d2a530", cursor: "pointer" }}
                                                                className="text-sm text-white p-1 text-center mt-1"
                                                                onClick={() => handleEventClick(event.id)} // Add click handler
                                                                data-bs-toggle="tooltip"
                                                                data-bs-placement="top"
                                                                title={`Event: ${event.title}\nDescription: ${event.description}\nDate: ${event.date}`}
                                                            >
                                                                {event.title}
                                                            </div>
                                                        ))}
                                                    </div>
                                                ) : (
                                                    ""
                                                )}
                                            </td>
                                        ))}
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default EventCalendar;
