import { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import FullCalendar from '@fullcalendar/react'
import dayGridPlugin from '@fullcalendar/daygrid'
import timeGridPlugin from '@fullcalendar/timegrid'
import interactionPlugin from '@fullcalendar/interaction'
import allLocales from '@fullcalendar/core/locales-all';

interface CalendarEvent {
  id: number
  title: string
  startDate: string
  endDate: string
  time: string
  color: string
  [key: string]: any
}

interface CalendarViewProps {
  events: CalendarEvent[]
  onEventClick?: (event: CalendarEvent) => void
  onDateClick?: (date: Date) => void
  onMonthChange?: (month: string) => void
}

export default function CalendarView({ events, onEventClick, onDateClick, onMonthChange }: CalendarViewProps) {
  const { t, i18n } = useTranslation()
  const [isInitialized, setIsInitialized] = useState(false)



  const calendarEvents = useMemo(() => {
    return events.map(event => {
      const startDate = new Date(event.startDate);
      const endDate = new Date(event.endDate);
      
      // For FullCalendar, end date should be the day after the last day for proper spanning
      const calendarEndDate = event.startDate !== event.endDate ? 
        new Date(endDate.getTime() + 24 * 60 * 60 * 1000).toISOString().split('T')[0] : 
        undefined;
      
      return {
        id: event.id.toString(),
        title: event.title,
        start: event.startDate,
        end: calendarEndDate,
        allDay: true,
        backgroundColor: event.color,
        borderColor: event.color,
        extendedProps: event
      };
    })
  }, [events])

  const handleEventClick = (info: any) => {
    onEventClick?.(info.event.extendedProps)
  }

  const handleDateClick = (info: any) => {
    onDateClick?.(new Date(info.dateStr))
  }

  const calendarLocale = (() => {
        const lang = i18n.language || 'en';
        const normalized = lang.toLowerCase().replace('_', '-');
        return normalized === 'zh' ? 'zh-cn' : normalized;
    })();

  return (
    <div className="fullcalendar-container w-full overflow-x-auto">
      <FullCalendar
        locales={allLocales}
        locale={calendarLocale}
        plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
        initialView="dayGridMonth"
        headerToolbar={{
          left: 'prev,next today',
          center: 'title',
          right: 'dayGridMonth,timeGridWeek,timeGridDay'
        }}
        events={calendarEvents}
        height="auto"
        eventClick={handleEventClick}
        dateClick={handleDateClick}
        datesSet={(info) => {
          if (isInitialized) {
            const month = info.start.toISOString().slice(0, 7);
            onMonthChange?.(month);
          } else {
            setIsInitialized(true);
          }
        }}
        dayMaxEventRows={3}
        moreLinkText={t('more')}
        allDayText={t('All day')}
        eventMaxStack={3}
      />
      
      <style>{`
        .fullcalendar-container {
          width: 100%;
        }
        
        .fullcalendar-container .fc {
          --fc-today-bg-color: hsl(var(--primary) / 0.15) !important;
          --fc-border-color: hsl(var(--border)) !important;
          --fc-neutral-bg-color: hsl(var(--muted) / 0.4) !important;
          --fc-page-bg-color: hsl(var(--card)) !important;
          font-family: inherit;
          border: 1px solid hsl(var(--border));
          border-radius: 0.5rem;
          background: hsl(var(--card)) !important;
          color: hsl(var(--card-foreground));
          width: 100%;
          min-width: 300px;
        }
        
        .fullcalendar-container .fc-toolbar {
          margin-bottom: 0;
          padding: 1rem;
          border-bottom: 1px solid hsl(var(--border));
          flex-wrap: wrap;
          gap: 0.5rem;
        }
        
        @media (max-width: 768px) {
          .fullcalendar-container .fc-toolbar {
            padding: 0.5rem;
            flex-direction: column;
            align-items: center;
            gap: 0.5rem;
          }
          
          .fullcalendar-container .fc-toolbar-chunk {
            display: flex;
            justify-content: center;
            flex-wrap: wrap;
            gap: 0.25rem;
          }
          
          .fullcalendar-container .fc-button {
            padding: 0.25rem 0.5rem;
            font-size: 0.75rem;
            border-radius: 0.375rem;
          }
          
          .fullcalendar-container .fc-toolbar-title {
            font-size: 0.95rem;
            text-align: center;
          }
          
          .fullcalendar-container .fc-view-harness {
            padding: 0.25rem;
          }
          
          .fullcalendar-container .fc-daygrid-day-number {
            padding: 0.125rem 0.25rem;
            font-size: 0.7rem;
          }
          
          .fullcalendar-container .fc-event {
            padding: 0.125rem 0.25rem;
            font-size: 0.65rem;
            margin: 0.0625rem 0;
            min-height: 1.25rem;
          }
          
          .fullcalendar-container .fc-event-title {
            font-size: 0.65rem;
          }
          
          .fullcalendar-container .fc-col-header-cell {
            padding: 0.375rem 0.125rem;
            font-size: 0.7rem;
          }
        }
        
        .fullcalendar-container .fc-toolbar-title {
          font-size: 1.25rem;
          font-weight: 600;
          color: hsl(var(--foreground));
        }
        
        .fullcalendar-container .fc-button {
          background: hsl(var(--primary));
          border: 1px solid hsl(var(--primary));
          color: hsl(var(--primary-foreground));
          padding: 0.5rem 0.75rem;
          border-radius: 0.5rem;
          font-size: 0.875rem;
          font-weight: 500;
          text-transform: capitalize;
          box-shadow: none !important;
          transition: all 0.2s ease;
        }
        
        .fullcalendar-container .fc-button:hover {
          background: hsl(var(--primary) / 0.9) !important;
          border-color: hsl(var(--primary) / 0.9) !important;
          color: hsl(var(--primary-foreground)) !important;
        }
        
        .fullcalendar-container .fc-button-active {
          background: hsl(var(--primary)) !important;
          border-color: hsl(var(--primary)) !important;
          color: hsl(var(--primary-foreground)) !important;
        }

        .fullcalendar-container .fc-button:not(.fc-button-active):not(:hover) {
          background: hsl(var(--muted)) !important;
          border-color: hsl(var(--border)) !important;
          color: hsl(var(--muted-foreground)) !important;
        }

        .fullcalendar-container .fc-button:disabled {
          opacity: 0.6 !important;
          background: hsl(var(--muted)) !important;
          border-color: hsl(var(--border)) !important;
          color: hsl(var(--muted-foreground)) !important;
          cursor: not-allowed;
        }
        
        .fullcalendar-container .fc-view-harness {
          padding: 1rem;
          overflow: visible !important;
        }

        .fullcalendar-container .fc-theme-standard td,
        .fullcalendar-container .fc-theme-standard th,
        .fullcalendar-container .fc-scrollgrid {
          border-color: hsl(var(--border)) !important;
        }
        
        .fullcalendar-container .fc-daygrid-day {
          cursor: pointer;
          border: 1px solid hsl(var(--border));
          transition: all 0.2s ease;
          overflow: visible !important;
          background: hsl(var(--card));
        }
        
        .fullcalendar-container .fc-daygrid-day:hover {
          background: hsl(var(--accent) / 0.5) !important;
        }
        
        .fullcalendar-container .fc-day-other {
          background: hsl(var(--muted) / 0.2) !important;
        }

        .fullcalendar-container .fc-daygrid-day-number {
          color: hsl(var(--foreground));
          font-weight: 600;
          padding: 0.5rem;
          font-size: 0.875rem;
        }

        .fullcalendar-container .fc-day-other .fc-daygrid-day-number {
          color: hsl(var(--muted-foreground) / 0.6);
        }
        
        .fullcalendar-container .fc-event {
          border-radius: 0.375rem;
          padding: 0.375rem 0.75rem;
          font-size: 0.8rem;
          border: none;
          margin: 0.25rem;
          min-height: 2rem;
          display: flex;
          align-items: center;
          cursor: pointer;
          transition: opacity 0.2s ease;
        }
        
        .fullcalendar-container .fc-event:hover {
          opacity: 0.9;
        }
        
        .fullcalendar-container .fc-daygrid-event {
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          width: 100%;
        }
        
        .fullcalendar-container .fc-event-title {
          font-weight: 600;
          font-size: 0.8rem;
          line-height: 1.3;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          width: 100%;
          color: white !important;
        }
        
        .fullcalendar-container .fc-event-main {
          width: 100%;
          display: flex;
          align-items: center;
        }
        
        .fullcalendar-container .fc-event-main-frame {
          width: 100%;
          display: flex;
          align-items: center;
        }
        
        .fullcalendar-container .fc-day-today,
        .fullcalendar-container .fc-daygrid-day.fc-day-today,
        .fullcalendar-container .fc-timegrid-col.fc-day-today,
        .fullcalendar-container td.fc-day-today {
          background: hsl(var(--primary) / 0.1) !important;
        }

        .fullcalendar-container .fc-daygrid-day.fc-day-today .fc-daygrid-day-number {
          color: hsl(var(--primary)) !important;
          font-weight: 700 !important;
        }
        
        .fullcalendar-container .fc-col-header-cell,
        .fullcalendar-container th.fc-col-header-cell,
        .fullcalendar-container .fc-theme-standard th {
          background: hsl(var(--muted) / 0.5) !important;
          border: 1px solid hsl(var(--border)) !important;
          color: hsl(var(--foreground)) !important;
          padding: 0.5rem;
          font-size: 0.875rem;
        }

        .fullcalendar-container .fc-col-header-cell-cushion,
        .fullcalendar-container th.fc-col-header-cell a {
          color: hsl(var(--foreground)) !important;
          text-decoration: none !important;
          font-weight: 600 !important;
          display: inline-block;
          padding: 0.25rem 0.5rem;
        }

        .fullcalendar-container .fc-col-header-cell.fc-day-today,
        .fullcalendar-container th.fc-col-header-cell.fc-day-today,
        .fullcalendar-container .fc-theme-standard th.fc-day-today,
        .fullcalendar-container .fc-scrollgrid-sync-table th.fc-day-today {
          background: hsl(var(--primary)) !important;
          color: hsl(var(--primary-foreground)) !important;
        }

        .fullcalendar-container .fc-col-header-cell.fc-day-today *,
        .fullcalendar-container th.fc-col-header-cell.fc-day-today *,
        .fullcalendar-container .fc-col-header-cell.fc-day-today .fc-col-header-cell-cushion,
        .fullcalendar-container th.fc-col-header-cell.fc-day-today .fc-col-header-cell-cushion,
        .fullcalendar-container .fc-scrollgrid-sync-table th.fc-day-today a {
          color: hsl(var(--primary-foreground)) !important;
          font-weight: 700 !important;
        }

        .fullcalendar-container .fc-timegrid-col.fc-day-today {
          background: hsl(var(--primary) / 0.05) !important;
        }

        .fullcalendar-container .fc-timegrid-slot,
        .fullcalendar-container .fc-timegrid-cols table,
        .fullcalendar-container .fc-timegrid-col,
        .fullcalendar-container .fc-timegrid-axis {
          border-color: hsl(var(--border)) !important;
        }

        .fullcalendar-container .fc-timegrid-slot-label-cushion,
        .fullcalendar-container .fc-timegrid-axis-cushion,
        .fullcalendar-container .fc-timegrid-allday-label {
          color: hsl(var(--muted-foreground)) !important;
          font-size: 0.75rem;
          font-weight: 600;
        }
        
        .fullcalendar-container .fc-popover {
          z-index: 9999 !important;
          max-height: 400px;
          background: hsl(var(--card)) !important;
          border: 1px solid hsl(var(--border)) !important;
          box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
          border-radius: 0.5rem;
        }

        .fullcalendar-container .fc-popover-header {
          background: hsl(var(--muted) / 0.5) !important;
          color: hsl(var(--foreground)) !important;
          padding: 0.5rem 0.75rem;
          border-bottom: 1px solid hsl(var(--border)) !important;
        }

        .fullcalendar-container .fc-popover-title {
          color: hsl(var(--foreground)) !important;
          font-weight: 600;
        }

        .fullcalendar-container .fc-popover-close {
          color: hsl(var(--muted-foreground)) !important;
        }
        
        .fullcalendar-container .fc-more-popover {
          z-index: 9999 !important;
          max-height: 400px;
        }
        
        .fullcalendar-container .fc-popover-body {
          max-height: 350px;
          overflow-y: auto;
          overflow-x: hidden;
          background: hsl(var(--card)) !important;
        }

        .fullcalendar-container .fc-timegrid-slot-label,
        .fullcalendar-container .fc-timegrid-axis-cushion {
          color: hsl(var(--muted-foreground));
          font-size: 0.75rem;
        }
        
        .fullcalendar-container .fc-timegrid-slot {
          border-bottom-color: hsl(var(--border) / 0.5) !important;
        }
        
        .fullcalendar-container .fc-daygrid-event-harness {
          margin-bottom: 2px;
        }
        
        .fullcalendar-container .fc-daygrid-body,
        .fullcalendar-container .fc-scrollgrid,
        .fullcalendar-container .fc-scrollgrid-section,
        .fullcalendar-container .fc-scroller {
          overflow: visible !important;
        }
        
        .fullcalendar-container .fc-popover-body::-webkit-scrollbar {
          width: 6px;
        }
        
        .fullcalendar-container .fc-popover-body::-webkit-scrollbar-track {
          background: hsl(var(--muted));
          border-radius: 3px;
        }
        
        .fullcalendar-container .fc-popover-body::-webkit-scrollbar-thumb {
          background: hsl(var(--muted-foreground) / 0.5);
          border-radius: 3px;
        }
        
        .fullcalendar-container .fc-popover-body::-webkit-scrollbar-thumb:hover {
          background: hsl(var(--muted-foreground));
        }
      `}</style>
    </div>
  )
}