import 'react-big-calendar/lib/addons/dragAndDrop/styles.css';
import 'react-big-calendar/lib/css/react-big-calendar.css';
import './collectionCalendar.css';

import {
    useMemo,
    useState,
} from 'react';

import {
    addDays,
    endOfDay,
    format,
    getDay,
    parse,
    startOfDay,
    startOfWeek,
} from 'date-fns';
import { enUS } from 'date-fns/locale/en-US';
import { ru } from 'date-fns/locale/ru';
import {
    Calendar,
    dateFnsLocalizer,
} from 'react-big-calendar';
import withDragAndDrop from 'react-big-calendar/lib/addons/dragAndDrop';

import { Lang } from '@/lang/Lang';

const DnDCalendar = withDragAndDrop(Calendar)
const locales = {
    en: enUS,
    ru,
};

const localizer = dateFnsLocalizer({
    format,
    parse,
    startOfWeek: (date: Date, culture?: string) =>
        startOfWeek(date, {
            weekStartsOn: 1,
            locale: locales[(culture as 'ru' | 'en') ?? 'en'],
        }),
    getDay,
    locales,
});

type CalendarEvent = {
    id: string;
    title: string;
    start: Date;
    end: Date;
    allDay?: boolean;
};

const CollectionCalendar = () => {
    const lang = Lang.getCurrentLang();

    const initialEvents: CalendarEvent[] = useMemo(() => {
        const now = new Date();
        const sow = startOfWeek(now, { weekStartsOn: 1, locale: locales[lang] });

        return [
            {
                id: 'evt-1',
                title: 'Тест: созвон (перетащи меня)',
                start: addDays(new Date(sow.setHours(10, 0, 0, 0)), 1),
                end: addDays(new Date(sow.setHours(11, 0, 0, 0)), 1),
            },
            {
                id: 'evt-2',
                title: 'Тест: дизайн-ревью',
                start: addDays(new Date(sow.setHours(14, 0, 0, 0)), 2),
                end: addDays(new Date(sow.setHours(15, 30, 0, 0)), 2),
            },
            {
                id: 'evt-3',
                title: 'Тест: all-day',
                start: startOfDay(addDays(sow, 4)),
                end: endOfDay(addDays(sow, 4)),
                allDay: true,
            },
        ];
    }, []);

    const [events, setEvents] = useState<CalendarEvent[]>(initialEvents);

    const messages = useMemo(() => {
        return {
            date: Lang.key('calendar_date'),
            time: Lang.key('calendar_time'),
            event: Lang.key('calendar_event'),
            allDay: Lang.key('calendar_all_day'),
            week: Lang.key('calendar_week'),
            work_week: Lang.key('calendar_work_week'),
            day: Lang.key('calendar_day'),
            month: Lang.key('calendar_month'),
            previous: Lang.key('calendar_previous'),
            next: Lang.key('calendar_next'),
            yesterday: Lang.key('calendar_yesterday'),
            tomorrow: Lang.key('calendar_tomorrow'),
            today: Lang.key('calendar_today'),
            agenda: Lang.key('calendar_agenda'),
            noEventsInRange: Lang.key('calendar_no_events_in_range'),
            showMore: (total: number) => `${Lang.key('calendar_show_more_prefix')} ${total}`,
        };
    }, [lang]);

    return (
        <div className="collection-calendar">
            <DnDCalendar
                style={{ height: 1000 }}
                localizer={localizer}
                events={events}
                culture={lang}
                messages={messages}
                views={['month', 'week', 'day']}
                defaultView="week"
                step={30}
                timeslots={1}
                resizable
                draggableAccessor={() => true}
                onEventDrop={({ event, start, end }) => {
                    const moved = event as CalendarEvent;
                    setEvents((prev) =>
                        prev.map((e) =>
                            e.id === moved.id
                                ? {
                                    ...e,
                                    start: start as Date,
                                    end: end as Date,
                                }
                                : e
                        )
                    );
                }}
                onEventResize={({ event, start, end }) => {
                    const resized = event as CalendarEvent;
                    setEvents((prev) =>
                        prev.map((e) =>
                            e.id === resized.id
                                ? {
                                    ...e,
                                    start: start as Date,
                                    end: end as Date,
                                }
                                : e
                        )
                    );
                }}
            />
        </div>
    )
}

export default CollectionCalendar;