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

const EventCalendar = () => {
  const [currentMonth, setCurrentMonth] = useState(moment());
  const [selectedYear, setSelectedYear] = useState("2025"); // <-- NEW: default selected year
  const router = useRouter();

  const events = [
    { id: 1, date: "2025-11-08", title: "Sathya Narayana poojai, Saturday", url: "/event-sathya-narayana-poojai" },
    { id: 2, date: "2025-12-07", title: "Sangada hara charthurthi, Sunday", url: "/event-sangada-hara-charthurthi-december" },
    { id: 3, date: "2026-01-01", title: "New year celebration, Thursday", url: "/event-new-year" },
    { id: 4, date: "2026-02-01", title: "Thai poosam, Sunday", url: "/event-thai-poosam" },
    { id: 5, date: "2026-03-06", title: "Sangada hara charthurthi, Friday", url: "/event-sangada-hara-charthurthi-march" },
    { id: 6, date: "2026-04-05", title: "Sangada hara charthurthi, Sunday", url: "/event-sangada-hara-charthurthi-april" },
    { id: 7, date: "2026-05-01", title: "Chitra Pournami (TBC), Friday", url: "/event-chitra-pournami" },
    { id: 8, date: "2026-05-16", title: "Monthly Karthigai (TBC), Saturday", url: "/event-monthly-karthigai-may" },
    { id: 9, date: "2026-05-29", title: "Vaikasi Visagam (TBC), Friday", url: "/event-vaikasi-visagam" },
    { id: 10, date: "2026-06-03", title: "Sangada hara chathurthi (TBC), Wednesday", url: "/event-sangada-hara-charthurthi-june" },
    { id: 11, date: "2026-06-12", title: "Monthly Karthigai (TBC), Friday", url: "/event-monthly-karthigai-june" },
  ];

  const filteredEvents = events.filter(
    (event) => moment(event.date).format("YYYY") === selectedYear
  );

  const startOfMonth = currentMonth.clone().startOf("month");
  const endOfMonth = currentMonth.clone().endOf("month");

  const daysInMonth = [];
  for (let i = 0; i < startOfMonth.day(); i++) {
    daysInMonth.push(null);
  }
  for (let i = 1; i <= endOfMonth.date(); i++) {
    daysInMonth.push(moment(currentMonth).date(i));
  }

  const getEventForDate = (date) => {
    const dateString = date?.format("YYYY-MM-DD");
    return events.filter(event => event.date === dateString);
  };

  const handleMonthChange = (direction) => {
    setCurrentMonth(currentMonth.clone().add(direction, "months"));
  };

  const handleYearClick = (year) => {
    setSelectedYear(year);
  };

  return (
    <div className="service-area-2 space overflow-hidden" id="event-calender">
      <div className="container">
        <h2 className="text-center mb-4">Event Calendar</h2>

        {/* === Year Filter Buttons === */}
        <div className="d-flex justify-content-center gap-3 mb-4">
          {["2025", "2026"].map((year) => (
            <button
              key={year}
              className={`btn ${selectedYear === year ? "btn-warning" : "btn-outline-warning"}`}
              onClick={() => handleYearClick(year)}
            >
              {year}
            </button>
          ))}
        </div>

        <div className="row justify-content-between">
          <div className="col-12 col-lg-4">
            <div className="d-flex justify-content-between align-items-center">
              <button className="btn style2" onClick={() => handleMonthChange(-1)}>Prev</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",
                        backgroundColor:
                        getEventForDate(day).length > 0 ? "#eac768" : "white",
                        position: "relative",
                    }}
                    title={
                        getEventForDate(day).length > 0
                        ? getEventForDate(day).map((e) => e.title).join(", ")
                        : ""
                    } // shows event name on hover
                    >
                    {day ? <span className="text-end d-block">{day.date()}</span> : ""}
                    </td>

                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* === Events Table === */}
          <div className="col-12 col-lg-7">
            <table
              className="table table-bordered mt-4 custom-scroll"
              style={{
                height: `${filteredEvents?.length > 5 ? "300px" : "auto"}`,
                overflowY: filteredEvents?.length > 5 ? "auto" : "visible",
                tableLayout: "fixed",
              }}
            >
              <thead>
                <tr>
                  <th className="fs-4 p-3">Date and Time</th>
                  <th className="fs-4 p-3">Event Name</th>
                </tr>
              </thead>
              <tbody>
                {filteredEvents.map((event) => (
                  <tr key={event.id}>
                    <td className="fs-6 p-3">
                      {moment(event.date).format("YYYY-MMM-DD")}
                    </td>
                    <td className="fs-6 p-3">
                      <Link href={event?.url}>{event.title}</Link>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
};

export default EventCalendar;
