"use client";

import { useState, useEffect } from "react";
import type { ReactElement } from "react";
import { Calendar } from "@/components/calendar/Calendar";
import { mockEvents } from "@/lib/api/events";
import type { Event } from "@mosaic/shared";

export default function CalendarPage(): ReactElement {
  const [events, setEvents] = useState<Event[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    void loadEvents();
  }, []);

  async function loadEvents(): Promise<void> {
    setIsLoading(true);
    setError(null);

    try {
      // TODO: Replace with real API call when backend is ready
      // const data = await fetchEvents();
      await new Promise((resolve) => setTimeout(resolve, 300));
      setEvents(mockEvents);
    } catch (err) {
      setError(
        err instanceof Error
          ? err.message
          : "We had trouble loading your calendar. Please try again when you're ready."
      );
    } finally {
      setIsLoading(false);
    }
  }

  return (
    <main className="container mx-auto px-4 py-8">
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900">Calendar</h1>
        <p className="text-gray-600 mt-2">View your schedule at a glance</p>
      </div>

      {error !== null ? (
        <div className="rounded-lg border border-amber-200 bg-amber-50 p-6 text-center">
          <p className="text-amber-800">{error}</p>
          <button
            onClick={() => void loadEvents()}
            className="mt-4 rounded-md bg-amber-600 px-4 py-2 text-sm font-medium text-white hover:bg-amber-700 transition-colors"
          >
            Try again
          </button>
        </div>
      ) : (
        <Calendar events={events} isLoading={isLoading} />
      )}
    </main>
  );
}
