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

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

    // Use slug as the key — matches fetchTasksByStatus.fulfilled reducer
    const statusKey = status.slug || 'no-status';
    const tasks = columns?.[statusKey] || [];
    const isLoading = loadingStatus?.[statusKey] || false;

    const userId = loggedInUser ? loggedInUser.loggedUserId : loggedUserId;

    const handleRefresh = () => {
        if (projectInfo?.id) {
            dispatch(fetchTasksByStatus({
                projectId: projectInfo.id,
                statusId: status.id === 'no-status' ? null : status.id,
                statusSlug: status.slug,
                limit: 14,
                offset: 0,
                append: false,
                userId,
            }));
        }
    };

    return (
        <Accordion.Item
            value={statusKey}
            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',
            }}
        >
            {/* Sticky section header — matches default list section style */}
            <div
                className="flex items-center w-full border-b border-solid border-[#dddddd] !bg-[#EBF1F4]"
                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 />
                    {/* Status colour dot */}
                    {status.color_code && status.id !== 'no-status' && (
                        <div
                            className="w-2.5 h-2.5 rounded-full flex-shrink-0"
                            style={{ backgroundColor: status.color_code }}
                        />
                    )}
                    <span className="text-sm font-semibold text-[#333]">
                        {translate(status.name)}
                    </span>
                    <Badge
                        size="sm"
                        variant="light"
                        color={status.id === 'no-status' ? 'gray' : '#39758D'}
                        radius="sm"
                    >
                        {tasks.length}
                    </Badge>
                </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={statusKey} type="STATUS_TASK">
                        {(dropProvided, dropSnapshot) => (
                            <div
                                ref={dropProvided.innerRef}
                                {...dropProvided.droppableProps}
                                className={`w-full min-h-[40px] !px-[5px] ${dropSnapshot.isDraggingOver ? 'bg-blue-50' : ''}`}
                                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={statusKey}
                                                            taskData={task}
                                                        />
                                                    </div>
                                                )}
                                            </Draggable>
                                        )
                                    ))
                                ) : (
                                    <div className="text-center text-gray-400 py-3 text-sm">
                                        {translate('No tasks with this status')}
                                    </div>
                                )}
                                {dropProvided.placeholder}
                            </div>
                        )}
                    </Droppable>
                )}
            </Accordion.Panel>
        </Accordion.Item>
    );
};

export default TaskListStatusSectionItem;
