"use client";

import { useEffect, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { RefreshCw, Calendar as CalendarIcon } from "lucide-react";
import { useRouter } from "next/navigation";

interface Event {
  id: string;
  title: string;
  start: string;
  end: string;
  allDay: boolean;
  calendar: string;
  calendarColor: string;
}

export function Calendar() {
  const [events, setEvents] = useState<Event[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const router = useRouter();

  const fetchEvents = async () => {
    setLoading(true);
    try {
      const response = await fetch('/api/calendars?refresh=true');
      if (!response.ok) {
        throw new Error('Failed to fetch events');
      }
      
      const calendarsData = await response.json();
      console.log('Calendar Widget - Fetched calendars:', calendarsData);

      // Get current date at the start of the day
      const now = new Date();
      now.setHours(0, 0, 0, 0);

      // Helper function to get display name for calendar
      const getCalendarDisplayName = (calendar: any) => {
        // If calendar is synced to an external account, use the account name
        if (calendar.syncConfig?.syncEnabled && calendar.syncConfig?.mailCredential) {
          return calendar.syncConfig.mailCredential.display_name || 
                 calendar.syncConfig.mailCredential.email;
        }
        // For non-synced calendars, use the calendar name
        return calendar.name;
      };

      // Extract and process events from all calendars
      const allEvents = calendarsData.flatMap((calendar: any) => 
        (calendar.events || []).map((event: any) => ({
          id: event.id,
          title: event.title,
          start: event.start,
          end: event.end,
          allDay: event.isAllDay,
          calendar: getCalendarDisplayName(calendar),
          calendarColor: calendar.color,
          externalEventId: event.externalEventId || null, // Add externalEventId for deduplication
        }))
      );

      // Deduplicate events by externalEventId (if same event appears in multiple calendars)
      // Keep the first occurrence of each unique externalEventId
      const seenExternalIds = new Set<string>();
      const seenEventKeys = new Set<string>(); // For events without externalEventId, use title+start+calendar as key
      const deduplicatedEvents = allEvents.filter((event: any) => {
        if (event.externalEventId) {
          // For events with externalEventId, deduplicate strictly by externalEventId
          if (seenExternalIds.has(event.externalEventId)) {
            console.log('Calendar Widget - Skipping duplicate by externalEventId:', {
              title: event.title,
              externalEventId: event.externalEventId,
              calendar: event.calendar,
            });
            return false; // Skip duplicate
          }
          seenExternalIds.add(event.externalEventId);
        } else {
          // For events without externalEventId, use title + start date + calendar as key
          // This prevents false positives when same title/date appears in different calendars
          const eventKey = `${event.title}|${new Date(event.start).toISOString().split('T')[0]}|${event.calendar}`;
          if (seenEventKeys.has(eventKey)) {
            console.log('Calendar Widget - Skipping duplicate by title+date+calendar:', {
              title: event.title,
              start: event.start,
              calendar: event.calendar,
            });
            return false; // Skip duplicate
          }
          seenEventKeys.add(eventKey);
        }
        return true; // Keep event
      });
      
      console.log('Calendar Widget - Deduplication:', {
        totalBefore: allEvents.length,
        totalAfter: deduplicatedEvents.length,
        duplicatesRemoved: allEvents.length - deduplicatedEvents.length,
      });

      // Filter for upcoming events
      const upcomingEvents = deduplicatedEvents
        .filter((event: any) => new Date(event.start) >= now)
        .sort((a: any, b: any) => new Date(a.start).getTime() - new Date(b.start).getTime())
        .slice(0, 7);

      console.log('Calendar Widget - Processed events:', upcomingEvents);
      setEvents(upcomingEvents);
      setError(null);
    } catch (err) {
      console.error('Error fetching events:', err);
      setError('Failed to load events');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchEvents();
  }, []);

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return new Intl.DateTimeFormat('fr-FR', {
      day: '2-digit',
      month: 'short'
    }).format(date);
  };

  const formatTime = (dateString: string) => {
    const date = new Date(dateString);
    return new Intl.DateTimeFormat('fr-FR', {
      hour: '2-digit',
      minute: '2-digit',
    }).format(date);
  };

  return (
    <Card className="transition-transform duration-500 ease-in-out transform hover:scale-105 bg-white/95 backdrop-blur-sm border-0 shadow-lg">
      <CardHeader className="flex flex-row items-center justify-between pb-2 border-b border-gray-100">
        <CardTitle className="text-lg font-semibold text-gray-800 flex items-center gap-2">
          <CalendarIcon className="h-5 w-5 text-gray-600" />
          Agenda
        </CardTitle>
        <Button 
          variant="ghost" 
          size="icon" 
          onClick={() => fetchEvents()}
          className="h-7 w-7 p-0 hover:bg-gray-100/50 rounded-full"
        >
          <RefreshCw className="h-3.5 w-3.5 text-gray-600" />
        </Button>
      </CardHeader>
      <CardContent className="p-3">
        {loading ? (
          <div className="flex items-center justify-center py-6">
            <div className="h-4 w-4 animate-spin rounded-full border-2 border-blue-500 border-t-transparent" />
          </div>
        ) : error ? (
          <div className="text-xs text-red-500 text-center py-3">{error}</div>
        ) : events.length === 0 ? (
          <div className="text-xs text-gray-500 text-center py-6">No upcoming events</div>
        ) : (
          <div className="space-y-2 max-h-[400px] overflow-y-auto pr-1 scrollbar-thin scrollbar-thumb-gray-200 scrollbar-track-transparent">
            {events.map((event) => (
              <div 
                key={event.id}
                className="p-2 rounded-lg bg-white shadow-sm hover:shadow-md transition-all duration-200 border border-gray-100"
              >
                <div className="flex gap-2">
                  <div 
                    className="flex-shrink-0 w-14 h-14 rounded-lg flex flex-col items-center justify-center border"
                    style={{
                      backgroundColor: `${event.calendarColor}10`,
                      borderColor: event.calendarColor
                    }}
                  >
                    <span 
                      className="text-[10px] font-medium"
                      style={{ color: event.calendarColor }}
                    >
                      {formatDate(event.start)}
                    </span>
                    <span 
                      className="text-[10px] font-bold mt-0.5"
                      style={{ color: event.calendarColor }}
                    >
                      {formatTime(event.start)}
                    </span>
                  </div>
                  <div className="flex-1 min-w-0 space-y-1">
                    <div className="flex items-start justify-between gap-2">
                      <p className="text-sm font-medium text-gray-800 line-clamp-2 flex-1">
                        {event.title}
                      </p>
                      {!event.allDay && (
                        <span className="text-[10px] text-gray-500 whitespace-nowrap">
                          {formatTime(event.start)} - {formatTime(event.end)}
                        </span>
                      )}
                    </div>
                    <div 
                      className="flex items-center text-[10px] px-1.5 py-0.5 rounded-md"
                      style={{
                        backgroundColor: `${event.calendarColor}10`,
                        color: event.calendarColor
                      }}
                    >
                      <span className="truncate">{event.calendar}</span>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  );
} 