import React, { useState, useEffect, Fragment } from 'react';
import { Accordion, Box, Text, Title } from '@mantine/core';
import { IconCheck, IconChevronDown } from '@tabler/icons-react';
import { useSelector, useDispatch } from 'react-redux';
import {
    fetchTasksByStatus,
    updateColumns,
    updateTaskStatus,
    completeTask,
    activateTask,
} from '../../../../Settings/store/taskSlice';
import { modals } from '@mantine/modals';
import { DragDropContext, Draggable, Droppable } from 'react-beautiful-dnd';
import TaskListStatusSectionItem from './TaskListStatusSectionItem';
import { notifications } from '@mantine/notifications';

const NO_STATUS_KEY = 'no-status';

const TaskListSectionByStatus = () => {
    const dispatch = useDispatch();
    const { loggedUserId } = useSelector(state => state.auth.user);
    const { loggedInUser } = useSelector(state => state.auth.session);
    const { projectInfo, projectStatuses, columns, filterValues, taskListSections } = useSelector(state => state.settings.task);
    const completeStatus = projectStatuses?.find(s => s.is_complete_status == 1);
    const regularSections = Object.values(taskListSections || {}).filter(s => s.mark_is_complete === 'regular');

    const userId = loggedInUser ? loggedInUser.loggedUserId : loggedUserId;
    const search = filterValues?.name || '';
    // Cross-dimension filters (excludes internal_status_id — 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,
        date_type:   filterValues?.date_type   || null,
    };

    // Build the full ordered list: dynamic statuses + static "No Status Assigned"
    const statusesWithNone = [
        ...projectStatuses,
        { id: NO_STATUS_KEY, name: 'No Status Assigned', slug: NO_STATUS_KEY, color_code: null },
    ];

    const [expandedItems, setExpandedItems] = useState([]);

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

        const allKeys = statusesWithNone.map(s => s.slug || NO_STATUS_KEY);
        setExpandedItems(allKeys);

        statusesWithNone.forEach(status => {
            dispatch(fetchTasksByStatus({
                projectId: projectInfo.id,
                statusId: status.id === NO_STATUS_KEY ? null : status.id,
                statusSlug: status.slug,
                limit: 10,
                offset: 0,
                append: false,
                userId,
                search,
                filterValues: filterParams,
            }));
        });
    }, [projectInfo?.id, projectStatuses.length, search,
        filterParams.assigned_to, filterParams.section_id,
        filterParams.priority_id, filterParams.date_type]);

    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;

        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);

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

            // Find the target status by slug
            const targetStatus = statusesWithNone.find(s => s.slug === destKey);

            const newStatusId = targetStatus && targetStatus.id !== NO_STATUS_KEY
                ? targetStatus.id
                : null;
            const newStatusName = targetStatus ? targetStatus.name : '';

            dispatch(updateTaskStatus({
                id: movedTask.id,
                data: {
                    status_id: newStatusId,
                    status_name: newStatusName,
                    updated_by: userId,
                },
            }));

            if (completeStatus && newStatusId === completeStatus.id) {
                // Dragged to the designated complete status → also complete the task
                dispatch(completeTask({
                    id: movedTask.id,
                    data: { project_id: projectInfo.id, type: 'task', updated_by: userId },
                }));
            } else if (movedTask.status === 'COMPLETED' && (!completeStatus || newStatusId !== completeStatus.id)) {
                // COMPLETED task dragged away from complete status → reopen with section picker
                modals.open({
                    title: <Title order={5}>Select Section</Title>,
                    centered: true,
                    withCloseButton: true,
                    children: (
                        <Fragment>
                            <Text size="sm" mb="md">Move this task to:</Text>
                            {regularSections.map(section => (
                                <Box
                                    key={section.id}
                                    className="cursor-pointer p-2 hover:bg-gray-100 rounded mb-1"
                                    onClick={() => {
                                        modals.closeAll();
                                        dispatch(activateTask({
                                            id: movedTask.id,
                                            data: { project_id: projectInfo.id, task_section_id: section.id, updated_by: userId },
                                        }));
                                    }}
                                >
                                    <Text size="sm">{section.name}</Text>
                                </Box>
                            ))}
                        </Fragment>
                    ),
                });
            }

            notifications.show({
                color: 'teal',
                title: 'Status 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-status-root" type="STATUS_SECTION" isDropDisabled={true}>
                        {(provided) => (
                            <div {...provided.droppableProps} ref={provided.innerRef}>
                                {statusesWithNone.map((status, index) => (
                                    <Draggable
                                        key={status.slug || NO_STATUS_KEY}
                                        draggableId={`status-section-${status.slug || NO_STATUS_KEY}`}
                                        index={index}
                                        isDragDisabled={true}
                                    >
                                        {(dragProvided, dragSnapshot) => (
                                            <TaskListStatusSectionItem
                                                status={status}
                                                columns={columns}
                                                projectInfo={projectInfo}
                                                provided={dragProvided}
                                                snapshot={dragSnapshot}
                                            />
                                        )}
                                    </Draggable>
                                ))}
                                {provided.placeholder}
                            </div>
                        )}
                    </Droppable>
                </DragDropContext>
            </Accordion>
        </Fragment>
    );
};

export default TaskListSectionByStatus;
