import React, { useState, useEffect, Fragment } from 'react';
import { Accordion } from '@mantine/core';
import { IconCheck, IconChevronDown } from '@tabler/icons-react';
import { useSelector, useDispatch } from 'react-redux';
import {
    fetchTasksByDueDate,
    updateColumns,
    updateTaskDueDate,
} from '../../../../Settings/store/taskSlice';
import { DragDropContext, Draggable, Droppable } from 'react-beautiful-dnd';
import TaskListDueDateSectionItem from './TaskListDueDateSectionItem';
import { notifications } from '@mantine/notifications';

// Ordered static sections — matches groupByDateLabels in Redux state
const DUE_DATE_SECTIONS = [
    { key: 'today', label: 'Today' },
    { key: 'next_seven_days', label: 'Next 7 Days' },
    { key: 'overdue', label: 'Overdue' },
    { key: 'upcoming', label: 'Upcoming' },
    { key: 'no-date', label: 'No Due Date Assigned' },
];

// What date to set when a task is dropped into each section
const getNewDateForSection = (sectionKey) => {
    const today = new Date();
    const pad = (n) => String(n).padStart(2, '0');
    const fmt = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;

    switch (sectionKey) {
        case 'today':
            return fmt(today);
        case 'next_seven_days': {
            const d = new Date(today); d.setDate(d.getDate() + 7); return fmt(d);
        }
        case 'upcoming': {
            const d = new Date(today); d.setDate(d.getDate() + 30); return fmt(d);
        }
        case 'no-date':
            return null;
        default:
            return null;
    }
};

const TaskListSectionByDueDate = () => {
    const dispatch = useDispatch();
    const { loggedUserId } = useSelector(state => state.auth.user);
    const { loggedInUser } = useSelector(state => state.auth.session);
    const { projectInfo, columns, filterValues } = useSelector(state => state.settings.task);

    const userId = loggedInUser ? loggedInUser.loggedUserId : loggedUserId;
    const search = filterValues?.name || '';
    // Cross-dimension filters (excludes date_type — that's the groupBy dimension here)
    const filterParams = {
        assigned_to:        filterValues?.assigned_to        || null,
        section_id:         filterValues?.section_id         || null,
        priority_id:        filterValues?.priority_id        || null,
        internal_status_id: filterValues?.internal_status_id || null,
    };

    const [expandedItems, setExpandedItems] = useState(DUE_DATE_SECTIONS.map(s => s.key));

    useEffect(() => {
        if (!projectInfo?.id) return;

        DUE_DATE_SECTIONS.forEach(section => {
            dispatch(fetchTasksByDueDate({
                projectId: projectInfo.id,
                dateType: section.key,
                limit: 10,
                offset: 0,
                append: false,
                userId,
                search,
                filterValues: filterParams,
            }));
        });
    }, [projectInfo?.id, search,
        filterParams.assigned_to, filterParams.section_id,
        filterParams.priority_id, filterParams.internal_status_id]);

    const onDragEnd = (result) => {
        if (!result.destination) return;
        const { source, destination } = result;

        if (source.droppableId === destination.droppableId && source.index === destination.index) return;

        const sourceKey = source.droppableId;
        const destKey = destination.droppableId;

        // Overdue is read-only — shouldn't receive drops (isDropDisabled handles it but belt-and-suspenders)
        if (destKey === 'overdue') return;

        const sourceTasks = [...(columns?.[sourceKey] || [])];
        const [movedTask] = sourceTasks.splice(source.index, 1);
        if (!movedTask) return;

        if (sourceKey !== destKey) {
            const destTasks = [...(columns?.[destKey] || [])];
            destTasks.splice(destination.index, 0, movedTask);

            dispatch(updateColumns({
                ...columns,
                [sourceKey]: sourceTasks,
                [destKey]: destTasks,
            }));

            const newDate = getNewDateForSection(destKey);

            dispatch(updateTaskDueDate({
                id: movedTask.id,
                data: {
                    end_date: newDate,
                    updated_by: userId,
                },
            }));

            notifications.show({
                color: 'teal',
                title: 'Due Date Updated',
                message: 'Tasks are ordered according to the main task list, the order you see here might not retain',
                icon: <IconCheck size={16} />,
                autoClose: 6000,
            });
        }
    };

    return (
        <Fragment>
            <Accordion
                variant="separated"
                multiple={true}
                value={expandedItems}
                onChange={setExpandedItems}
                chevron={<IconChevronDown size={30} stroke={2} />}
                classNames={{
                    control: '!w-[18px] !pl-0 !pr-2',
                    content: '!pb-0 !pt-0 !px-0',
                }}
                styles={{
                    panel: { overflow: 'visible' },
                    content: { overflow: 'visible' },
                }}
            >
                <DragDropContext onDragEnd={onDragEnd}>
                    <Droppable droppableId="section-by-duedate-root" type="DUEDATE_SECTION" isDropDisabled={true}>
                        {(provided) => (
                            <div {...provided.droppableProps} ref={provided.innerRef}>
                                {DUE_DATE_SECTIONS.map((section, index) => (
                                    <Draggable
                                        key={section.key}
                                        draggableId={`duedate-section-${section.key}`}
                                        index={index}
                                        isDragDisabled={true}
                                    >
                                        {(dragProvided, dragSnapshot) => (
                                            <TaskListDueDateSectionItem
                                                sectionKey={section.key}
                                                columns={columns}
                                                projectInfo={projectInfo}
                                                provided={dragProvided}
                                                snapshot={dragSnapshot}
                                            />
                                        )}
                                    </Draggable>
                                ))}
                                {provided.placeholder}
                            </div>
                        )}
                    </Droppable>
                </DragDropContext>
            </Accordion>
        </Fragment>
    );
};

export default TaskListSectionByDueDate;
