'use client';

import React, { useCallback, useEffect, useMemo, useState } from 'react';
import dayjs, { Dayjs } from 'dayjs';
import timezone from 'dayjs/plugin/timezone';
import utc from 'dayjs/plugin/utc';
import { Calendar, CalendarProps, dayjsLocalizer, View, Views } from 'react-big-calendar';

import 'react-big-calendar/lib/css/react-big-calendar.css';

import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { 
  Button, 
  Stack, 
  Typography, 
  useTheme,
  Dialog,
  DialogTitle,
  DialogContent,
  IconButton,
  Box,
  Chip,
  Card,
  CardContent,
  Divider,
} from '@mui/material';
import { DatePicker } from '@mui/x-date-pickers';
import CloseIcon from '@mui/icons-material/Close';
import AccessTimeIcon from '@mui/icons-material/AccessTime';
import PeopleIcon from '@mui/icons-material/People';
import EventIcon from '@mui/icons-material/Event';

dayjs.extend(utc);
dayjs.extend(timezone);

// Day.js Localizer
const localizer = dayjsLocalizer(dayjs);

type Event = {
  _id: string;
  id: number;
  title: string;
  start: Date;
  end: Date;
  eventUsersCount: number;
  eventName: string;
  eventSummary?: string;
  eventDate: string;
  startTime: string;
  endTime: string;
  organizerName?: string;
  address?: string;
  price?: number;
  numberOfSeats?: number;
  remainingSeats?: number;
  status?: 'pending' | 'in_progress' | 'completed';
};


const CalendarComponent = ({
  date,
  events,
  handleSelectSlot,
  handleNavigate,
  handleViewChange,
  currentView,
}: {
  date: Date;
  events: Event[];
  handleSelectSlot: ({ start, end }: { start: Date; end: Date }) => void;
  handleNavigate: (date: Date) => void;
  handleViewChange: (view: View) => void;
  currentView: View;
}) => {
  const [currentDate, setCurrentDate] = useState<Date>(date);
  const [myEvents, setEvents] = useState<Event[]>(events);
  // const [currentView, setCurrentView] = useState<View>('month');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [selectedDate, setSelectedDate] = useState<Dayjs | null | undefined>(dayjs(new Date()));
  const [selectedDayEvents, setSelectedDayEvents] = useState<Event[]>([]);
  const [dayEventsModalOpen, setDayEventsModalOpen] = useState(false);

  const theme = useTheme(); // Get the MUI theme
  const primaryColor = theme.palette.primary.main; // Access the primary color
  
  // Update events when props change
  useEffect(() => {
    setEvents(events);
  }, [events]);
  
  // Handle change of the selected date
  const handleDateChange = (date: Dayjs | null) => {
    setSelectedDate(date);
    if (date) {
      setCurrentDate(date.toDate());
    }
  };

  // const handleSelectSlot = useCallback(({ start, end }: { start: Date; end: Date }) => {
  //   const title = window.prompt('New Event Name');
  //   if (title) {
  //     setEvents((prev) => [...prev, { id: prev.length + 1, title, start, end }]);
  //   }
  // }, []);

  const handleDrillDown = useCallback((date: Date) => {
    // When drilling down to a specific date (clicking on "+X more")
    const dateStr = dayjs(date).format('YYYY-MM-DD');
    const eventsOnDate = myEvents.filter(e => 
      dayjs(e.start).format('YYYY-MM-DD') === dateStr
    );
    
    if (eventsOnDate.length > 0) {
      setSelectedDayEvents(eventsOnDate);
      setDayEventsModalOpen(true);
    }
  }, [myEvents]);

  const handleSelectEvent = useCallback((event: Event) => {
    // When an event is clicked, show all events for that day
    const eventDate = dayjs(event.start).format('YYYY-MM-DD');
    const eventsOnSameDay = myEvents.filter(e => 
      dayjs(e.start).format('YYYY-MM-DD') === eventDate
    );
    
    if (eventsOnSameDay.length > 1) {
      // If multiple events, show them in a modal
      setSelectedDayEvents(eventsOnSameDay);
      setDayEventsModalOpen(true);
    } else {
      // If single event, just show it (you can extend this to show event details)
      setSelectedDayEvents([event]);
      setDayEventsModalOpen(true);
    }
  }, [myEvents]);

  // const handleNavigate = useCallback((date: Date) => {
  //   setCurrentDate(date);
  // }, []);

  // const handleViewChange = useCallback((view: View) => {
  //   setCurrentView(view);
  //   if (view === 'month') {
  //     setCurrentDate(new Date()); // Reset to current month if month view is selected
  //   }
  // }, []);

  const handleYearChange = useCallback((yearChange: number) => {
    setCurrentDate((prev) => {
      const newDate = dayjs(prev).add(yearChange, 'year');
      return newDate.toDate();
    });
  }, []);

  const { defaultDate, scrollToTime } = useMemo(
    () => ({
      defaultDate: new Date(),
      scrollToTime: new Date(1970, 1, 1, 6),
    }),
    []
  );

  const eventStyleGetter = useCallback(
    (event: Event) => {
      // Apply the primary color to the event background
      let backgroundColor = primaryColor; // Default to primary color
      let textColor = theme.palette.mode === 'dark' ? '#fff' : '#000';

      if (event.title.toLowerCase().includes('project')) {
        backgroundColor = theme.palette.mode === 'dark' ? '#ad1457' : '#e91e63';
      } else if (event.title.toLowerCase().includes('meeting')) {
        backgroundColor = theme.palette.mode === 'dark' ? '#388e3c' : '#4caf50';
      }

      return {
        style: {
          backgroundColor,
          color: textColor,
        },
      };
    },
    [primaryColor, theme.palette.mode]
  );

  return (
    <>
      {/* Year Navigation */}
      {/* <div style={{ marginBottom: '1rem' }}>
        <button onClick={() => handleYearChange(-1)}>Previous Year</button>
        <span style={{ margin: '0 1rem' }}>{dayjs(currentDate).format('YYYY')}</span>
        <button onClick={() => handleYearChange(1)}>Next Year</button>
      </div> */}

      {/* View selection */}

      {/* Calendar */}
      <Calendar
        localizer={localizer}
        events={myEvents}
        date={date}
        onNavigate={handleNavigate}
        view={currentView} // Pass currentView to change calendar view
        onView={handleViewChange}
        defaultDate={defaultDate}
        scrollToTime={scrollToTime}
        onSelectEvent={handleSelectEvent}
        onSelectSlot={handleSelectSlot}
        onDrillDown={handleDrillDown}
        selectable
        style={{ height: 600 }}
        eventPropGetter={eventStyleGetter}
        popup // Enable popup for "+X more" links
        popupOffset={{ x: 0, y: 10 }} // Offset for popup positioning
      />

      {/* Day Events Modal */}
      <Dialog
        open={dayEventsModalOpen}
        onClose={() => setDayEventsModalOpen(false)}
        maxWidth="md"
        fullWidth
        PaperProps={{
          sx: {
            borderRadius: 4,
            boxShadow: theme.palette.mode === 'dark'
              ? '0 24px 48px rgba(0, 0, 0, 0.4)'
              : '0 24px 48px rgba(0, 0, 0, 0.15)',
          },
        }}
      >
        <DialogTitle
          sx={{
            background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
            color: 'white',
            py: 3,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
          }}
        >
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
            <EventIcon sx={{ fontSize: 32 }} />
            <Box>
              <Typography variant="h5" fontWeight={700}>
                Events on {selectedDayEvents.length > 0 && dayjs(selectedDayEvents[0].start).format('MMMM D, YYYY')}
              </Typography>
              <Typography variant="body2" sx={{ opacity: 0.9, mt: 0.5 }}>
                {selectedDayEvents.length} {selectedDayEvents.length === 1 ? 'event' : 'events'} scheduled
              </Typography>
            </Box>
          </Box>
          <IconButton
            onClick={() => setDayEventsModalOpen(false)}
            sx={{ color: 'white' }}
          >
            <CloseIcon />
          </IconButton>
        </DialogTitle>
        <DialogContent sx={{ p: 3, bgcolor: theme.palette.mode === 'dark' ? '#1a202c' : '#f8fafc' }}>
          <Stack spacing={2} sx={{ mt: 2 }}>
            {selectedDayEvents.map((event, index) => (
              <Card
                key={event._id || index}
                elevation={2}
                sx={{
                  borderRadius: 3,
                  transition: 'all 0.3s ease',
                  background: theme.palette.mode === 'dark'
                    ? 'linear-gradient(145deg, #2d3748 0%, #1a202c 100%)'
                    : 'linear-gradient(145deg, #ffffff 0%, #f8fafc 100%)',
                  border: theme.palette.mode === 'dark' ? '1px solid #4a5568' : '1px solid #e2e8f0',
                  '&:hover': {
                    transform: 'translateY(-2px)',
                    boxShadow: theme.palette.mode === 'dark'
                      ? '0 8px 24px rgba(0, 0, 0, 0.3)'
                      : '0 8px 24px rgba(0, 0, 0, 0.1)',
                  },
                }}
              >
                <CardContent sx={{ p: 3 }}>
                  <Stack direction="row" justifyContent="space-between" alignItems="start" mb={2}>
                    <Box>
                      <Typography variant="h6" fontWeight={700} color="text.primary" gutterBottom>
                        {event.eventName || event.title}
                      </Typography>
                      <Chip
                        label={dayjs(event.start).isAfter(dayjs()) ? 'Upcoming' : 'Past'}
                        color={dayjs(event.start).isAfter(dayjs()) ? 'success' : 'default'}
                        size="small"
                        sx={{ fontWeight: 600 }}
                      />
                    </Box>
                  </Stack>

                  {event.eventSummary && (
                    <Typography 
                      variant="body2" 
                      color="text.secondary" 
                      sx={{ mb: 2 }}
                    >
                      {event.eventSummary}
                    </Typography>
                  )}

                  <Divider sx={{ my: 2 }} />

                  <Stack spacing={1.5}>
                    <Stack direction="row" alignItems="center" spacing={1}>
                      <AccessTimeIcon sx={{ color: 'text.secondary', fontSize: 20 }} />
                      <Typography variant="body2" color="text.secondary">
                        {dayjs(event.start).format('hh:mm A')} - {dayjs(event.end).format('hh:mm A')}
                      </Typography>
                    </Stack>
                    
                    <Stack direction="row" alignItems="center" spacing={1}>
                      <PeopleIcon sx={{ color: 'text.secondary', fontSize: 20 }} />
                      <Typography variant="body2" color="text.secondary">
                        {event.eventUsersCount || 0} participants
                      </Typography>
                    </Stack>

                    {event.organizerName && (
                      <Typography variant="body2" color="text.secondary">
                        <strong>Organizer:</strong> {event.organizerName}
                      </Typography>
                    )}

                    {event.address && (
                      <Typography variant="body2" color="text.secondary">
                        <strong>Location:</strong> {event.address}
                      </Typography>
                    )}

                    {event.price !== undefined && (
                      <Typography variant="body2" color="text.secondary">
                        <strong>Price:</strong> {event.price === 0 ? 'Free' : `$${event.price}`}
                      </Typography>
                    )}
                  </Stack>
                </CardContent>
              </Card>
            ))}
          </Stack>
        </DialogContent>
      </Dialog>
    </>
  );
};

export default CalendarComponent;
