"use client";
import { useMemo, useState } from "react";
import Link from "next/link";
import { WEEKDAYS, fmt12 } from "@/lib/timeslot-utils";

interface BookingWithTime {
  id: number;
  time_slot_id: number;
  booking_date: string;
  time_slots: { start_time: string; end_time: string };
}

interface ScheduleWithBookings {
  id: number;
  start_date: string;
  end_date: string;
  status: string;
  schedule_bookings: BookingWithTime[];
}

interface StudentAssignedCalendarProps {
  schedules: ScheduleWithBookings[];
}

const MONTH_NAMES = [
  "January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December",
];

function buildCalendarCells(month: Date) {
  const year = month.getFullYear();
  const m = month.getMonth();
  const firstDayOfMonth = new Date(year, m, 1);
  const daysInMonth = new Date(year, m + 1, 0).getDate();
  const leadingBlanks = firstDayOfMonth.getDay();

  const cells: { dateKey: string | null; dayNumber: number | null }[] = [];
  for (let i = 0; i < leadingBlanks; i++) cells.push({ dateKey: null, dayNumber: null });
  for (let d = 1; d <= daysInMonth; d++) {
    const dateKey = `${year}-${String(m + 1).padStart(2, "0")}-${String(d).padStart(2, "0")}`;
    cells.push({ dateKey, dayNumber: d });
  }
  return cells;
}

function getTodayKey() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

const StudentAssignedCalendar = ({ schedules }: StudentAssignedCalendarProps) => {
  const [visibleMonth, setVisibleMonth] = useState(() => {
    const now = new Date();
    return new Date(now.getFullYear(), now.getMonth(), 1);
  });
  const [selectedDate, setSelectedDate] = useState<string | null>(null);

  const todayKey = useMemo(() => getTodayKey(), []);
  const isPastDate = (dateKey: string) => dateKey < todayKey;

  const bookingsByDate = useMemo(() => {
    const map: Record<string, { schedule: ScheduleWithBookings; booking: BookingWithTime }> = {};
    for (const sched of schedules) {
      for (const b of sched.schedule_bookings) {
        map[b.booking_date.slice(0, 10)] = { schedule: sched, booking: b };
      }
    }
    return map;
  }, [schedules]);

  const calendarCells = useMemo(() => buildCalendarCells(visibleMonth), [visibleMonth]);
  const goPrevMonth = () => setVisibleMonth((m) => new Date(m.getFullYear(), m.getMonth() - 1, 1));
  const goNextMonth = () => setVisibleMonth((m) => new Date(m.getFullYear(), m.getMonth() + 1, 1));

  const handleMonthSelect = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const newMonth = parseInt(e.target.value, 10);
    setVisibleMonth((prev) => new Date(prev.getFullYear(), newMonth, 1));
  };

  const handleYearSelect = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const newYear = parseInt(e.target.value, 10);
    setVisibleMonth((prev) => new Date(newYear, prev.getMonth(), 1));
  };

  // Build a reasonable year range: a few years back to a few years ahead
  // of whichever years actually have scheduled bookings (falls back to
  // "this year ± 2" if there are no bookings at all).
  const yearOptions = useMemo(() => {
    const currentYear = new Date().getFullYear();
    const years: number[] = [];
    for (let y = currentYear; y <= currentYear + 10; y++) years.push(y);
    return years;
  }, []);

  const openDate = (dateKey: string) => {
    if (!bookingsByDate[dateKey]) return;
    setSelectedDate(dateKey);
  };

  return (
    <section className="aboutinnercontainer academycontainer calendarcontainer">
      <div className="container container-xxl">
        <div className="row justify-content-center">
          <div className="col-xxl-10 col-xl-10 col-lg-10 col-md-12 col-sm-12 col-12">
            <div className="p-0">
              <div className="row">
                {/* LEFT: calendar of assigned classes */}
                <div className="col-lg-12">
                  <div className="calendarbx">
                    <div className="d-flex calendar-control justify-content-between align-items-center mb-2 gap-2 flex-wrap">
                      <button className="default-btn" onClick={goPrevMonth} type="button">
                        <i className="bi bi-chevron-left" />
                      </button>

                      <div className="d-flex gap-2">
                        <select
                          className="form-select form-select-sm"
                          style={{ width: "auto" }}
                          value={visibleMonth.getMonth()}
                          onChange={handleMonthSelect}
                          aria-label="Select month"
                        >
                          {MONTH_NAMES.map((name, idx) => (
                            <option key={name} value={idx}>
                              {name}
                            </option>
                          ))}
                        </select>

                        <select
                          className="form-select form-select-sm"
                          style={{ width: "auto" }}
                          value={visibleMonth.getFullYear()}
                          onChange={handleYearSelect}
                          aria-label="Select year"
                        >
                          {yearOptions.map((y) => (
                            <option key={y} value={y}>
                              {y}
                            </option>
                          ))}
                        </select>
                      </div>

                      <button className="default-btn" onClick={goNextMonth} type="button">
                        <i className="bi bi-chevron-right" />
                      </button>
                    </div>
                    <p className="info-text">Click a highlighted date to view class details.</p>

                    <div
                      className="d-grid schedule-slot"
                      style={{ gridTemplateColumns: "repeat(7, 1fr)" }}
                    >
                      {WEEKDAYS.map((wd) => (
                        <div key={wd} className="text-center small fw-semibold calendar-heading">
                          {wd.slice(0, 2)}
                        </div>
                      ))}

                      {calendarCells.map((cell, idx) => {
                        if (!cell.dateKey) return <div key={idx} />;
                        const entry = bookingsByDate[cell.dateKey];
                        const isSelected = selectedDate === cell.dateKey;
                        const past = isPastDate(cell.dateKey);

                        return (
                          <button
                            key={idx}
                            onClick={() => openDate(cell.dateKey!)}
                            disabled={!entry}
                            className={`schedule-btn d-flex flex-column align-items-center justify-content-center ${isSelected ? "schedule-selected" : entry ? "available-schedule" : "not-available"
                              }`}
                            style={{
                              fontSize: 11,
                              opacity: entry ? (past ? 0.55 : 1) : 0.35,
                              lineHeight: 1.1,
                              position: "relative",
                            }}
                          >
                            <h6>{cell.dayNumber}</h6>
                            {entry && (
                              <span>
                                {fmt12(entry.booking.time_slots.start_time)}
                                <em>-</em>
                                {fmt12(entry.booking.time_slots.end_time)}
                              </span>
                            )}
                          </button>
                        );
                      })}
                    </div>

                    {Object.keys(bookingsByDate).length === 0 && (
                      <p className="text-muted small mt-3 mb-0">No upcoming classes scheduled.</p>
                    )}
                  </div>
                </div>

                {/* RIGHT: selected date details */}
                {/* <div className="col-lg-6 mt-4 mt-lg-0">
                  <div className="border rounded p-3 h-100">
                    {!selectedDate && (
                      <p className="text-muted small mb-0">Select a scheduled date on the calendar.</p>
                    )}

                    {selectedDate && bookingsByDate[selectedDate] && (
                      <>
                        <p className="fw-medium mb-2">{selectedDate}</p>
                        <p className="small text-muted mb-3">
                          Class time: {fmt12(bookingsByDate[selectedDate].booking.time_slots.start_time)} -{" "}
                          {fmt12(bookingsByDate[selectedDate].booking.time_slots.end_time)}
                        </p>

                        <Link href="/student/schedule" className="admin-theme-btn">
                          Manage / Request a Change
                        </Link>
                      </>
                    )}
                  </div>
                </div> */}
              </div>
              <div className="text-center mt-4">
                <Link href="/student/dashboard" className="theme-btn">Go to dashboard</Link>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

export default StudentAssignedCalendar;