import React from "react";
import styles from "./task-list-table.module.css";
import TaskAssignTo from "../Task/TaskAssignTo";
import TaskDueDate from "../Task/TaskDueDate";
import { editTask, toggleGanttListVisibility } from "../../../../Settings/store/taskSlice";
import { useDispatch, useSelector } from "react-redux";
import { useParams } from "react-router-dom";
import { Divider, Group, Text, ThemeIcon, Tooltip, Badge } from "@mantine/core";
import { IconCircleMinus, IconX } from "@tabler/icons-react";
import { modals } from "@mantine/modals";
import { showNotification, updateNotification } from "@mantine/notifications";
import { translate } from "../../../../../utils/i18n";
import TaskStatus from "../Task/TaskStatus";

export const TaskListTable = ({
    rowHeight,
    tasks,
    setTasks,
    onExpanderClick,
    onClick
}) => {
    const dispatch = useDispatch();
    const { id } = useParams();
    const { ganttListIsVisible } = useSelector((state) => state.settings.task);

    if (!ganttListIsVisible) {
        return (
            <div
                className={styles.taskListWrapper}
                style={{
                    fontFamily: 'inherit',
                    height: tasks.length * rowHeight,
                    width: '40px',
                    backgroundColor: '#f8f9fa',
                    borderRight: '1px solid #e9ecef',
                    cursor: 'pointer',
                    display: 'flex',
                    flexDirection: 'column'
                }}
                onClick={() => dispatch(toggleGanttListVisibility())}
            >
                <div style={{
                    position: 'sticky',
                    top: '50%',
                    transform: 'translateY(-50%)',
                    width: '100%',
                    display: 'flex',
                    justifyContent: 'center',
                }}>
                    <div style={{
                        transform: 'rotate(-90deg)',
                        whiteSpace: 'nowrap',
                        color: '#6c757d',
                        fontWeight: 600,
                        fontSize: '14px',
                        textAlign: 'center',
                        lineHeight: '1.2'
                    }}>
                        {translate("Project Table")} <br /> {translate("Click to expand")}
                    </div>
                </div>
            </div>
        );
    }

    const removeTaskFromGanttHandler = (taskId) => {
        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: taskId,
                    data: updatedTask
                }))
                    .then((response) => {
                        if (response.payload && response.payload.status && response.payload.status === 200) {
                            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 Remove Task from Gantt Chart.');
                    });
            },
        });
    }

    return (
        <div className={styles.taskListWrapper} style={{ fontFamily: 'inherit' }}>
            {tasks.map((t, index) => {
                return (
                    <div
                        key={t.id}
                        className={`taskRowWrapper task-list-item ${styles.taskListTableRow}`}
                        style={{
                            height: rowHeight,
                            cursor: 'pointer',
                            borderBottom: '1px solid #e9ecef',
                            transition: 'background-color 0.2s',
                        }}
                        onClick={() => onClick(t)}
                        onMouseEnter={(e) => e.currentTarget.style.backgroundColor = '#f8f9fa'}
                        onMouseLeave={(e) => e.currentTarget.style.backgroundColor = 'transparent'}
                    >
                        {/* Name Column */}
                        <div
                            className={styles.taskListCell}
                            style={{
                                minWidth: "250px",
                                maxWidth: "250px",
                                paddingLeft: "0px",
                                display: 'flex',
                                alignItems: 'center',
                            }}
                        >
                            <div
                                className={`pr-3 ${styles.taskListNameWrapper} ${t.parent ? styles.subTaskList : ""}`}
                                style={{ display: 'flex', alignItems: 'center', width: '100%' }}
                            >
                                <div
                                    className={
                                        t.hideChildren === false
                                            ? styles.taskListExpander
                                            : styles.taskListEmptyExpander
                                    }
                                    onClick={(e) => {
                                        e.stopPropagation();
                                        onExpanderClick(t);
                                    }}
                                    style={{ marginRight: '8px', cursor: 'pointer', width: '20px', textAlign: 'center' }}
                                >
                                    {t.hideChildren === false ? "▼" : (t.hideChildren === true ? "▶" : "")}
                                </div>
                                <div
                                    className="taskNameWrapper"
                                    style={{
                                        display: 'flex',
                                        alignItems: 'center',
                                        overflow: 'hidden',
                                        flex: 1,
                                        cursor: 'pointer',
                                    }}
                                    onClick={() => onClick(t)}
                                >
                                    <Tooltip
                                        label={<div dangerouslySetInnerHTML={{ __html: t.fullName }} />}
                                        position="top-start"
                                        withArrow
                                        transitionProps={{ duration: 200, transition: 'fade' }}
                                    >
                                        <Text
                                            size="sm"
                                            className="truncate"
                                            style={{
                                                overflow: 'hidden',
                                                textOverflow: 'ellipsis',
                                                whiteSpace: 'nowrap',
                                                fontWeight: 500,
                                                color: '#343a40'
                                            }}
                                            dangerouslySetInnerHTML={{ __html: t.fullName }}
                                        />
                                    </Tooltip>
                                    {!t.headerOnly && (
                                        <Tooltip
                                            label={translate('Remove from Gantt')}
                                            position="top"
                                            withArrow
                                            transitionProps={{ duration: 200, transition: 'fade' }}
                                        >
                                            <IconX
                                                className={styles.ganttRemoveIcon}
                                                stroke={1.5}
                                                size={14}
                                                onClick={(e) => {
                                                    e.stopPropagation();
                                                    removeTaskFromGanttHandler(t.id);
                                                }}
                                            />
                                        </Tooltip>
                                    )}
                                </div>
                            </div>
                        </div>

                        {/* Assignee Column */}
                        <div
                            className={styles.taskListCell}
                            style={{
                                minWidth: "100px",
                                maxWidth: "100px",
                                textAlign: "center",
                                borderLeft: '1px solid #f1f3f5',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center'
                            }}
                            onClick={(e) => e.stopPropagation()}
                        >
                            {!t.headerOnly && <TaskAssignTo taskId={Number(t.id)} assigned={t.assigned_to} view='ganttView' />}
                        </div>

                        {/* Status Column */}
                        <div
                            className={styles.taskListCell}
                            style={{
                                minWidth: "150px",
                                maxWidth: "150px",
                                textAlign: "center",
                                borderLeft: '1px solid #f1f3f5',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center'
                            }}
                            onClick={(e) => e.stopPropagation()}
                        >
                            {!t.headerOnly && <TaskStatus taskId={Number(t.id)} status={t.internal_status || t.status} view='ganttView' taskDbStatus={t.status} />}
                        </div>


                        {/* Date Column */}
                        <div
                            className={styles.taskListCell}
                            style={{
                                minWidth: "130px",
                                maxWidth: "130px",
                                textAlign: "center",
                                borderLeft: '1px solid #f1f3f5',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center'
                            }}
                            onClick={(e) => e.stopPropagation()}
                        >
                            {!t.headerOnly && <TaskDueDate
                                taskId={t.id}
                                startDate={t.start_date}
                                dueDate={t.end_date}
                                startDateIsVisible={t.start_date_is_visible}
                                dueDateIsVisible={t.end_date_is_visible}
                            />}
                        </div>
                    </div>
                );
            })}
        </div>
    );
};