
'use client';

import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Calendar, Plus, Download, Settings, RefreshCw } from 'lucide-react';
import { toast } from 'sonner';
import { AddEventDialog } from './add-event-dialog';
import { CalendarSyncSettings } from './calendar-sync-settings';
import { format } from 'date-fns';

interface CalendarEvent {
  id: string;
  title: string;
  description?: string;
  location?: string;
  startTime: string;
  endTime: string;
  eventType: string;
  syncStatus: string;
  syncProvider?: string;
}

export function CalendarView() {
  const [events, setEvents] = useState<CalendarEvent[]>([]);
  const [loading, setLoading] = useState(true);
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [showSettings, setShowSettings] = useState(false);
  const [selectedDate, setSelectedDate] = useState(new Date());

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

  const fetchEvents = async () => {
    try {
      setLoading(true);
      const startDate = new Date(selectedDate);
      startDate.setDate(1);
      const endDate = new Date(selectedDate);
      endDate.setMonth(endDate.getMonth() + 1);
      endDate.setDate(0);

      const response = await fetch(
        `/api/calendar/events?startDate=${startDate.toISOString()}&endDate=${endDate.toISOString()}`
      );
      const data = await response.json();
      
      if (response.ok) {
        setEvents(data.events || []);
      } else {
        toast.error('Failed to load calendar events');
      }
    } catch (error) {
      console.error('Error fetching events:', error);
      toast.error('Error loading calendar events');
    } finally {
      setLoading(false);
    }
  };

  const handleExportICS = async () => {
    try {
      const response = await fetch('/api/calendar/export-ics');
      if (response.ok) {
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'quote2contract-calendar.ics';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
        toast.success('Calendar exported successfully');
      } else {
        toast.error('Failed to export calendar');
      }
    } catch (error) {
      console.error('Error exporting calendar:', error);
      toast.error('Error exporting calendar');
    }
  };

  const getEventTypeColor = (type: string) => {
    const colors: Record<string, string> = {
      WORK_START: 'bg-green-500',
      DELIVERY: 'bg-blue-500',
      INSPECTION: 'bg-yellow-500',
      SIGN_OFF: 'bg-purple-500',
      MILESTONE: 'bg-orange-500',
      MEETING: 'bg-pink-500',
      FOLLOW_UP: 'bg-indigo-500'
    };
    return colors[type] || 'bg-gray-500';
  };

  const getSyncStatusBadge = (status: string, provider?: string) => {
    if (status === 'SYNCED' && provider) {
      return (
        <Badge variant="outline" className="text-green-600 border-green-600">
          ✓ Synced to {provider}
        </Badge>
      );
    }
    if (status === 'PENDING') {
      return (
        <Badge variant="outline" className="text-yellow-600 border-yellow-600">
          Pending Sync
        </Badge>
      );
    }
    if (status === 'FAILED') {
      return (
        <Badge variant="outline" className="text-red-600 border-red-600">
          Sync Failed
        </Badge>
      );
    }
    return null;
  };

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="flex items-center gap-2">
              <Calendar className="w-5 h-5" />
              CRM Calendar
            </CardTitle>
            <div className="flex items-center gap-2">
              <Button variant="outline" size="sm" onClick={handleExportICS}>
                <Download className="w-4 h-4 mr-2" />
                Export ICS
              </Button>
              <Button variant="outline" size="sm" onClick={() => setShowSettings(true)}>
                <Settings className="w-4 h-4 mr-2" />
                Sync Settings
              </Button>
              <Button size="sm" onClick={() => setShowAddDialog(true)}>
                <Plus className="w-4 h-4 mr-2" />
                Add Event
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            <div className="flex items-center justify-between mb-4">
              <Button
                variant="outline"
                size="sm"
                onClick={() => {
                  const newDate = new Date(selectedDate);
                  newDate.setMonth(newDate.getMonth() - 1);
                  setSelectedDate(newDate);
                }}
              >
                Previous
              </Button>
              <h3 className="text-lg font-semibold">
                {format(selectedDate, 'MMMM yyyy')}
              </h3>
              <Button
                variant="outline"
                size="sm"
                onClick={() => {
                  const newDate = new Date(selectedDate);
                  newDate.setMonth(newDate.getMonth() + 1);
                  setSelectedDate(newDate);
                }}
              >
                Next
              </Button>
            </div>

            {loading ? (
              <div className="text-center py-8 text-muted-foreground">
                Loading events...
              </div>
            ) : events.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                No events scheduled for this month.
              </div>
            ) : (
              <div className="space-y-3">
                {events.map((event) => (
                  <div
                    key={event.id}
                    className="border rounded-lg p-4 hover:bg-muted/50 transition-colors"
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-2">
                          <div
                            className={`w-3 h-3 rounded-full ${getEventTypeColor(
                              event.eventType
                            )}`}
                          />
                          <h4 className="font-semibold">{event.title}</h4>
                          <Badge variant="secondary">{event.eventType.replace('_', ' ')}</Badge>
                        </div>
                        {event.description && (
                          <p className="text-sm text-muted-foreground mb-2">
                            {event.description}
                          </p>
                        )}
                        <div className="flex items-center gap-4 text-sm text-muted-foreground">
                          <span>
                            {format(new Date(event.startTime), 'MMM dd, yyyy HH:mm')} -{' '}
                            {format(new Date(event.endTime), 'HH:mm')}
                          </span>
                          {event.location && <span>📍 {event.location}</span>}
                        </div>
                      </div>
                      <div>
                        {getSyncStatusBadge(event.syncStatus, event.syncProvider)}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      <AddEventDialog
        open={showAddDialog}
        onOpenChange={setShowAddDialog}
        onEventAdded={fetchEvents}
      />

      <CalendarSyncSettings
        open={showSettings}
        onOpenChange={setShowSettings}
      />
    </div>
  );
}
