import { useRef } from "react";
import FullCalendar from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid";
import interactionPlugin from "@fullcalendar/interaction";
import { EventInput } from "@fullcalendar/core";
import { RefreshCw } from "lucide-react";
import { CashflowEvent } from "@/types/cashflow";

interface CashflowCalendarProps {
  events: CashflowEvent[];
  loading: boolean;
  onEventClick: (event: CashflowEvent) => void;
}

export function CashflowCalendar({
  events,
  loading,
  onEventClick,
}: CashflowCalendarProps) {
  const calendarRef = useRef<any>(null);

  // Filter and transform events for FullCalendar
  const filteredEvents: EventInput[] = events.map((event) => ({
    id: String(event.id),
    title: event.title,
    start: event.start,
    end: event.end,
    backgroundColor: event.color,
    borderColor: event.color,
    textColor: event.textColor,
    extendedProps: {
      ...event.details,
      detailUrl: event.detailUrl,
      originalEvent: event,
    },
  }));

  const handleEventClick = (info: any) => {
    const clickedEvent = info.event.extendedProps
      .originalEvent as CashflowEvent;
    if (clickedEvent) {
      onEventClick(clickedEvent);
    }
  };

  if (loading && events.length === 0) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="text-center">
          <RefreshCw className="inline-block h-8 w-8 animate-spin text-[#428B4D] mb-4" />
          <p className="text-gray-600">Loading events...</p>
        </div>
      </div>
    );
  }

  return (
    <>
      {/* Event Count Info */}
      {events.length > 0 && (
        <div className="mb-4 text-sm text-gray-600">
          Showing {filteredEvents.length} of {events.length} events
        </div>
      )}

      <FullCalendar
        ref={calendarRef}
        plugins={[dayGridPlugin, interactionPlugin]}
        initialView="dayGridMonth"
        events={filteredEvents}
        eventClick={handleEventClick}
        headerToolbar={{
          left: "prev,next today",
          center: "title",
          right: "dayGridMonth,dayGridWeek",
        }}
        height="auto"
        eventDisplay="block"
        eventTimeFormat={{
          hour: "2-digit",
          minute: "2-digit",
          meridiem: false,
        }}
        dayMaxEvents={3}
        moreLinkClick="popover"
        eventClassNames="cursor-pointer hover:opacity-80 transition-opacity"
      />
    </>
  );
}
