import React, { useState, useCallback, useEffect, useRef } from 'react';
import { IconArrowsExchange, IconDotsVertical, IconEye, IconArchive, IconSquareCheck, IconSquareX, IconLock, IconLockOpen, IconCopy, IconCheck, IconCircleX, IconCirclePlus, IconCircleMinus, IconX, IconPlaylistX, IconStopwatch } from '@tabler/icons-react';
import { useSelector, useDispatch } from 'react-redux';
import { hasPermission, useProjectPermissions } from "../../../../ui/permissions";
import { Text, Menu, Group, ThemeIcon, Divider, Popover, List, ScrollArea, Flex } from "@mantine/core";
import { modals } from "@mantine/modals";
import TaskDelete from "./TaskDelete";
import { showNotification, updateNotification } from "@mantine/notifications";
import ChangeTaskSection from "./ChangeTaskSection";
import {
    convertTask,
    archiveTask,
    completeTask,
    openTaskEditDrawer, setEditableTask, closeTaskEditDrawer, changeTaskVisibility, duplicateTask,
    inCompleteTask,
    activateTask,
    markAsCloseTask,
    editTask,
    updateTaskStatus,
} from "../../../../Settings/store/taskSlice";
import { fetchProjectTaskSections } from "../../../../Settings/store/projectSlice";
import { translate } from '../../../../../utils/i18n';
import { addTask, removeTask } from '../../../../../services/TaskService';

const T = {
    border:   '#E2E8F0',
    text:     '#1A202C',
    icon:     '#6B7280',
    teal:     '#39758D',
    radius:   '12px',
};

const menuStyles = {
    dropdown: {
        padding: 0,
        border: `1px solid ${T.border}`,
        borderRadius: T.radius,
        boxShadow: '0 8px 32px rgba(0,0,0,.12)',
        overflow: 'hidden',
        '--menu-item-hover': '#EBF1F4',
    },
    item: {
        borderRadius: 0,
        fontSize: '12px',
        color: T.text,
        padding: '7px 12px',
    },
    label: {
        padding: '10px 14px 8px',
        borderBottom: `1px solid ${T.border}`,
        fontSize: '12px',
        fontWeight: 700,
        color: T.text,
        marginBottom: 0,
    },
    divider: {
        borderColor: T.border,
        margin: 0,
    },
};

const TaskActionsMenu = ({ actions = [], taskData, isSubtask, isDrawer, currentSectionSlug }) => {
    const dispatch = useDispatch();
    const { loggedInUser } = useSelector((state) => state.auth.session);
    const { loggedUserId } = useSelector((state) => state.auth.user);
    const { projectInfo, taskListSections, projectStatuses, childColumns } = useSelector((state) => state.settings.task);
    const { projectSections } = useSelector((state) => state.settings.project);
    const projectPermissions = useProjectPermissions(projectInfo?.id);
    const completeStatus = projectStatuses?.find(s => s.is_complete_status == 1);
    const subtasks = childColumns?.[taskData.slug] || [];
    const [opened, setOpened] = useState(false);
    const [incompleteMenuOpened, setIncompleteMenuOpened] = useState(false);
    const fetchedProjectSectionsRef = useRef(null);

    const openPopover = useCallback(() => setOpened(true), []);
    const closePopover = useCallback(() => setOpened(false), []);

    useEffect(() => {
        if (!opened) {
            setIncompleteMenuOpened(false);
        }
    }, [opened]);

    useEffect(() => {
        const shouldFetchSections =
            opened &&
            !isSubtask &&
            actions.includes('complete') &&
            taskData?.project_id &&
            fetchedProjectSectionsRef.current !== taskData.project_id;

        if (shouldFetchSections) {
            dispatch(fetchProjectTaskSections(taskData.project_id));
            fetchedProjectSectionsRef.current = taskData.project_id;
        }
    }, [opened, isSubtask, actions, taskData?.project_id, dispatch]);

    const regularSections = (projectSections || []).filter(
        (section) => section?.mark_is_complete === 'regular'
    );
    const currentSection = currentSectionSlug
        ? taskListSections?.[currentSectionSlug]
        : taskListSections?.[taskData?.section_slug];
    const isCompleted = currentSection
        ? currentSection?.mark_is_complete === 'complete'
        : taskData?.status === 'COMPLETED';
    const hasRegularSections = regularSections.length > 0;

    // const [task, setTask] = useState(taskData);

    // useEffect(() => { setTask(taskData); }, [taskData]);

    const handleEditTaskDrawerOpen = () => {
        closePopover();
        dispatch(openTaskEditDrawer());
        dispatch(setEditableTask(taskData && taskData));
    };
    const handleEditSubTaskDrawerOpen = () => {
        closePopover();
        dispatch(openTaskEditDrawer());
        dispatch(setEditableTask(taskData && taskData));
    };

    const [selectedAccordion, setSelectedAccordion] = useState('');
    const toggleSection = (section) => {
        setSelectedAccordion(section);
    };

    const archiveTaskHandler = () => {
        const taskSectionId = taskData?.task_section_id;
        const taskId = taskData?.id;
        showNotification({
            id: 'load-data',
            loading: true,
            title: 'Task',
            message: "Archiving The Task...",
            disallowClose: true,
            color: 'green',
            styles: () => ({
                root: {
                    zIndex: 3000,
                },
            }),
        });
        dispatch(archiveTask({
            id: taskSectionId,
            data: {
                project_id: null,
                task_id: taskId,
                updated_by: loggedInUser?.loggedUserId ?? loggedUserId,
            }
        }))
            .then((response) => {
                if (response.payload && response.payload.status && response.payload.status === 200) {
                    if (isDrawer) {
                        dispatch(closeTaskEditDrawer())
                    }
                    updateNotification({
                        id: 'load-data',
                        loading: true,
                        title: 'Task',
                        message: response.payload && response.payload.message && response.payload.message,
                        autoClose: 2000,
                        disallowClose: true,
                        color: 'green',
                    });
                }
            })
            .catch((error) => {
                console.error('Error archiving task:', error);
                alert('Failed to archive task.');

            });
    };

    const handleCompleteTask = () => {
        closePopover();
        modals.openConfirmModal({
            title: (
                <>
                    <Group spacing="xs">
                        <ThemeIcon color="orange" radius="xl" size="lg" variant="filled">
                            <IconCheck size={24} />
                        </ThemeIcon>
                        <Text size="md" weight={500}>
                            {translate('Mark as Complete')}
                        </Text>
                    </Group>
                </>
            ),
            centered: true,
            children: (
                <>
                    <Divider size="xs" mb={24} className='!-ml-4 w-[calc(100%+2rem)]' />
                    <Text size="md" mb={30}>
                        Are you sure you want to complete this task?
                        {completeStatus && subtasks.length > 0 && (
                            <><br /><br />All {subtasks.length} subtask(s) will also be marked as complete.</>
                        )}
                    </Text>
                </>
            ),
            labels: { confirm: 'Yes, complete it', cancel: 'cancel' },
            confirmProps: { color: 'orange' },
            onConfirm: () => {
                showNotification({
                    id: 'load-data',
                    loading: true,
                    title: 'Task',
                    message: "Completing The Task...",
                    disallowClose: true,
                    color: 'green',
                    styles: () => ({
                        root: {
                            zIndex: 3000,
                        },
                    }),
                });
                dispatch(completeTask({
                    id: taskData.id,
                    data: {
                        project_id: taskData.project_id,
                        type: 'task',
                        updated_by: loggedInUser?.loggedUserId ?? loggedUserId,
                    }
                }))
                    .then((response) => {
                        if (response.payload && response.payload.status && response.payload.status === 200) {
                            if (isDrawer) {
                                dispatch(closeTaskEditDrawer())
                            }
                            // Sync internal_status to the designated complete status if one is set
                            if (completeStatus) {
                                const userId = loggedInUser?.loggedUserId ?? loggedUserId;
                                dispatch(updateTaskStatus({
                                    id: taskData.id,
                                    data: { status_id: completeStatus.id, updated_by: userId },
                                }));
                                subtasks.forEach(subtask => {
                                    dispatch(updateTaskStatus({ id: subtask.id, data: { status_id: completeStatus.id, updated_by: userId } }));
                                });
                            }
                            updateNotification({
                                id: 'load-data',
                                loading: true,
                                title: 'Task',
                                message: response.payload && response.payload.message && response.payload.message,
                                autoClose: 2000,
                                disallowClose: true,
                                color: 'green',
                            });
                        } else {
                            updateNotification({
                                id: 'load-data',
                                loading: false,
                                title: 'Task',
                                message: response.payload && response.payload.message && response.payload.message,
                                autoClose: 2000,
                                disallowClose: true,
                                color: 'red',
                            });
                        }
                    })
                    .catch((error) => {
                        console.error('Error completing task:', error);
                        alert('Failed to mark as complete task.');
                    });
            },
        });
    }

    const handleConvertTask = () => {
        closePopover();
        modals.openConfirmModal({
            title: 'Convert Task',
            centered: true,
            children: (
                <Text size="sm">
                    Are you sure you want to convert this subtask as task?
                </Text>
            ),
            labels: { confirm: 'Yes, convert it', cancel: 'cancel' },
            confirmProps: { color: 'orange' },
            onConfirm: () => {
                showNotification({
                    id: 'load-data',
                    loading: true,
                    title: 'Task',
                    message: "Converting The Subtask...",
                    disallowClose: true,
                    color: 'green',
                    styles: () => ({
                        root: {
                            zIndex: 3000,
                        },
                    }),
                });
                dispatch(convertTask({
                    id: taskData.id,
                    data: {
                        updated_by: loggedInUser?.loggedUserId ?? loggedUserId,
                    }
                }))
                    .then((response) => {
                        if (response.payload && response.payload.status && response.payload.status === 200) {
                            if (isDrawer) {
                                dispatch(closeTaskEditDrawer())
                            }
                            updateNotification({
                                id: 'load-data',
                                loading: false,
                                title: 'Task',
                                message: response.payload && response.payload.message && response.payload.message,
                                autoClose: 2000,
                                disallowClose: true,
                                color: 'green',
                            });
                        } else {
                            updateNotification({
                                id: 'load-data',
                                loading: false,
                                title: 'Task',
                                message: response.payload && response.payload.message && response.payload.message,
                                autoClose: 2000,
                                disallowClose: true,
                                color: 'red',
                            });
                        }
                    })
                    .catch((error) => {
                        console.error('Error converting task:', error);
                        alert('Failed to convert task.');
                    });
            },
        });
    }

    const changeVisibilityHandler = () => {
        closePopover();
        modals.openConfirmModal({
            title: (
                <Group spacing="xs">
                    <ThemeIcon color="orange" radius="xl" size="lg" variant="filled">
                        {taskData.taskPrivacy === 'public' ?
                            <IconLock size={24} /> :
                            <IconLockOpen size={24} />
                        }
                    </ThemeIcon>
                    <Text size="md" weight={500}>
                        {translate('Change Task Visibility')}
                    </Text>
                </Group>
            ),
            centered: true,
            children: (
                <>
                    <Divider size="xs" mb={14} className='!-ml-4 w-[calc(100%+2rem)]' />
                    <Text size="md" mb={30}>
                        Are you sure you want to change task visibility?
                    </Text>
                </>
            ),
            labels: { confirm: translate('Yes'), cancel: translate('Cancel') },
            confirmProps: { color: 'orange' },
            onConfirm: () => {
                showNotification({
                    id: 'load-data',
                    loading: true,
                    title: 'Task',
                    message: "Changing Visibility...",
                    disallowClose: true,
                    color: 'green',
                    styles: () => ({
                        root: {
                            zIndex: 3000,
                        },
                    }),
                });
                dispatch(changeTaskVisibility({
                    id: taskData.id,
                    data: {
                        taskPrivacy: taskData.taskPrivacy === 'public' ? 'private' : 'public',
                        updated_by: loggedInUser?.loggedUserId ?? loggedUserId,
                    }
                }))
                    .then((response) => {
                        if (response.payload && response.payload.status && response.payload.status === 200) {
                            if (isDrawer) {
                                dispatch(closeTaskEditDrawer())
                            }
                            updateNotification({
                                id: 'load-data',
                                loading: false,
                                title: 'Task',
                                message: response.payload && response.payload.message && response.payload.message,
                                autoClose: 2000,
                                disallowClose: true,
                                color: 'green',
                            });
                        } else {
                            updateNotification({
                                id: 'load-data',
                                loading: false,
                                title: 'Task',
                                message: response.payload && response.payload.message && response.payload.message,
                                autoClose: 2000,
                                disallowClose: true,
                                color: 'red',
                            });
                        }
                    })
                    .catch((error) => {
                        console.error('Error changing visibility task:', error);
                        alert('Failed to changing visibility task.');
                    });
            },
        });
    };

    const duplicateTaskHandler = () => {
        closePopover();
        modals.openConfirmModal({
            title: (
                <Group spacing="xs">
                    <ThemeIcon color="orange" radius="xl" size="lg" variant="filled">
                        <IconCopy size={24} />
                    </ThemeIcon>
                    <Text size="md" weight={500}>
                        {translate('Duplicate Task')}
                    </Text>
                </Group>
            ),
            centered: true,
            children: (
                <>
                    <Divider size="xs" mb={14} className='!-ml-4 w-[calc(100%+2rem)]' />
                    <Text size="md" mb={30}>
                        Are you sure you want to duplicate the task?
                    </Text>
                </>
            ),
            labels: { confirm: translate('Yes'), cancel: translate('Cancel') },
            confirmProps: { color: 'orange' },
            onConfirm: () => {
                showNotification({
                    id: 'load-data',
                    loading: true,
                    title: 'Task',
                    message: "Duplicating the task...",
                    disallowClose: true,
                    color: 'green',
                    styles: () => ({
                        root: {
                            zIndex: 3000,
                        },
                    }),
                });
                dispatch(duplicateTask({
                    id: taskData.id,
                    data: {
                        created_by: loggedInUser?.loggedUserId ?? loggedUserId,
                    }
                }))
                    .then((response) => {
                        if (response.payload && response.payload.status && response.payload.status === 200) {
                            if (isDrawer) {
                                dispatch(closeTaskEditDrawer())
                            }
                            updateNotification({
                                id: 'load-data',
                                loading: false,
                                title: 'Task',
                                message: response.payload && response.payload.message && response.payload.message,
                                autoClose: 2000,
                                disallowClose: true,
                                color: 'green',
                            });
                        } else {
                            updateNotification({
                                id: 'load-data',
                                loading: false,
                                title: 'Task',
                                message: response.payload && response.payload.message && response.payload.message,
                                autoClose: 2000,
                                disallowClose: true,
                                color: 'red',
                            });
                        }
                    })
                    .catch((error) => {
                        console.error('Error changing visibility task:', error);
                        alert('Failed to changing visibility task.');
                    });
            },
        });
    };

    const handleCompleteSubTask = () => {
        closePopover();
        modals.openConfirmModal({
            title: (
                <Group spacing="xs">
                    <ThemeIcon color="orange" radius="xl" size="lg" variant="filled">
                        <IconCheck size={24} />
                    </ThemeIcon>
                    <Text size="md" weight={500}>
                        {translate('Complete Subtask')}
                    </Text>
                </Group>
            ),
            centered: true,
            children: (
                <>
                    <Divider size="xs" mb={24} className='!-ml-4 w-[calc(100%+2rem)]' />
                    <Text size="md" mb={30}>
                        {translate('Are you sure you want to complete this subtask?')}
                    </Text>
                </>
            ),
            labels: { confirm: 'Yes, complete it', cancel: 'cancel' },
            confirmProps: { color: 'orange' },
            onConfirm: () => {
                showNotification({
                    id: 'load-data',
                    loading: true,
                    title: 'Subtask',
                    message: "Completing The Subtask...",
                    disallowClose: true,
                    color: 'green',
                    styles: () => ({
                        root: {
                            zIndex: 3000,
                        },
                    }),
                });
                dispatch(completeTask({
                    id: taskData.id,
                    data: {
                        project_id: taskData.project_id,
                        type: 'subtask',
                        updated_by: loggedInUser?.loggedUserId ?? loggedUserId,
                    }
                }))
                    .then((response) => {
                        if (response.payload && response.payload.status && response.payload.status === 200) {
                            if (isDrawer) {
                                dispatch(closeTaskEditDrawer())
                            }
                            updateNotification({
                                id: 'load-data',
                                loading: true,
                                title: 'Subtask',
                                message: response.payload && response.payload.message && response.payload.message,
                                autoClose: 2000,
                                disallowClose: true,
                                color: 'green',
                            });
                        } else {
                            updateNotification({
                                id: 'load-data',
                                loading: false,
                                title: 'Subtask',
                                message: response.payload && response.payload.message && response.payload.message,
                                autoClose: 2000,
                                disallowClose: true,
                                color: 'red',
                            });
                        }
                    })
                    .catch((error) => {
                        console.error('Error completing subtask:', error);
                        alert('Failed to complete subtask.');
                    });
            },
        });
    }

    const handleInCompleteSubTask = () => {
        closePopover();
        modals.openConfirmModal({
            title: (
                <Group spacing="xs">
                    <ThemeIcon color="orange" radius="xl" size="lg" variant="filled">
                        <IconCircleX size={24} />
                    </ThemeIcon>
                    <Text size="md" weight={500}>
                        {translate('Incomplete Subtask')}
                    </Text>
                </Group>
            ),
            centered: true,
            children: (
                <>
                    <Divider size="xs" mb={24} className='!-ml-4 w-[calc(100%+2rem)]' />
                    <Text size="md" mb={30}>
                        {translate('Are you sure you want to incomplete this subtask?')}
                    </Text>
                </>
            ),
            labels: { confirm: 'Yes', cancel: 'Cancel' },
            confirmProps: { color: 'orange' },
            onConfirm: () => {
                showNotification({
                    id: 'load-data',
                    loading: true,
                    title: 'Subtask',
                    message: "Incompleting The Subtask...",
                    disallowClose: true,
                    color: 'green',
                    styles: () => ({
                        root: {
                            zIndex: 3000,
                        },
                    }),
                });
                dispatch(inCompleteTask({
                    id: taskData.id,
                    data: {
                        project_id: taskData.project_id,
                        type: 'subtask',
                        updated_by: loggedInUser?.loggedUserId ?? loggedUserId,
                    }
                }))
                    .then((response) => {
                        if (response.payload && response.payload.status && response.payload.status === 200) {
                            if (isDrawer) {
                                dispatch(closeTaskEditDrawer())
                            }
                            updateNotification({
                                id: 'load-data',
                                loading: true,
                                title: 'Subtask',
                                message: response.payload && response.payload.message && response.payload.message,
                                autoClose: 2000,
                                disallowClose: true,
                                color: 'green',
                            });
                        } else {
                            updateNotification({
                                id: 'load-data',
                                loading: false,
                                title: 'Subtask',
                                message: response.payload && response.payload.message && response.payload.message,
                                autoClose: 2000,
                                disallowClose: true,
                                color: 'red',
                            });
                        }
                    })
                    .catch((error) => {
                        console.error('Error completing subtask:', error);
                    });
            },
        });
    }

    const handleInCompleteTask = (sectionId) => {
        closePopover();
        setIncompleteMenuOpened(false);
        modals.openConfirmModal({
            title: (
                <Group spacing="xs">
                    <ThemeIcon color="orange" radius="xl" size="lg" variant="filled">
                        <IconSquareX size={24} />
                    </ThemeIcon>
                    <Text size="md" weight={500}>
                        {translate('Mark as Incomplete')}
                    </Text>
                </Group>
            ),
            centered: true,
            children: (
                <>
                    <Divider size="xs" mb={24} className='!-ml-4 w-[calc(100%+2rem)]' />
                    <Text size="md" mb={30}>
                        Are you sure you want to mark this task as incomplete and move it to {regularSections.find(s => s.id === sectionId)?.name}?
                        {subtasks.length > 0 && (
                            <><br /><br />All {subtasks.length} subtask(s) will also be re-opened.</>
                        )}
                    </Text>
                </>
            ),
            labels: { confirm: 'Yes, activate it', cancel: 'cancel' },
            confirmProps: { color: 'orange' },
            onConfirm: () => {
                showNotification({
                    id: 'load-data',
                    loading: true,
                    title: 'Task',
                    message: "Marking task as incomplete...",
                    disallowClose: true,
                    color: 'green',
                    styles: () => ({
                        root: {
                            zIndex: 3000,
                        },
                    }),
                });
                dispatch(activateTask({
                    id: taskData.id,
                    data: {
                        project_id: taskData.project_id,
                        task_section_id: sectionId,
                        updated_by: loggedInUser?.loggedUserId ?? loggedUserId,
                    }
                }))
                    .then((response) => {
                        if (response.payload && response.payload.status && response.payload.status === 200) {
                            if (isDrawer) {
                                dispatch(closeTaskEditDrawer())
                            }
                            // Clear internal_status when reopening a task, cascade to loaded subtasks
                            const userId = loggedInUser?.loggedUserId ?? loggedUserId;
                            dispatch(updateTaskStatus({
                                id: taskData.id,
                                data: { status_id: null, updated_by: userId },
                            }));
                            subtasks.forEach(subtask => {
                                dispatch(updateTaskStatus({ id: subtask.id, data: { status_id: null, updated_by: userId } }));
                            });
                            updateNotification({
                                id: 'load-data',
                                loading: true,
                                title: 'Task',
                                message: response.payload && response.payload.message && response.payload.message,
                                autoClose: 2000,
                                disallowClose: true,
                                color: 'green',
                            });
                        } else {
                            updateNotification({
                                id: 'load-data',
                                loading: false,
                                title: 'Task',
                                message: response.payload && response.payload.message && response.payload.message,
                                autoClose: 2000,
                                disallowClose: true,
                                color: 'red',
                            });
                        }
                    })
                    .catch((error) => {
                        console.error('Error marking task as incomplete:', error);
                        alert('Failed to mark task as incomplete.');
                    });
            },
        });
    };

    const handleMarkAsClose = () => {
        closePopover();
        modals.openConfirmModal({
            title: (
                <Group spacing="xs">
                    <ThemeIcon color="orange" radius="xl" size="lg" variant="filled">
                        <IconX size={24} />
                    </ThemeIcon>
                    <Text size="md" weight={500}>
                        {translate('Mark as Close')}
                    </Text>
                </Group>
            ),
            centered: true,
            children: (
                <>
                    <Divider size="xs" mb={24} className='!-ml-4 w-[calc(100%+2rem)]' />
                    <Text size="md" mb={30}>
                        Are you sure you want to mark this task as closed? It will be removed from the completed section.
                    </Text>
                </>
            ),
            labels: { confirm: 'Yes, close it', cancel: 'cancel' },
            confirmProps: { color: 'orange' },
            onConfirm: () => {
                showNotification({
                    id: 'load-data',
                    loading: true,
                    title: 'Task',
                    message: "Marking The Task as Closed...",
                    disallowClose: true,
                    color: 'blue',
                    styles: () => ({
                        root: {
                            zIndex: 3000,
                        },
                    }),
                });
                dispatch(markAsCloseTask({
                    id: taskData.id,
                    data: {
                        project_id: taskData.project_id,
                        updated_by: loggedInUser?.loggedUserId ?? loggedUserId,
                    }
                }))
                    .then((response) => {
                        if (response.payload && response.payload.status && response.payload.status === 200) {
                            if (isDrawer) {
                                dispatch(closeTaskEditDrawer())
                            }
                            updateNotification({
                                id: 'load-data',
                                loading: true,
                                title: 'Task',
                                message: response.payload && response.payload.message && response.payload.message,
                                autoClose: 2000,
                                disallowClose: true,
                                color: 'blue',
                            });
                        } else {
                            updateNotification({
                                id: 'load-data',
                                loading: false,
                                title: 'Task',
                                message: response.payload?.message || 'An error occurred. Please try again.',
                                autoClose: 2000,
                                disallowClose: true,
                                color: 'red',
                            });
                        }
                    })
                    .catch(error => {
                        console.error('Error marking task as closed:', error);
                        updateNotification({
                            id: 'load-data',
                            loading: false,
                            title: 'Task',
                            message: (error && error.message) ? error.message : 'Failed to mark task as closed. Please try again.',
                            autoClose: 2000,
                            disallowClose: true,
                            color: 'red',
                        });
                    });
            },
        });
    };

    const addTaskToGanttHandler = () => {
        if (!taskData.start_date && !taskData.end_date) {
            showNotification({
                color: 'red',
                title: translate('Date Required'),
                message: translate('Set at least a start or end date before adding to Gantt.'),
                icon: <IconCircleX size={18} />,
            });
            return;
        }
        modals.openConfirmModal({
            title: (
                <Group spacing="xs">
                    <ThemeIcon color="orange" radius="xl" size="lg" variant="filled">
                        <IconCirclePlus size={24} />
                    </ThemeIcon>
                    <Text size="md" weight={500}>
                        {translate('Add Task to Gantt Chart')}
                    </Text>
                </Group>
            ),
            centered: true,
            children: (
                <>
                    <Divider size="xs" mb={14} className='!-ml-4 w-[calc(100%+2rem)]' />
                    <Text size="md" mb={30}>
                        {translate('Are you sure you want to Add Task to Gantt Chart ?')}
                    </Text>
                </>
            ),
            labels: { confirm: translate('Yes'), cancel: translate('Cancel') },
            confirmProps: { color: 'orange' },
            onConfirm: () => {
                showNotification({
                    id: 'load-data',
                    loading: true,
                    title: 'Task',
                    message: "Adding Task to Gantt...",
                    disallowClose: true,
                    color: 'green',
                    styles: () => ({
                        root: {
                            zIndex: 3000,
                        },
                    }),
                });
                const updatedTask = {
                    is_visible: 1
                }
                dispatch(editTask({
                    id: taskData.id,
                    data: updatedTask
                }))
                    .then((response) => {
                        if (response.payload && response.payload.status && response.payload.status === 200) {
                            if (isDrawer) {
                                dispatch(closeTaskEditDrawer())
                            }
                            updateNotification({
                                id: 'load-data',
                                loading: false,
                                title: 'Task',
                                message: response.payload && response.payload.message && response.payload.message,
                                autoClose: 2000,
                                disallowClose: true,
                                color: 'green',
                            });
                        } else {
                            updateNotification({
                                id: 'load-data',
                                loading: false,
                                title: 'Task',
                                message: response.payload && response.payload.message && response.payload.message,
                                autoClose: 2000,
                                disallowClose: true,
                                color: 'red',
                            });
                        }
                    })
                    .catch((error) => {
                        console.error('Error adding task on gantt:', error);
                        alert('Failed to Add Task to Gantt Chart.');
                    });
            },
        });

    }

    const removeTaskFromGanttHandler = () => {
        modals.openConfirmModal({
            title: (
                <Group spacing="xs">
                    <ThemeIcon color="orange" radius="xl" size="lg" variant="filled">
                        <IconCircleMinus size={24} />
                    </ThemeIcon>
                    <Text size="md" weight={500}>
                        {translate('Remove Task From Gantt Chart')}
                    </Text>
                </Group>
            ),
            centered: true,
            children: (
                <>
                    <Divider size="xs" mb={14} className='!-ml-4 w-[calc(100%+2rem)]' />
                    <Text size="md" mb={30}>
                        {translate('Are you sure you want to remove task from gantt chart ?')}
                    </Text>
                </>
            ),
            labels: { confirm: translate('Yes'), cancel: translate('Cancel') },
            confirmProps: { color: 'orange' },
            onConfirm: () => {
                showNotification({
                    id: 'load-data',
                    loading: true,
                    title: 'Task',
                    message: "Removing Task From Gantt...",
                    disallowClose: true,
                    color: 'green',
                });
                const updatedTask = {
                    is_visible: 0
                }
                dispatch(editTask({
                    id: taskData.id,
                    data: updatedTask
                }))
                    .then((response) => {
                        if (response.payload && response.payload.status && response.payload.status === 200) {
                            if (isDrawer) {
                                dispatch(closeTaskEditDrawer())
                            }
                            updateNotification({
                                id: 'load-data',
                                loading: false,
                                title: 'Task',
                                message: response.payload && response.payload.message && response.payload.message,
                                autoClose: 2000,
                                disallowClose: true,
                                color: 'green',
                            });
                        } else {
                            updateNotification({
                                id: 'load-data',
                                loading: false,
                                title: 'Task',
                                message: response.payload && response.payload.message && response.payload.message,
                                autoClose: 2000,
                                disallowClose: true,
                                color: 'red',
                            });
                        }
                    })
                    .catch((error) => {
                        console.error('Error adding task on gantt:', error);
                        alert('Failed to Add Task to Gantt Chart.');
                    });
            },
        });
    }

    return (
        <>
            <Menu width={220} position="bottom-end" shadow={false} opened={opened} onChange={setOpened} styles={menuStyles}>
                <Menu.Target>
                    {isSubtask ? (
                        <div
                            onClick={openPopover}
                            className='h-[24px] w-[24px] border border-[#E9E9E9] bg-white rounded-full p-[3px] mr-[14px] cursor-pointer hover:bg-gray-50 transition-colors'
                        >
                            <IconDotsVertical size={16} stroke={1.25} color={T.icon} />
                        </div>
                    ) : (
                        <div
                            onClick={openPopover}
                            className='h-[24px] w-[24px] border border-[#E9E9E9] bg-white rounded-full p-[3px] ml-[5px] cursor-pointer hover:bg-gray-50 transition-colors'
                        >
                            <IconDotsVertical size={16} stroke={1.25} color={T.icon} />
                        </div>
                    )}
                </Menu.Target>

                {isSubtask ? (
                    <Menu.Dropdown>
                        <Menu.Label>
                            <span style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                                <div style={{ width: 8, height: 8, borderRadius: '50%', backgroundColor: T.teal, flexShrink: 0 }} />
                                {translate('Subtask')}
                            </span>
                        </Menu.Label>
                        {actions.includes('view') && (
                            <Menu.Item
                                leftSection={<IconEye size={16} stroke={1.5} color={T.icon} />}
                                onClick={handleEditSubTaskDrawerOpen}
                            >
                                {translate('View Subtask')}
                            </Menu.Item>
                        )}
                        {actions.includes('convert') && (taskData && taskData.status !== 'COMPLETED') &&
                            hasPermission(loggedInUser, ['create-task'], projectPermissions, 'project') && (
                                <Menu.Item
                                    leftSection={<IconArrowsExchange size={16} stroke={1.5} color={T.icon} />}
                                    onClick={handleConvertTask}
                                >
                                    {translate('Convert to Task')}
                                </Menu.Item>
                            )}
                        {actions.includes('subtask-complete') && (taskData && taskData.status !== 'COMPLETED') &&
                            hasPermission(loggedInUser, ['complete-task'], projectPermissions, 'project') && (
                                <Menu.Item
                                    leftSection={<IconSquareCheck size={16} stroke={1.5} color={T.icon} />}
                                    onClick={handleCompleteSubTask}
                                >
                                    {translate('Complete Subtask')}
                                </Menu.Item>
                            )}
                        {actions.includes('subtask-complete') && (taskData && taskData.status === 'COMPLETED') &&
                            hasPermission(loggedInUser, ['complete-task'], projectPermissions, 'project') && (
                                <Menu.Item
                                    leftSection={<IconCircleX size={16} stroke={1.5} color={T.icon} />}
                                    onClick={handleInCompleteSubTask}
                                >
                                    {translate('Incomplete Subtask')}
                                </Menu.Item>
                            )}
                        {actions.includes('ganttTask') && hasPermission(loggedInUser, ['add-remove-task-to-gantt'], projectPermissions, 'project') && (
                            <>
                                {(taskData && taskData.status !== 'COMPLETED') && taskData.ganttIsVisible === 1 && (
                                    <Menu.Item
                                        leftSection={<IconCircleMinus size={16} stroke={1.5} color={T.icon} />}
                                        onClick={removeTaskFromGanttHandler}
                                    >
                                        {translate('Remove from Gantt')}
                                    </Menu.Item>
                                )}
                                {!isCompleted && taskData.ganttIsVisible === 0 && (
                                    <Menu.Item
                                        leftSection={<IconCirclePlus size={16} stroke={1.5} color={T.icon} />}
                                        onClick={addTaskToGanttHandler}
                                    >
                                        {translate('Add to Gantt')}
                                    </Menu.Item>
                                )}
                            </>
                        )}
                        {actions.includes('delete') && (
                            (taskData && taskData.createdBy_id == loggedInUser?.loggedUserId) ||
                            hasPermission(loggedInUser, ['delete-tasks-by-others'], projectPermissions, 'project')
                        ) && (
                            <>
                                <Menu.Divider />
                                <Menu.Item>
                                    <TaskDelete task={taskData} taskId={taskData && taskData.id} isSubtask isDrawer />
                                </Menu.Item>
                            </>
                        )}
                    </Menu.Dropdown>

                ) : (
                    <Menu.Dropdown>
                        <Menu.Label>
                            <span style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                                <div style={{ width: 8, height: 8, borderRadius: '50%', backgroundColor: T.teal, flexShrink: 0 }} />
                                {translate('Task')}
                            </span>
                        </Menu.Label>
                        {actions.includes('view') && (
                            <Menu.Item
                                leftSection={<IconEye size={16} stroke={1.5} color={T.icon} />}
                                onClick={handleEditTaskDrawerOpen}
                            >
                                {translate('View Task Details')}
                            </Menu.Item>
                        )}
                        {actions.includes('complete') && hasPermission(loggedInUser, ['complete-task'], projectPermissions, 'project') && (
                            taskData && isCompleted ? (
                                <Menu.Item
                                    leftSection={<IconSquareX size={16} stroke={1.5} color={hasRegularSections ? T.icon : "#BDBDBD"} />}
                                    disabled={!hasRegularSections}
                                    closeMenuOnClick={false}
                                    bg={incompleteMenuOpened ? '#EBF1F4' : ''}
                                >
                                    <Popover
                                        opened={incompleteMenuOpened}
                                        onChange={setIncompleteMenuOpened}
                                        position="left"
                                        offset={34}
                                        width={200}
                                        shadow="md"
                                        withArrow
                                        trapFocus={false}
                                        closeOnClickOutside={true}
                                        radius="lg"
                                    >
                                        <Popover.Target>
                                            <Flex
                                                align="center"
                                                gap="sm"
                                                onMouseDown={(event) => {
                                                    event.stopPropagation();
                                                    if (!hasRegularSections) {
                                                        return;
                                                    }
                                                    setIncompleteMenuOpened((prev) => !prev);
                                                }}
                                            >
                                                <Text size="sm" c={hasRegularSections ? "black" : "#BDBDBD"}>
                                                    {translate('Mark as Incomplete')}
                                                </Text>
                                            </Flex>
                                        </Popover.Target>
                                        <Popover.Dropdown
                                            onClick={(event) => event.stopPropagation()}
                                            onMouseDown={(event) => event.stopPropagation()}
                                        >
                                            <ScrollArea
                                                className={regularSections.length > 5 ? "h-[200px]" : ""}
                                                scrollbarSize={2}
                                            >
                                                <Text size='sm' className='px-2' fw={700}>{translate('Select Section')}</Text>
                                                <Divider my={"xs"} />
                                                <List spacing="xs" size="sm">
                                                    {regularSections.map((section) => (
                                                        <List.Item
                                                            key={section.id}
                                                            className="cursor-pointer hover:bg-gray-100 rounded transition-colors"
                                                            onClick={() => handleInCompleteTask(section.id)}
                                                        >
                                                            <Text size='sm'>{section.name}</Text>
                                                        </List.Item>
                                                    ))}
                                                </List>
                                            </ScrollArea>
                                        </Popover.Dropdown>
                                    </Popover>
                                </Menu.Item>
                            ) : (
                                <Menu.Item
                                    leftSection={<IconSquareCheck size={16} stroke={1.5} color={T.icon} />}
                                    onClick={handleCompleteTask}
                                >
                                    {translate('Mark as Complete')}
                                </Menu.Item>
                            )
                        )}
                        {taskData && isCompleted && hasPermission(loggedInUser, ['close-task'], projectPermissions, 'project') && (
                            <Menu.Item
                                leftSection={<IconPlaylistX size={16} stroke={1.5} color={T.icon} />}
                                onClick={handleMarkAsClose}
                            >
                                {translate('Close Task')}
                            </Menu.Item>
                        )}
                        {actions.includes('duplicateTask') && !isCompleted && hasPermission(loggedInUser, ['create-task'], projectPermissions, 'project') && (
                            <Menu.Item
                                leftSection={<IconCopy size={16} stroke={1.5} color={T.icon} />}
                                onClick={duplicateTaskHandler}
                            >
                                {translate('Duplicate Task')}
                            </Menu.Item>
                        )}
                        {actions.includes('changeVisibility') && !isCompleted && taskData && taskData.createdBy_id == loggedInUser?.loggedUserId && (
                            <>
                                {taskData.taskPrivacy === 'public' && (
                                    <Menu.Item
                                        leftSection={<IconLock size={16} stroke={1.5} color={T.icon} />}
                                        onClick={changeVisibilityHandler}
                                    >
                                        {translate('Make Private')}
                                    </Menu.Item>
                                )}
                                {taskData.taskPrivacy === 'private' && (
                                    <Menu.Item
                                        leftSection={<IconLockOpen size={16} stroke={1.5} color={T.icon} />}
                                        onClick={changeVisibilityHandler}
                                    >
                                        {translate('Make Public')}
                                    </Menu.Item>
                                )}
                            </>
                        )}
                        {actions.includes('ganttTask') && (taskData && taskData.status !== 'COMPLETED') && hasPermission(loggedInUser, ['add-remove-task-to-gantt'], projectPermissions, 'project') && (
                            <>
                                {taskData.ganttIsVisible === 1 ? (
                                    <Menu.Item
                                        leftSection={<IconCircleMinus size={16} stroke={1.5} color={T.icon} />}
                                        onClick={removeTaskFromGanttHandler}
                                    >
                                        {translate('Remove from Gantt')}
                                    </Menu.Item>
                                ) : (
                                    <Menu.Item
                                        leftSection={<IconCirclePlus size={16} stroke={1.5} color={T.icon} />}
                                        onClick={addTaskToGanttHandler}
                                    >
                                        {translate('Add to Gantt')}
                                    </Menu.Item>
                                )}
                            </>
                        )}
                        {actions.includes('changeSection') && !isCompleted && (
                            <Menu.Item>
                                <ChangeTaskSection task={taskData} taskId={taskData && taskData.id} isDrawer />
                            </Menu.Item>
                        )}
                        {window.lazytasksTimeTracker && !isCompleted &&
                         hasPermission(loggedInUser, ['timetracker-access'], projectPermissions, 'project') && (() => {
                            const isSuperadminUser = loggedInUser?.is_superadmin ?? false
                            const canTrackTime = isSuperadminUser || Number(taskData?.assigned_to?.id) === Number(loggedInUser?.loggedUserId)
                            const active = window.lazytasksTimeTracker.getActiveTimer()
                            const isActiveTask = active?.task_id == taskData?.id
                            return (
                                <Menu.Item
                                    leftSection={<IconStopwatch size={16} stroke={1.5} color={T.icon} />}
                                    style={{ opacity: canTrackTime ? 1 : 0.5, cursor: canTrackTime ? 'pointer' : 'not-allowed' }}
                                    onClick={() => {
                                        if (isActiveTask) {
                                            window.lazytasksTimeTracker.stopTimer()
                                        } else {
                                            window.lazytasksTimeTracker.startTimer(
                                                taskData?.id,
                                                taskData?.project_id,
                                                taskData?.title || taskData?.name
                                            )
                                        }
                                    }}
                                >
                                    {isActiveTask
                                        ? translate('Stop Timer')
                                        : translate('Start Timer')}
                                </Menu.Item>
                            )
                        })()}
                        {(actions.includes('archive') || actions.includes('delete')) &&
                          ((taskData && (taskData.createdBy_id == loggedInUser?.loggedUserId || taskData.assignedTo_id == loggedInUser?.loggedUserId)) ||
                           hasPermission(loggedInUser, ['manage-tasks-by-others'], projectPermissions, 'project') ||
                           hasPermission(loggedInUser, ['delete-tasks-by-others'], projectPermissions, 'project')) && !isCompleted &&
                            <Menu.Divider />
                        }
                        {/* Close Task hidden for completed tasks — use Mark as Incomplete instead */}
                        {actions.includes('archive') && !isCompleted && (
                            (taskData && (taskData.createdBy_id == loggedInUser?.loggedUserId || taskData.assignedTo_id == loggedInUser?.loggedUserId)) ||
                            hasPermission(loggedInUser, ['manage-tasks-by-others'], projectPermissions, 'project')
                        ) && (
                            <Menu.Item
                                leftSection={<IconArchive size={16} stroke={1.5} color={T.icon} />}
                                onClick={archiveTaskHandler}
                            >
                                {translate('Archive Task')}
                            </Menu.Item>
                        )}
                        {actions.includes('delete') && !isCompleted && (
                            (taskData && taskData.createdBy_id == loggedInUser?.loggedUserId) ||
                            hasPermission(loggedInUser, ['delete-tasks-by-others'], projectPermissions, 'project')
                        ) && (
                            <Menu.Item>
                                <TaskDelete task={taskData} taskId={taskData?.id} isDrawer />
                            </Menu.Item>
                        )}
                    </Menu.Dropdown>
                )}
            </Menu>
        </>


    );
};

export default TaskActionsMenu;
