import React from 'react';
import { Accordion, Tooltip, Avatar, Loader, Flex, Badge } from '@mantine/core';
import { IconRefresh, IconCalendar, IconCalendarDue, IconAlertTriangle, IconCalendarStats, IconCalendarOff } from '@tabler/icons-react';
import { useDispatch, useSelector } from 'react-redux';
import { fetchTasksByDueDate } from '../../../../Settings/store/taskSlice';
import { Droppable, Draggable } from 'react-beautiful-dnd';
import TaskContent from '../Task/TaskContent';
import { translate } from '../../../../../utils/i18n';

const SECTION_META = {
    today: { label: 'Today', icon: IconCalendarDue, color: '#2563EB', badgeColor: 'blue', dropDisabled: false },
    next_seven_days: { label: 'Next 7 Days', icon: IconCalendarStats, color: '#16A34A', badgeColor: 'green', dropDisabled: false },
    overdue: { label: 'Overdue', icon: IconAlertTriangle, color: '#DC2626', badgeColor: 'red', dropDisabled: true },
    upcoming: { label: 'Upcoming', icon: IconCalendar, color: '#9333EA', badgeColor: 'grape', dropDisabled: false },
    'no-date': { label: 'No Due Date Assigned', icon: IconCalendarOff, color: '#6B7280', badgeColor: 'gray', dropDisabled: false },
};

const TaskListDueDateSectionItem = ({
    sectionKey,
    columns,
    projectInfo,
    provided,
    snapshot,
}) => {
    const dispatch = useDispatch();
    const { loggedUserId } = useSelector(state => state.auth.user);
    const { loggedInUser } = useSelector(state => state.auth.session);
    const { loadingDueDate } = useSelector(state => state.settings.task);

    const tasks = columns?.[sectionKey] || [];
    const isLoading = loadingDueDate?.[sectionKey] || false;
    const meta = SECTION_META[sectionKey] || { label: sectionKey, color: '#6B7280', badgeColor: 'gray', dropDisabled: false };
    const Icon = meta.icon;

    const userId = loggedInUser ? loggedInUser.loggedUserId : loggedUserId;

    const handleRefresh = () => {
        if (projectInfo?.id) {
            dispatch(fetchTasksByDueDate({
                projectId: projectInfo.id,
                dateType: sectionKey,
                limit: 14,
                offset: 0,
                append: false,
                userId,
            }));
        }
    };

    return (
        <Accordion.Item
            value={sectionKey}
            ref={provided.innerRef}
            className={`!border-solid !border-[#dddddd] !rounded-t-md accordion-item ${snapshot?.isDragging ? '!bg-[#EBF1F4] z-50' : '!bg-[#fcfcfc]'}`}
            {...provided.draggableProps}
            style={{ ...provided.draggableProps.style, boxShadow: 'none', transition: 'transform 0.1s ease' }}
        >
            <div
                className="flex items-center w-full border-b border-solid border-[#dddddd]"
                style={{ position: 'sticky', top: 0, zIndex: 10, backgroundColor: '#EBF1F4', width: '100%' }}
            >
                <div className="flex w-full items-center font-bold py-1 pr-3 !pl-3 gap-5">
                    <Accordion.Control />
                    {Icon && <Icon size={16} color={meta.color} />}
                    <span className="text-sm font-semibold" style={{ color: meta.color }}>
                        {translate(meta.label)}
                    </span>
                    <Badge size="sm" variant="light" color={meta.badgeColor} radius="sm">
                        {tasks.length}
                    </Badge>
                    {meta.dropDisabled && (
                        <span className="text-xs text-gray-400 italic">{translate('(read-only)')}</span>
                    )}
                </div>
                <div className="flex gap-2 mr-2">
                    <Tooltip withinPortal={false} label={translate('Refresh')} position="top" withArrow>
                        <Avatar className="cursor-pointer" onClick={handleRefresh} size={26} color="#ED7D31" variant="light">
                            <IconRefresh className="hover:scale-110" size={16} />
                        </Avatar>
                    </Tooltip>
                </div>
            </div>

            <Accordion.Panel>
                {isLoading ? (
                    <Flex justify="center" align="center" py="sm">
                        <Loader type="dots" size={24} />
                    </Flex>
                ) : (
                    <Droppable droppableId={sectionKey} type="DUEDATE_TASK" isDropDisabled={meta.dropDisabled}>
                        {(dropProvided, dropSnapshot) => (
                            <div
                                ref={dropProvided.innerRef}
                                {...dropProvided.droppableProps}
                                className={`w-full min-h-[40px] !px-[5px] ${dropSnapshot.isDraggingOver ? 'bg-blue-50' : meta.dropDisabled ? 'opacity-60' : ''}`}
                                style={{ transition: 'background-color 0.2s ease' }}
                            >
                                {tasks.length > 0 ? (
                                    tasks.map((task, index) => (
                                        task?.id && (
                                            <Draggable
                                                key={task.id}
                                                draggableId={`task-${task.id}`}
                                                index={index}
                                            >
                                                {(dragProvided, dragSnapshot) => (
                                                    <div
                                                        ref={dragProvided.innerRef}
                                                        {...dragProvided.draggableProps}
                                                        {...dragProvided.dragHandleProps}
                                                        className={`mb-0 mt-0 single-task ${dragSnapshot.isDragging ? 'z-50' : ''}`}
                                                        style={{
                                                            ...dragProvided.draggableProps.style,
                                                            backgroundColor: dragSnapshot.isDragging ? '#EBF1F4' : '#ffffff',
                                                            transition: 'all 0.1s ease-in-out',
                                                            cursor: dragSnapshot.isDragging ? 'grabbing' : 'grab',
                                                            opacity: dragSnapshot.isDragging ? 0.9 : 1,
                                                            transform: dragSnapshot.isDragging
                                                                ? `${dragProvided.draggableProps.style?.transform} rotate(-2deg) scale(1.02)`
                                                                : dragProvided.draggableProps.style?.transform,
                                                            boxShadow: dragSnapshot.isDragging ? '0 6px 12px rgba(0,0,0,0.15)' : 'none',
                                                            border: dragSnapshot.isDragging ? '1px solid #E5E5E5' : 'none',
                                                        }}
                                                    >
                                                        <TaskContent
                                                            view="listView"
                                                            taskSection={sectionKey}
                                                            taskData={task}
                                                        />
                                                    </div>
                                                )}
                                            </Draggable>
                                        )
                                    ))
                                ) : (
                                    <div className="text-center text-gray-400 py-3 text-sm">
                                        {translate('No tasks in this period')}
                                    </div>
                                )}
                                {dropProvided.placeholder}
                            </div>
                        )}
                    </Droppable>
                )}
            </Accordion.Panel>
        </Accordion.Item>
    );
};

export default TaskListDueDateSectionItem;
