import { FC, useState } from 'react';
import { Calendar } from 'react-big-calendar';
import { CalendarEvent } from '../types/calendar';
import { localizer } from '../utils/calendar';
import { Button } from './Button';
import { Group } from './Group';
import { Stack } from './Stack';

type CarCalendarProp = {
  events: CalendarEvent[];
  defaultDate?: Date;
};

export const CarCalendar: FC<CarCalendarProp> = ({
  events,
  defaultDate = new Date(),
}) => {
  const [date, setDate] = useState(defaultDate);
  const handleNavigate = (action: string) => {
    switch (action) {
      case 'PREV':
        setDate(
          (prevDate) => new Date(prevDate.setMonth(prevDate.getMonth() - 1)),
        );
        break;
      case 'NEXT':
        setDate(
          (prevDate) => new Date(prevDate.setMonth(prevDate.getMonth() + 1)),
        );
        break;
      case 'TODAY':
        setDate(new Date());
        break;
      default:
        break;
    }
  };

  return (
    <Stack className="gap-2">
      <CustomToolbar
        onNavigate={handleNavigate}
        label={date.toLocaleDateString()}
      />
      <Calendar
        localizer={localizer}
        events={events}
        startAccessor="start"
        endAccessor="end"
        date={date}
        style={{ height: 300 }}
        eventPropGetter={(event) => ({
          style: { backgroundColor: event.color },
        })}
        views={['month']}
        toolbar={false}
      />
    </Stack>
  );
};

const CustomToolbar: React.FC<{
  onNavigate: (action: string) => void;
  label: string;
}> = ({ onNavigate, label }) => {
  return (
    <Group className="items-center justify-center gap-2">
      <button className="bg-white" onClick={() => onNavigate('PREV')}>
        <div className="i-ant-design-left-outlined" />
      </button>
      <span className="mt-0.8">{label}</span>
      <button className="bg-white" onClick={() => onNavigate('NEXT')}>
        <div className="i-ant-design-right-outlined" />
      </button>
      <Button className="bg-white text-xs" onClick={() => onNavigate('TODAY')}>
        Today
      </Button>
    </Group>
  );
};
