import React, { Fragment, useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
    Avatar,
    LoadingOverlay, Card, Box,
    ScrollArea,
    Text, TextInput,
    Title, Drawer,
    Tooltip, Tabs, useMantineTheme,
    Popover, List, Flex, Divider, Group, ThemeIcon,
} from '@mantine/core';
import { showNotification, updateNotification } from "@mantine/notifications";
import { notifications } from "@mantine/notifications";
import { IconUserCircle, IconArchiveOff, IconTrash, IconCheck, IconSearch, IconRefresh } from '@tabler/icons-react';
import { fetchArchiveTasks, fetchClosedTasks, unarchiveTask, deleteTask, removeSuccessMessage, activateTask, fetchProjectOverview } from "../../../components/Settings/store/taskSlice";
import { fetchProjectTaskSections } from "../../../components/Settings/store/projectSlice";
import acronym from "../../../components/ui/acronym";
import useTwColorByName from "../../../components/ui/useTwColorByName";
import { modals } from '@mantine/modals';
import { translate } from '../../../utils/i18n';
import { hasPermission, useProjectPermissions } from '../../ui/permissions';

const ViewArchive = ({ onCloseDrawer, drawerContext = 'archive', onTabChange }) => {
    const theme = useMantineTheme();
    const dispatch = useDispatch();
    const bgColor = useTwColorByName();

    const { archivedTasks, archivedSections, closedTasks, isLoading, isError, error } = useSelector((state) => state.settings.task);
    const { loggedInUser } = useSelector((state) => state.auth.session);
    const { loggedUserId } = useSelector((state) => state.auth.user);

    // Add local loading state
    const [localLoading, setLocalLoading] = useState(false);
    const [searchQueryTasks, setSearchQueryTasks] = useState('');
    const [searchQuerySections, setSearchQuerySections] = useState('');
    const [searchQueryClosedTasks, setSearchQueryClosedTasks] = useState('');
    const [activeTab, setActiveTab] = useState(
        drawerContext === 'sections'
            ? 'sections'
            : drawerContext === 'closed-tasks'
                ? 'closed-tasks'
                : 'tasks'
    );
    const { projectInfo } = useSelector((state) => state.settings.task);
    const projectPermissions = useProjectPermissions(projectInfo?.id);
    const { projectSections } = useSelector((state) => state.settings.project);

    // State for closed task section selector popover
    const [closedTaskPopoverOpen, setClosedTaskPopoverOpen] = useState({});

    // State for archived-task section picker (opens when original section is deleted/archived)
    const [archiveTaskPickerOpen, setArchiveTaskPickerOpen] = useState({});

    useEffect(() => {
        setLocalLoading(true);
        Promise.all([
            dispatch(fetchArchiveTasks()),
            dispatch(fetchClosedTasks()),
            projectInfo?.id ? dispatch(fetchProjectTaskSections(projectInfo.id)) : Promise.resolve()
        ])
            .then(() => {
                setLocalLoading(false);
            })
            .catch(() => {
                setLocalLoading(false);
            });
    }, [dispatch, projectInfo?.id]);

    useEffect(() => {
        const nextTab = drawerContext === 'sections'
            ? 'sections'
            : drawerContext === 'closed-tasks'
                ? 'closed-tasks'
                : 'tasks';
        setActiveTab(nextTab);
        onTabChange?.(nextTab);
    }, [drawerContext, onTabChange]);

    const filteredTasks = (archivedTasks || []).filter(task =>
        task.taskName.toLowerCase().includes(searchQueryTasks.toLowerCase())
    );

    const filteredSections = (archivedSections || []).filter(section =>
        section.sectionName.toLowerCase().includes(searchQuerySections.toLowerCase())
    );

    const filteredClosedTasks = (closedTasks || []).filter(task =>
        task.taskName.toLowerCase().includes(searchQueryClosedTasks.toLowerCase())
    );

    const regularSections = projectSections || [];

    // Sections eligible for unarchive destination: not soft-deleted, not archived.
    // Includes regular sections and the designated-complete section.
    const unarchiveDestinationSections = regularSections.filter(
        s => s.mark_is_complete === 'regular' || s.mark_is_complete === 'complete'
    );

    const isOriginalSectionUnavailable = (task) => {
        const section = regularSections.find(s => s.id === task.sectionId);
        if (!section) return true; // section soft-deleted
        return section.mark_is_complete === 'ARCHIVED_R' || section.mark_is_complete === 'ARCHIVED_C';
    };

    const unarchiveTaskHandler = (taskSectionId, taskId, destinationSectionId = null) => {
        if (onCloseDrawer) onCloseDrawer();
        const destinationSection = destinationSectionId
            ? regularSections.find(s => s.id === destinationSectionId)
            : null;
        modals.openConfirmModal({
            title: 'Unarchive Task',
            centered: true,
            children: (
                <Text size="sm">
                    {destinationSection ? (
                        <>Original section was deleted. Move this task to <b>{destinationSection.name}</b> and unarchive?</>
                    ) : (
                        <>Are you sure you want to unarchive this task?</>
                    )}
                </Text>
            ),
            labels: { confirm: 'Unarchive', cancel: 'Cancel' },
            confirmProps: { color: 'orange' },
            onConfirm: () => {
                showNotification({
                    id: 'load-data',
                    loading: true,
                    title: 'Task',
                    message: "Unarchiving The Task...",
                    disallowClose: true,
                    color: 'green',
                });
                const payload = {
                    task_id: taskId,
                    updated_by: loggedInUser?.loggedUserId ?? loggedUserId,
                };
                if (destinationSectionId) {
                    payload.task_section_id = destinationSectionId;
                }
                dispatch(unarchiveTask({
                    id: destinationSectionId || taskSectionId,
                    data: payload,
                }))
                    .then((response) => {
                        if (response.payload && response.payload.status === 200) {
                            updateNotification({
                                id: 'load-data',
                                loading: true,
                                title: 'Task',
                                message: response.payload?.message,
                                autoClose: 2000,
                                disallowClose: true,
                                color: 'green',
                            });
                        }
                    })
                    .catch((error) => {
                        console.error('Error archiving task:', error);
                        alert('Failed to archive task.');
                    });
            }
        });
    };

    const deleteTaskHandler = (taskId) => {
        if (onCloseDrawer) onCloseDrawer();
        modals.openConfirmModal({
            title: 'Delete Task',
            centered: true,
            children: (
                <Text size="sm" c="red">
                    Are you sure you want to permanently delete this task? This action cannot be undone.
                </Text>
            ),
            labels: { confirm: 'Delete', cancel: 'Cancel' },
            confirmProps: { color: 'red' },
            zIndex: 10001,
            onConfirm: () => {
                showNotification({
                    id: 'load-data',
                    loading: true,
                    title: 'Task',
                    message: "Deleting The Task...",
                    disallowClose: true,
                    color: 'green',
                });
                const taskType = 'task';
                dispatch(deleteTask({
                    id: taskId,
                    data: {
                        deleted_by: loggedInUser?.loggedUserId ?? loggedUserId,
                        type: taskType
                    }
                }))
                    .then((response) => {
                        if (response.payload.status === 200) {
                            updateNotification({
                                id: 'load-data',
                                loading: true,
                                title: 'Task',
                                message: response.payload && response.payload.message && response.payload.message,
                                disallowClose: true,
                                color: 'green',
                            });
                            // notifications.show({
                            //     color: theme.primaryColor,
                            //     title: response.payload.message,
                            //     icon: <IconCheck />,
                            //     autoClose: 3000,
                            // });

                            // const timer = setTimeout(() => {
                            //     dispatch(removeSuccessMessage());
                            // }, 2000);

                            setLocalLoading(true);
                            dispatch(fetchArchiveTasks())
                                .then(() => setLocalLoading(false))
                                .catch(() => setLocalLoading(false));

                            // return () => clearTimeout(timer);
                        }
                    });
            }
        });
    };


    const unarchiveSectionHandler = (taskSectionId) => {
        if (onCloseDrawer) onCloseDrawer();
        modals.openConfirmModal({
            title: 'Unarchive Task',
            centered: true,
            children: (
                <Text size="sm">
                    Are you sure you want to unarchive this task?
                </Text>
            ),
            labels: { confirm: 'Unarchive', cancel: 'Cancel' },
            confirmProps: { color: 'orange' },
            onConfirm: () => {
                showNotification({
                    id: 'load-data',
                    loading: true,
                    title: 'Task',
                    message: "Unarchiving Section...",
                    disallowClose: true,
                    color: 'green',
                });
                dispatch(unarchiveTask({
                    id: taskSectionId,
                    data: {
                        task_id: null,
                        unarchive_section: true,
                        updated_by: loggedInUser?.loggedUserId ?? loggedUserId,
                    }
                }))
                    .then((response) => {

                        if (response.payload && response.payload.status && response.payload.status === 200) {
                            if (projectInfo?.id) {
                                dispatch(fetchProjectOverview(projectInfo.id));
                            }
                            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 reactivateClosedTaskHandler = (taskId, sectionId) => {
        showNotification({
            id: 'load-data',
            loading: true,
            title: 'Task',
            message: "Reactivating The Task...",
            disallowClose: true,
            color: 'green',
        });
        dispatch(activateTask({
            id: taskId,
            data: {
                project_id: projectInfo?.id,
                task_section_id: sectionId,
                updated_by: loggedInUser?.loggedUserId ?? loggedUserId,
            }
        }))
            .then((response) => {
                if (response.payload && response.payload.status === 200) {
                    updateNotification({
                        id: 'load-data',
                        loading: false,
                        title: 'Task',
                        message: response.payload?.message,
                        autoClose: 2000,
                        disallowClose: true,
                        color: 'green',
                    });

                    // Refresh closed tasks list
                    setLocalLoading(true);
                    dispatch(fetchClosedTasks())
                        .then(() => setLocalLoading(false))
                        .catch(() => setLocalLoading(false));
                } else {
                    updateNotification({
                        id: 'load-data',
                        loading: false,
                        title: 'Task',
                        message: response.payload?.message || 'Failed to reactivate task',
                        autoClose: 2000,
                        disallowClose: true,
                        color: 'red',
                    });
                }
            })
            .catch((error) => {
                console.error('Error reactivating task:', error);
                updateNotification({
                    id: 'load-data',
                    loading: false,
                    title: 'Task',
                    message: 'Failed to reactivate task',
                    autoClose: 2000,
                    disallowClose: true,
                    color: 'red',
                });
            });
    };

    const deleteClosedTaskHandler = (taskId) => {
        modals.openConfirmModal({
            title: 'Delete Task',
            centered: true,
            zIndex: 10001,
            children: (
                <Text size="sm" c="#495057">
                    Are you sure you want to permanently delete this task? This action cannot be undone.
                </Text>
            ),
            labels: { confirm: 'Delete', cancel: 'Cancel' },
            confirmProps: { color: 'red' },
            onConfirm: () => {
                showNotification({
                    id: 'load-data',
                    loading: true,
                    title: 'Task',
                    message: "Deleting The Task...",
                    disallowClose: true,
                    color: 'green',
                });
                dispatch(deleteTask({
                    id: taskId,
                    data: {
                        deleted_by: loggedInUser?.loggedUserId ?? loggedUserId,
                        type: 'task'
                    }
                }))
                    .then((response) => {
                        if (response.payload?.status === 200) {
                            updateNotification({
                                id: 'load-data',
                                loading: false,
                                title: 'Task',
                                message: response.payload?.message,
                                autoClose: 2000,
                                disallowClose: true,
                                color: 'green',
                            });

                            // Refresh closed tasks list
                            setLocalLoading(true);
                            dispatch(fetchClosedTasks())
                                .then(() => setLocalLoading(false))
                                .catch(() => setLocalLoading(false));
                        }
                    })
                    .catch((error) => {
                        console.error('Error deleting task:', error);
                        updateNotification({
                            id: 'load-data',
                            loading: false,
                            title: 'Task',
                            message: 'Failed to delete task',
                            autoClose: 2000,
                            disallowClose: true,
                            color: 'red',
                        });
                    });
            }
        });
    };

    return (
        <>
            <ScrollArea className="h-[calc(100vh-130px)] pr-1" scrollbarSize={4} offsetScrollbars={true}>
                <Box px="xs">

                    <Tabs variant="pills" radius="md" value={activeTab} onChange={(value) => {
                        setActiveTab(value);
                        onTabChange?.(value);
                    }} className='my-tabs'
                        styles={{
                            tab: { color: '#202020', backgroundColor: '#F5F8F9' },
                        }}
                    >
                        <Tabs.List className="mb-3" grow>
                            {hasPermission(loggedInUser, ['manage-section'], projectPermissions, 'project') && (
                                <Tabs.Tab value="sections" className="font-bold">
                                    {translate('Archived Sections')}
                                </Tabs.Tab>
                            )}
                            {hasPermission(loggedInUser, ['manage-section', 'create-task'], projectPermissions, 'project') && (
                                <Tabs.Tab value="tasks" className="font-bold">
                                    {translate('Archived Tasks')}
                                </Tabs.Tab>
                            )}
                            {hasPermission(loggedInUser, ['close-task'], projectPermissions, 'project') && (
                                <Tabs.Tab value="closed-tasks" className="font-bold">
                                    {translate('Closed Tasks')}
                                </Tabs.Tab>
                            )}

                        </Tabs.List>
                        <Tabs.Panel value="tasks">
                            <TextInput
                                leftSection={<IconSearch size={18} />}
                                placeholder={translate('Search archived tasks...')}
                                value={searchQueryTasks}
                                onChange={(e) => setSearchQueryTasks(e.target.value)}
                                className="mb-3"
                            />

                            <LoadingOverlay visible={localLoading} zIndex={1000} overlayProps={{ radius: "sm", blur: 2 }} />

                            {filteredTasks && filteredTasks.length > 0 ? filteredTasks.map((task) => (

                                <Card withBorder size="xs" radius="sm" padding="xs" className='mb-2' key={task.taskId}>
                                    <div className="flex items-center gap-4">
                                        <div className="flex-1">
                                            <Text size='sm'>{task.taskName}</Text>
                                        </div>
                                        <div className="flex items-center gap-3">
                                            {task.assignedToUsername ? (
                                                <Tooltip label={task.assignedToUsername} position="top" withArrow>
                                                    <Avatar
                                                        size='30'
                                                        src={task && task.avatar ? task.avatar : null}
                                                        stroke='1.25'
                                                    >
                                                        {task && task.avatar ? '' : <Text style={{ "lineHeight": "14px" }} size="xs">{task && task.assignedToUsername ? acronym(task.assignedToUsername) : ""}</Text>}
                                                    </Avatar>
                                                </Tooltip>
                                            ) : (
                                                <div className="h-[30px] w-[30px] border border-dashed border-[#202020] rounded-full flex items-center justify-center">
                                                    <Tooltip label="Assign to" position="top" withArrow>
                                                        <IconUserCircle color="#4d4d4d" size={20} stroke={1.25} />
                                                    </Tooltip>
                                                </div>
                                            )}
                                            <div className="flex items-center gap-2">
                                                {(
                                                    (loggedInUser?.loggedUserId != null && (
                                                        String(task.createdBy_id) === String(loggedInUser.loggedUserId) ||
                                                        String(task.assignedTo_id) === String(loggedInUser.loggedUserId)
                                                    )) ||
                                                    hasPermission(loggedInUser, ['manage-tasks-by-others'], projectPermissions, 'project')
                                                ) && (isOriginalSectionUnavailable(task) ? (
                                                    <Popover
                                                        opened={archiveTaskPickerOpen[task.taskId] || false}
                                                        onChange={(opened) => setArchiveTaskPickerOpen({ ...archiveTaskPickerOpen, [task.taskId]: opened })}
                                                        position="left"
                                                        offset={5}
                                                        width={220}
                                                        shadow="md"
                                                        withArrow
                                                        zIndex={10001}
                                                        trapFocus={false}
                                                        closeOnClickOutside={true}
                                                        radius="lg"
                                                    >
                                                        <Popover.Target>
                                                            <Tooltip label="Original section deleted — pick a destination" position="top" withArrow>
                                                                <IconArchiveOff
                                                                    className="cursor-pointer"
                                                                    color="var(--mantine-color-orange-filled)"
                                                                    size={22}
                                                                    stroke={1.25}
                                                                    onClick={() => setArchiveTaskPickerOpen({ ...archiveTaskPickerOpen, [task.taskId]: !archiveTaskPickerOpen[task.taskId] })}
                                                                />
                                                            </Tooltip>
                                                        </Popover.Target>
                                                        <Popover.Dropdown
                                                            onClick={(event) => event.stopPropagation()}
                                                            onMouseDown={(event) => event.stopPropagation()}
                                                        >
                                                            <ScrollArea
                                                                className={unarchiveDestinationSections.length > 5 ? "h-[200px]" : ""}
                                                                scrollbarSize={2}
                                                            >
                                                                <Text size='sm' className='px-2' fw={700}>{translate('Select Section')}</Text>
                                                                <Divider my={"xs"} />
                                                                {unarchiveDestinationSections.length === 0 ? (
                                                                    <Text size="xs" c="dimmed" ta="center" py="xs">
                                                                        {translate('No active sections available. Create a section first.')}
                                                                    </Text>
                                                                ) : (
                                                                    <List spacing="xs" size="sm" listStyleType="none">
                                                                        {unarchiveDestinationSections.map((section) => (
                                                                            <List.Item
                                                                                key={section.id}
                                                                                className="cursor-pointer hover:bg-gray-100 rounded transition-colors"
                                                                                onClick={() => {
                                                                                    setArchiveTaskPickerOpen({ ...archiveTaskPickerOpen, [task.taskId]: false });
                                                                                    unarchiveTaskHandler(task.sectionId, task.taskId, section.id);
                                                                                }}
                                                                            >
                                                                                <Text size='sm'>{section.name}</Text>
                                                                            </List.Item>
                                                                        ))}
                                                                    </List>
                                                                )}
                                                            </ScrollArea>
                                                        </Popover.Dropdown>
                                                    </Popover>
                                                ) : (
                                                    <Tooltip label="Unarchive" position="top" withArrow>
                                                        <IconArchiveOff
                                                            className="cursor-pointer"
                                                            color="var(--mantine-color-orange-filled)"
                                                            size={22}
                                                            stroke={1.25}
                                                            onClick={() => unarchiveTaskHandler(task.sectionId, task.taskId)}
                                                        />
                                                    </Tooltip>
                                                ))}
                                                {!task.has_child && (
                                                    <button
                                                        type="button"
                                                        className="cursor-pointer bg-transparent border-0 p-0"
                                                        aria-label={translate('Delete task')}
                                                        onClick={() => deleteClosedTaskHandler(task.taskId)}
                                                    >
                                                        <IconTrash
                                                            color="var(--mantine-color-red-filled)"
                                                            size={22}
                                                            stroke={1.25}
                                                        />
                                                    </button>
                                                )}
                                            </div>
                                        </div>
                                    </div>
                                </Card>

                            )) : (
                                <Card withBorder size="xs" radius="sm" padding="xs" className='mb-2'>
                                    <Text size='sm' ta='center'>{translate('No archived tasks')}</Text>
                                </Card>
                            )}

                        </Tabs.Panel>
                        <Tabs.Panel value="sections">
                            <TextInput
                                leftSection={<IconSearch size={18} />}
                                placeholder={translate('Search archived sections...')}
                                value={searchQuerySections}
                                onChange={(e) => setSearchQuerySections(e.target.value)}
                                className="mb-3"
                            />

                            <LoadingOverlay visible={localLoading} zIndex={1000} overlayProps={{ radius: "sm", blur: 2 }} />

                            {filteredSections && filteredSections.length > 0 ? filteredSections.map((section, index) => (
                                <Card withBorder size="xs" radius="sm" padding="xs" className='mb-2' key={section.sectionId}>
                                    <div className="flex items-center gap-4">
                                        <div className="flex-1">
                                            <Text size='sm'>{section.sectionName}</Text>
                                        </div>
                                        <div className="flex justify-end items-center gap-3">
                                            <div className="flex items-center gap-2">
                                                <Tooltip label="Unarchive" position="top" withArrow>
                                                    <IconArchiveOff
                                                        className="cursor-pointer"
                                                        color="var(--mantine-color-orange-filled)"
                                                        size={22}
                                                        stroke={1.25}
                                                        onClick={() => unarchiveSectionHandler(section.sectionId)}
                                                    />
                                                </Tooltip>

                                            </div>
                                        </div>
                                    </div>
                                </Card>
                            )) :
                                (
                                    <Card withBorder size="xs" radius="sm" padding="xs" className='mb-2'>
                                        <Text size='sm' ta='center'>{translate('No archived sections')}</Text>
                                    </Card>
                                )}

                        </Tabs.Panel>
                        <Tabs.Panel value="closed-tasks">
                            <TextInput
                                leftSection={<IconSearch size={18} />}
                                placeholder={translate('Search closed tasks...')}
                                value={searchQueryClosedTasks}
                                onChange={(e) => setSearchQueryClosedTasks(e.target.value)}
                                className="mb-3"
                            />

                            <LoadingOverlay visible={localLoading} zIndex={1000} overlayProps={{ radius: "sm", blur: 2 }} />

                            {filteredClosedTasks && filteredClosedTasks.length > 0 ? filteredClosedTasks.map((task) => (
                                <Card withBorder size="xs" radius="sm" padding="xs" className='mb-2' key={task.taskId}>
                                    <div className="flex items-center gap-4">
                                        <div className="flex-1">
                                            <Text size='sm'>{task.taskName}</Text>
                                        </div>
                                        <div className="flex items-center gap-3">
                                            {task.assignedToUsername ? (
                                                <Tooltip label={task.assignedToUsername} position="top" withArrow>
                                                    <Avatar
                                                        size='30'
                                                        src={task && task.avatar ? task.avatar : null}
                                                        stroke='1.25'
                                                    >
                                                        {task && task.avatar ? '' : <Text style={{ "lineHeight": "14px" }} size="xs">{task && task.assignedToUsername ? acronym(task.assignedToUsername) : ""}</Text>}
                                                    </Avatar>
                                                </Tooltip>
                                            ) : (
                                                <div className="h-[30px] w-[30px] border border-dashed border-[#202020] rounded-full flex items-center justify-center">
                                                    <Tooltip label="Assign to" position="top" withArrow>
                                                        <IconUserCircle color="#4d4d4d" size={20} stroke={1.25} />
                                                    </Tooltip>
                                                </div>
                                            )}
                                            <div className="flex items-center gap-2">
                                                <Popover
                                                    opened={closedTaskPopoverOpen[task.taskId] || false}
                                                    onChange={(opened) => setClosedTaskPopoverOpen({ ...closedTaskPopoverOpen, [task.taskId]: opened })}
                                                    position="left"
                                                    offset={5}
                                                    width={200}
                                                    shadow="md"
                                                    withArrow
                                                    zIndex={10001}
                                                    trapFocus={false}
                                                    closeOnClickOutside={true}
                                                    radius="lg"
                                                >
                                                    <Popover.Target>
                                                        <Tooltip label="Reactivate" position="top" withArrow>
                                                            <IconRefresh
                                                                className="cursor-pointer"
                                                                color="#4D4D4D"
                                                                size={22}
                                                                stroke={1.25}
                                                                onClick={() => setClosedTaskPopoverOpen({ ...closedTaskPopoverOpen, [task.taskId]: !closedTaskPopoverOpen[task.taskId] })}
                                                            />
                                                        </Tooltip>
                                                    </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={() => {
                                                                            setClosedTaskPopoverOpen({ ...closedTaskPopoverOpen, [task.taskId]: false });
                                                                            modals.openConfirmModal({
                                                                                title: (
                                                                                    <Group spacing="xs">
                                                                                        <ThemeIcon color="orange" radius="xl" size="lg" variant="filled">
                                                                                            <IconRefresh size={24} />
                                                                                        </ThemeIcon>
                                                                                        <Text size="md" weight={500}>
                                                                                            {translate('Reopen Task')}
                                                                                        </Text>
                                                                                    </Group>
                                                                                ),
                                                                                centered: true,
                                                                                zIndex: 10001,
                                                                                children: (
                                                                                    <>
                                                                                        <Divider size="xs" mb={24} className='!-ml-4 w-[calc(100%+2rem)]' />
                                                                                        <Text size="md" mb={30}>
                                                                                            Are you sure you want to reopen this task and move it to {section.name}?
                                                                                        </Text>
                                                                                    </>
                                                                                ),
                                                                                labels: { confirm: 'Yes, reopen it', cancel: 'cancel' },
                                                                                confirmProps: { color: 'orange' },
                                                                                onConfirm: () => {
                                                                                    reactivateClosedTaskHandler(task.taskId, section.id);
                                                                                },
                                                                            });
                                                                        }}
                                                                    >
                                                                        <Text size='sm'>{section.name}</Text>
                                                                    </List.Item>
                                                                ))}
                                                            </List>
                                                        </ScrollArea>
                                                    </Popover.Dropdown>
                                                </Popover>
                                                {!task.has_child && (
                                                    <button
                                                        type="button"
                                                        className="cursor-pointer bg-transparent border-0 p-0"
                                                        aria-label={translate('Delete task')}
                                                        onClick={() => deleteClosedTaskHandler(task.taskId)}
                                                    >
                                                        <IconTrash
                                                            color="var(--mantine-color-red-filled)"
                                                            size={22}
                                                            stroke={1.25}
                                                        />
                                                    </button>
                                                )}
                                            </div>
                                        </div>
                                    </div>
                                </Card>
                            )) : (
                                <Card withBorder size="xs" radius="sm" padding="xs" className='mb-2'>
                                    <Text size='sm' ta='center'>{translate('No closed tasks')}</Text>
                                </Card>
                            )}

                        </Tabs.Panel>
                    </Tabs>
                </Box>
            </ScrollArea>
        </>
    );
}
export default ViewArchive;