"use client";
import { useEffect, useState } from "react";
import axiosInstance from "@/lib/axiosInstance";
import CalendarRestrictedNotice from "./Calendarrestrictednotice";
import StudentAssignedCalendar from "./StudentAssignedCalendar";

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[];
}

const CalendarSection = () => {
  const [checking, setChecking] = useState(true);
  const [isStudent, setIsStudent] = useState(false);
  const [schedules, setSchedules] = useState<ScheduleWithBookings[]>([]);

  useEffect(() => {
    const checkStudentAndLoad = async () => {
      try {
        // If this succeeds, the visitor has a valid student session.
        const { data } = await axiosInstance.get("/student/schedule");
        setSchedules(data?.data ?? []);
        setIsStudent(true);

        // NOTE: Logged-in students used to be redirected straight to
        // /student/dashboard whenever they landed on this public /calendar
        // page. That redirect has been disabled on purpose — a logged-in
        // student should now stay on this page and see their assigned
        // classes rendered below via <StudentAssignedCalendar />.
        //
        // if (typeof window !== "undefined") {
        //   window.location.href = "/student/dashboard";
        // }
      } catch (error) {
        // Not logged in (401) or request failed -> treat as a guest visitor.
        setIsStudent(false);
      } finally {
        setChecking(false);
      }
    };

    checkStudentAndLoad();
  }, []);

  if (checking) {
    return (
      <section className="aboutinnercontainer academycontainer calendarcontainer">
        <div className="container container-xxl">
          <p className="text-muted small text-center mb-0">Loading calendar...</p>
        </div>
      </section>
    );
  }

  if (!isStudent) {
    return <CalendarRestrictedNotice />;
  }

  return <StudentAssignedCalendar schedules={schedules} />;
};

export default CalendarSection;