import React, { useEffect, useRef, useState } from 'react';
import { useSelector } from 'react-redux';
import {
    FileInput, rem, Text, ScrollArea, Avatar, Popover,
    LoadingOverlay, ActionIcon, useMantineTheme, Flex, Switch,
    TextInput, Alert,
} from '@mantine/core';
import { IconCheck, IconFile, IconPaperclip, IconTrash, IconAlertCircle } from '@tabler/icons-react';
import ContentEditable from 'react-contenteditable';
import { useEditor } from '@tiptap/react';
import { Link, RichTextEditor } from '@mantine/tiptap';
import StarterKit from '@tiptap/starter-kit';
import Underline from '@tiptap/extension-underline';
import Placeholder from '@tiptap/extension-placeholder';
import Mention from '@tiptap/extension-mention';
import TextAlign from '@tiptap/extension-text-align';
import { notifications, showNotification, updateNotification } from '@mantine/notifications';
import { modals } from '@mantine/modals';
import dayjs from 'dayjs';

// Create-mode field components (callback-based, no Redux dispatch inside)
import TaskAssignTo from '../Elements/Project/TasksElements/Task/TaskAssignTo';
import TaskFollower from '../Elements/Project/TasksElements/Task/TaskFollower';
import DueDate from '../Elements/Project/TasksElements/Task/DueDate';
import Priority from '../Elements/Project/TasksElements/Task/Priority';
import Status from '../Elements/Project/TasksElements/Task/Status';
import TaskTagForTaskAdd from '../Elements/Project/TasksElements/Task/TaskTagForTaskAdd';
// Edit-mode gantt dependency components (imported only for edit + gantt context)
import TaskDependency from '../Elements/Project/TasksElements/Task/TaskDependency';
import TaskChildDependency from '../Elements/Project/TasksElements/Task/TaskChildDependency';

import { hasPermission } from './permissions';
import { translate } from '../../utils/i18n';
import { validateFileSize } from '../../utils/validateFileSize';

/**
 * Reusable label+content row for drawer fields.
 * Exported so edit-mode wrappers can build their own field rows with it.
 */
export const FieldRow = ({ label, zIndex = 1, children, className = '' }) => (
    <div className={`flex items-center ${className}`} style={{ position: 'relative', zIndex }}>
        <div className="w-1/4">
            <Text fw={600} fz={12} c="#64748B">{label}</Text>
        </div>
        {children}
    </div>
);

/**
 * TaskDrawer — unified drawer body component for all task create/edit contexts.
 *
 * Handles: layout, RichTextEditor + @mention, attachments, gantt toggle.
 * Does NOT contain any Redux calls — all side effects delegate to wrapper callbacks.
 *
 * Modes:
 *   'create' — manages full local form state, calls onSave(formData) on submit
 *   'edit'   — renders field rows via editFields slot, delegates name/desc via callbacks
 *
 * Wrapper files stay at their original paths so no consumers need updating.
 */
const TaskDrawer = ({
    // ── Core ──────────────────────────────────────────────────────────────────
    mode = 'create',            // 'create' | 'edit'
    buttonLabel,                // Override button label; defaults to Create / Update

    // ── User context (both modes) ─────────────────────────────────────────────
    user = {},                  // { loggedInUser, loggedUserId }
    projectPermissions = [],    // resolved project permission array

    // ── @mention member list ──────────────────────────────────────────────────
    members = [],               // [{ id, label/name, avatar }]

    // ── Common callbacks ──────────────────────────────────────────────────────
    onClose,

    // ── CREATE MODE ───────────────────────────────────────────────────────────
    onSave,                     // async fn(formData) → { status, message }
    initialTaskName = '',
    initialDates = null,        // { startDate, endDate } — prefill (calendar mode)
    boardMembers = [],          // override member list for Assigned/Following fields
    projectPriorities = [],     // override priorities for Priority field
    projectStatuses = [],       // override statuses for Status field
    sectionField = null,        // JSX | null — section picker row (calendar/quicktask)
    workspacePickers = null,    // JSX | null — workspace→project→section cascade (quicktask)

    // ── EDIT MODE ─────────────────────────────────────────────────────────────
    task = {},                  // task object from Redux
    taskObj = null,             // original task prop (for parent check, permissions)
    onNameSave,                 // fn(name) — called on ContentEditable blur
    onDescriptionSave,          // fn(description, mentionedUsers) — called on close
    onGanttToggle,              // fn(isVisible) — called when gantt switch changes
    isGanttVisible = false,     // gantt switch state (controlled by wrapper)
    localStartDate = null,      // for gantt validation (edit mode)
    localEndDate = null,
    actionsMenu = null,         // JSX — <TaskActionsMenu .../>
    editFields = null,          // JSX — field rows (Assigned, Following, Due Date, etc.)
    showCreatedBy = false,
    showRefNumber = false,
    isCompleted = false,
    isLoading = false,          // show loading overlay
    subtasksSection = null,     // JSX — full subtasks section
    commentsSection = null,     // JSX — full comments/activities section

    // ── ATTACHMENTS (both modes) ──────────────────────────────────────────────
    onAttachmentUpload,         // async fn(files) → { status, data, message }
    onAttachmentDelete,         // async fn(id) → { status, data, message }
    attachmentsInit = [],       // initial attachment list (edit mode)

    // ── Feature flags ─────────────────────────────────────────────────────────
    showGanttToggle = false,
}) => {
    const { loggedInUser, loggedUserId } = user;
    const theme = useMantineTheme();
    const icon = <IconPaperclip style={{ width: rem(18), height: rem(18) }} stroke={1.5} />;

    // ── Create-mode local state ───────────────────────────────────────────────
    const [createTaskName, setCreateTaskName] = useState(initialTaskName || translate('Type task name here'));
    const [selectedMember, setSelectedMember]       = useState(null);
    const [selectedFollower, setSelectedFollower]   = useState(null);
    const [selectedPriority, setSelectedPriority]   = useState(null);
    const [selectedStatus, setSelectedStatus]       = useState(null);
    const [selectedTags, setSelectedTags]           = useState(null);
    const [selectedDependencies, setSelectedDependencies] = useState(null);
    const [selectedStartDate, setSelectedStartDate] = useState(initialDates?.startDate || null);
    const [selectedDueDate, setSelectedDueDate]     = useState(initialDates?.endDate || null);
    const [startDateIsVisible, setStartDateIsVisible] = useState(false);
    const [dueDateIsVisible, setDueDateIsVisible]   = useState(true);
    const [isGanttCreate, setIsGanttCreate]         = useState(false);

    // Sync initialDates when prop changes (calendar mode: new date clicked)
    useEffect(() => {
        if (mode === 'create' && initialDates) {
            setSelectedStartDate(initialDates.startDate || null);
            setSelectedDueDate(initialDates.endDate || null);
        }
    }, [initialDates?.startDate, initialDates?.endDate]);

    // ── Edit-mode local state ─────────────────────────────────────────────────
    const [editTaskName, setEditTaskName] = useState(task?.name || '');
    const contentEditableRef = useRef('');

    // Sync when the active task changes (drawer stays mounted, task swaps)
    useEffect(() => {
        if (mode === 'edit') {
            setEditTaskName(task?.name || '');
        }
    }, [task?.id]);

    // ── Shared: description ───────────────────────────────────────────────────
    const [taskDescription, setTaskDescription] = useState(
        mode === 'edit' ? (task?.description || '') : ''
    );

    // ── Attachments ───────────────────────────────────────────────────────────
    const [attachments, setAttachments] = useState(attachmentsInit || []);
    const [isUploading, setIsUploading] = useState(false);
    const maxUploadSize = useSelector(s => s.settings?.setting?.effectiveMaxUploadSize) || 0;
    const maxUploadSizeHuman = useSelector(s => s.settings?.setting?.effectiveMaxUploadSizeHuman) || '';

    useEffect(() => {
        if (mode === 'edit') setAttachments(attachmentsInit || []);
    }, [JSON.stringify(attachmentsInit)]);

    // ── @mention ──────────────────────────────────────────────────────────────
    const [mentionPopoverOpened, setMentionPopoverOpened] = useState(false);
    const [mentionItems, setMentionItems]   = useState([]);
    const [mentionCommand, setMentionCommand] = useState(() => () => {});
    const mentionAnchorRef = useRef(null);
    const membersRef = useRef([]);

    useEffect(() => {
        if (members?.length) {
            membersRef.current = members.map(u => ({
                id: u.id,
                label: u.name || u.label,
                avatar: u.avatar,
            }));
        }
    }, [members]);

    // ── RichTextEditor ────────────────────────────────────────────────────────
    const canEditDescription =
        mode === 'create' ||
        (!isCompleted && (
            (task && (task.createdBy_id == loggedInUser?.loggedUserId || task.assignedTo_id == loggedInUser?.loggedUserId)) ||
            hasPermission(loggedInUser, ['manage-tasks-by-others'], projectPermissions, 'project')
        ));

    const editor = useEditor({
        extensions: [
            StarterKit.configure({ heading: { levels: [1, 2, 3, 4, 5] } }),
            Link.configure({
                autolink: true,
                linkOnPaste: true,
                openOnClick: true,
                HTMLAttributes: { target: '_blank', rel: 'noopener noreferrer' },
            }),
            Underline,
            TextAlign.configure({ types: ['heading', 'paragraph'] }),
            Placeholder.configure({ placeholder: translate('What is the task about...') }),
            Mention.configure({
                HTMLAttributes: { class: 'mention', 'data-id': 'id', 'data-label': 'label' },
                renderText: ({ node }) => `@${node.attrs.label}`,
                suggestion: {
                    char: '@',
                    items: ({ query }) =>
                        membersRef.current
                            .filter(u => u.label.toLowerCase().startsWith(query.toLowerCase()))
                            .sort((a, b) => a.label.localeCompare(b.label)),
                    render: () => ({
                        onStart: (props) => {
                            setMentionItems(props.items);
                            setMentionCommand(() => props.command);
                            if (props.clientRect) {
                                const rect = props.clientRect();
                                if (rect && mentionAnchorRef.current) {
                                    mentionAnchorRef.current.style.top = `${rect.top}px`;
                                }
                            }
                            setMentionPopoverOpened(true);
                        },
                        onUpdate: (props) => {
                            setMentionItems(props.items);
                            setMentionCommand(() => props.command);
                            if (props.clientRect) {
                                const rect = props.clientRect();
                                if (rect && mentionAnchorRef.current) {
                                    mentionAnchorRef.current.style.top = `${rect.top}px`;
                                }
                            }
                        },
                        onExit: () => {
                            setMentionPopoverOpened(false);
                            setMentionItems([]);
                        },
                    }),
                },
            }),
        ],
        content: taskDescription,
        editable: canEditDescription,
        onUpdate: ({ editor }) => setTaskDescription(editor.getHTML()),
    });

    // Keep editor content in sync when task changes (edit mode)
    useEffect(() => {
        if (editor && mode === 'edit' && task?.description !== undefined) {
            editor.commands.setContent(task.description || '');
        }
    }, [editor, task?.description]);

    // ── Attachment handlers ───────────────────────────────────────────────────
    const handleFileUpload = (files) => {
        const { ok, message } = validateFileSize(files, maxUploadSize, maxUploadSizeHuman);
        if (!ok) {
            notifications.show({
                color: 'red',
                title: translate('File size error'),
                message,
                autoClose: 4000,
            });
            return;
        }

        if (mode === 'edit') {
            const existingNames = attachments.map(a => a.name);
            const duplicates = files.filter(f => existingNames.includes(f.name));
            if (duplicates.length > 0) {
                notifications.show({
                    color: 'red',
                    title: translate('Duplicate file'),
                    message: `"${duplicates.map(f => f.name).join('", "')}" ${translate('is already attached to this task.')}`,
                    autoClose: 3000,
                });
                return;
            }
        }

        if (onAttachmentUpload) {
            setIsUploading(true);
            onAttachmentUpload(files).then(response => {
                setIsUploading(false);
                if (response?.status === 200) {
                    setAttachments(response.data);
                    if (mode === 'edit') {
                        notifications.show({
                            color: theme.primaryColor,
                            title: response.message,
                            icon: <IconCheck />,
                            autoClose: 2000,
                        });
                    }
                } else if (mode === 'edit') {
                    notifications.show({
                        color: 'red',
                        title: translate('Upload Failed'),
                        message: response?.message || translate('An error occurred during upload.'),
                        autoClose: 3000,
                    });
                }
            });
        } else {
            // Local-only mode (calendar/quicktask create drawers)
            setAttachments(Array.from(files));
        }
    };

    const handleAttachmentDelete = (idOrIndex) => {
        modals.openConfirmModal({
            title: <Text fw={700}>{translate('Delete attachment')}</Text>,
            size: 'sm',
            radius: 'md',
            withCloseButton: false,
            centered: true,
            children: (
                <Text size="sm">
                    {translate('Are you sure you want to delete this attachment? This action cannot be undone.')}
                </Text>
            ),
            labels: { confirm: translate('Delete'), cancel: translate('Cancel') },
            confirmProps: { color: 'red' },
            onConfirm: () => {
                if (onAttachmentDelete) {
                    setIsUploading(true);
                    onAttachmentDelete(idOrIndex).then(response => {
                        setIsUploading(false);
                        if (response?.status === 200) {
                            setAttachments(response.data);
                            notifications.show({
                                color: theme.primaryColor,
                                title: response.message,
                                icon: <IconCheck />,
                                autoClose: 2000,
                            });
                        }
                    });
                } else {
                    // Create mode without upload: remove by index
                    setAttachments(prev => prev.filter((_, i) => i !== idOrIndex));
                }
            },
        });
    };

    // ── Create: due date ──────────────────────────────────────────────────────
    const handleDueDateSelect = (dateData) => {
        if (!dateData) {
            setSelectedStartDate(null);
            setSelectedDueDate(null);
            setStartDateIsVisible(false);
            setDueDateIsVisible(false);
            return;
        }
        const { dates, visibility } = dateData;
        if (Array.isArray(dates)) {
            const [start, end] = dates;
            setSelectedStartDate(start ? dayjs(start).format('YYYY-MM-DD') : null);
            setSelectedDueDate(end ? dayjs(end).format('YYYY-MM-DD') : null);
        }
        setStartDateIsVisible(visibility.startDateIsVisible);
        setDueDateIsVisible(visibility.dueDateIsVisible);
    };

    // ── Create: submit ────────────────────────────────────────────────────────
    const handleCreateTask = () => {
        const name = createTaskName;
        if (!name || name === translate('Type task name here') || name.trim() === '') {
            notifications.show({
                color: 'red',
                title: translate('Task'),
                message: translate('Task name cannot be empty'),
                autoClose: 4000,
            });
            return;
        }

        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = taskDescription;
        const mentionedUsers = Array.from(tempDiv.querySelectorAll('.mention')).map(m => ({
            id: m.getAttribute('data-id'),
            name: m.getAttribute('data-label'),
        }));

        const formData = {
            name,
            description: taskDescription,
            mention_users: mentionedUsers,
            assigned_to: selectedMember,
            members: selectedFollower,
            start_date: selectedStartDate,
            end_date: selectedDueDate,
            start_date_is_visible: startDateIsVisible,
            end_date_is_visible: dueDateIsVisible,
            priority: selectedPriority,
            internal_status: selectedStatus,
            tags: selectedTags,
            dependencies: selectedDependencies,
            is_visible: isGanttCreate,
            attachments,
        };

        if (onSave) {
            showNotification({
                id: 'task-create',
                loading: true,
                title: translate('Task'),
                message: translate('Creating New Task...'),
                disallowClose: true,
                color: 'green',
            });
            onSave(formData).then(response => {
                if (response?.status === 200) {
                    // Reset form state
                    setCreateTaskName(initialTaskName || translate('Type task name here'));
                    setTaskDescription('');
                    editor?.commands.clearContent();
                    setSelectedMember(null);
                    setSelectedFollower(null);
                    setSelectedPriority(null);
                    setSelectedStatus(null);
                    setSelectedTags(null);
                    setSelectedDependencies(null);
                    setSelectedStartDate(null);
                    setSelectedDueDate(null);
                    setAttachments([]);
                    setIsGanttCreate(false);
                    updateNotification({
                        id: 'task-create',
                        loading: false,
                        title: translate('Task'),
                        message: response.message || translate('Task created successfully'),
                        autoClose: 4000,
                        color: 'green',
                    });
                    onClose?.();
                }
            });
        }
    };

    // ── Edit: name blur ───────────────────────────────────────────────────────
    const handleNameBlur = () => {
        const name = contentEditableRef.current?.innerHTML;
        if (task?.id && name && name !== editTaskName && onNameSave) {
            onNameSave(name);
            setEditTaskName(name);
        }
    };

    // ── Edit: close (save description) ───────────────────────────────────────
    const handleEditClose = () => {
        if (taskDescription && taskDescription !== task?.description && onDescriptionSave) {
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = taskDescription;
            const mentionedUsers = Array.from(tempDiv.querySelectorAll('.mention')).map(m => ({
                id: m.getAttribute('data-id'),
                name: m.getAttribute('data-label'),
            }));
            onDescriptionSave(taskDescription, mentionedUsers);
        }
        onClose?.();
    };

    // ── Gantt handlers ────────────────────────────────────────────────────────
    const handleGanttCreate = (enabling) => {
        if (enabling && !selectedStartDate && !selectedDueDate) {
            notifications.show({
                color: 'red',
                title: translate('Date Required'),
                message: translate('Adding to gantt requires a date or date range.'),
                autoClose: 4000,
            });
            return;
        }
        setIsGanttCreate(enabling);
    };

    const handleGanttEdit = (enabling) => {
        if (enabling && !localStartDate && !localEndDate) {
            notifications.show({
                color: 'red',
                title: translate('Date Required'),
                message: translate('Set at least a start or end date to display on Gantt.'),
                autoClose: 4000,
            });
            return;
        }
        onGanttToggle?.(enabling);
    };

    // ── Permissions ───────────────────────────────────────────────────────────
    const canAddAttachment = !isCompleted &&
        (mode === 'create' ||
         (task && (task.createdBy_id == loggedInUser?.loggedUserId || task.assignedTo_id == loggedInUser?.loggedUserId)) ||
         hasPermission(loggedInUser, ['manage-tasks-by-others'], projectPermissions, 'project'));

    const canDeleteAttach = (attachment) =>
        (attachment?.user_id == loggedInUser?.loggedUserId) ||
        hasPermission(loggedInUser, ['delete-attachments-by-others'], projectPermissions, 'project');

    const canToggleGantt = hasPermission(loggedInUser, ['add-remove-task-to-gantt'], projectPermissions, 'project');

    // ── Derived values ────────────────────────────────────────────────────────
    const resolvedButtonLabel = buttonLabel || (mode === 'create' ? translate('Create') : translate('Update'));
    const effectiveGanttVisible = mode === 'create' ? isGanttCreate : isGanttVisible;
    const effectiveStartDate    = mode === 'create' ? selectedStartDate : localStartDate;
    const effectiveEndDate      = mode === 'create' ? selectedDueDate   : localEndDate;

    // ── Render ────────────────────────────────────────────────────────────────
    return (
        <div className="drawer h-full flex flex-col">
            <div className={`flex flex-col flex-1 overflow-hidden ${appLocalizer?.is_admin ? 'mt-6' : 'mt-2'}`}>

                {/* Loading overlay (edit mode) */}
                {mode === 'edit' && (
                    <LoadingOverlay visible={isLoading} zIndex={1000} overlayProps={{ radius: 'sm', blur: 5 }} />
                )}

                {/* ── Header ── */}
                <div className="drawer-head flex w-full items-center pb-3 mb-3 border-b border-[#E2E8F0]">
                    <div className="w-[80%]">
                        {mode === 'create' ? (
                            <TextInput
                                placeholder={translate('Type task name here')}
                                defaultValue={initialTaskName}
                                onChange={(e) => setCreateTaskName(e.target.value)}
                                onKeyDown={(e) => { if (e.key === 'Enter') handleCreateTask(); }}
                                styles={{
                                    input: {
                                        height: 36,
                                        fontSize: 14,
                                        fontWeight: 600,
                                        border: '1px solid #E2E8F0',
                                        borderRadius: 6,
                                        color: '#1A202C',
                                    }
                                }}
                            />
                        ) : (
                            (!isCompleted && (
                                (taskObj && (taskObj.createdBy_id == loggedInUser?.loggedUserId || taskObj.assignedTo_id == loggedInUser?.loggedUserId)) ||
                                hasPermission(loggedInUser, ['manage-tasks-by-others'], projectPermissions, 'project')
                            )) ? (
                                <ContentEditable
                                    innerRef={contentEditableRef}
                                    html={editTaskName}
                                    onChange={(e) => setEditTaskName(e.target.value)}
                                    onBlur={handleNameBlur}
                                    className="inline-block w-full text-[#4d4d4d] font-bold text-[16px] !min-h-[36px]"
                                />
                            ) : (
                                <Text size="sm" className="text-[#000000] font-semibold text-[14px] px-0 !outline-none pr-1">
                                    {editTaskName}
                                </Text>
                            )
                        )}
                    </div>
                    <div className="dh-btn flex w-[20%]">
                        <div className="flex w-full gap-3 items-center justify-center">
                            <button
                                onClick={mode === 'create' ? handleCreateTask : handleEditClose}
                                className="!ml-2 h-[36px] border-0 w-[70px] bg-[#39758D] text-white rounded-md text-sm font-medium"
                            >
                                {resolvedButtonLabel}
                            </button>
                            {actionsMenu}
                        </div>
                    </div>
                </div>

                {/* ── Body ── */}
                <ScrollArea className="flex-1" style={{ minHeight: 0 }} scrollbarSize={4}>
                    <div className="tasks-body flex flex-col gap-4 relative w-full">

                        {/* Workspace + project + section cascade (quicktask) */}
                        {workspacePickers}

                        {/* Section picker row (calendar / quicktask) */}
                        {sectionField}

                        {/* Edit mode: Ref# */}
                        {mode === 'edit' && showRefNumber && taskObj?.parent === null && (
                            <FieldRow label={translate('Ref.#')} zIndex={8}>
                                <div className="w-3/4">
                                    <span className="bg-[#EBF1F4] text-[#4d4d4d] px-2 py-0.5 rounded text-sm">
                                        {String(task.task_serial_no || '').padStart(4, '0')}
                                    </span>
                                </div>
                            </FieldRow>
                        )}

                        {/* Edit mode: Created By */}
                        {mode === 'edit' && showCreatedBy && (
                            <FieldRow label={translate('Created By')} zIndex={7}>
                                <div className="relative w-3/4">
                                    <Text fw={400} fz={13} c="#1A202C">{task.createdBy_name}</Text>
                                </div>
                            </FieldRow>
                        )}

                        {/* Field rows:
                            – edit mode: wrapper provides field JSX (uses correct Redux slice)
                            – create mode: base renders callback-based field components */}
                        {mode === 'edit' ? (
                            editFields
                        ) : (
                            <>
                                <FieldRow label={translate('Assigned')} zIndex={7}>
                                    <div className="relative">
                                        <TaskAssignTo
                                            boardMembers={boardMembers}
                                            assignedMember={setSelectedMember}
                                            createdBy_id={loggedInUser?.loggedUserId || loggedUserId}
                                            assignedTo_id={selectedMember?.id}
                                        />
                                    </div>
                                </FieldRow>
                                <FieldRow label={translate('Following')} zIndex={6}>
                                    <div className="relative">
                                        <TaskFollower
                                            boardMembers={boardMembers}
                                            editHandler={setSelectedFollower}
                                        />
                                    </div>
                                </FieldRow>
                                <FieldRow label={translate('Due Date')} zIndex={5}>
                                    <DueDate
                                        editHandler={handleDueDateSelect}
                                        dueDate={selectedDueDate}
                                        startDate={selectedStartDate}
                                        startDateIsVisible={startDateIsVisible}
                                        dueDateIsVisible={dueDateIsVisible}
                                    />
                                </FieldRow>
                                <FieldRow label={translate('Priority')} zIndex={4}>
                                    <Priority
                                        editPriorityHandler={setSelectedPriority}
                                        projectPriorities={projectPriorities}
                                    />
                                </FieldRow>
                                <FieldRow label={translate('Status')} zIndex={3}>
                                    <Status
                                        editStatusHandler={setSelectedStatus}
                                        projectStatuses={projectStatuses}
                                    />
                                </FieldRow>
                                <FieldRow label={translate('Tags')} zIndex={2}>
                                    <TaskTagForTaskAdd onChangeSelectedItem={setSelectedTags} />
                                </FieldRow>
                            </>
                        )}

                        {/* ── Attachments ── */}
                        <div className="flex" style={{ position: 'relative', zIndex: 1 }}>
                            <LoadingOverlay visible={isUploading} overlayProps={{ radius: 'sm', blur: 2 }} />
                            <div className="w-1/4">
                                <Text fw={600} fz={12} c="#64748B">{translate('Attachments')}</Text>
                            </div>
                            <div className="flex flex-wrap gap-3 w-3/4">
                                {attachments?.map((attachment, index) => (
                                    <div
                                        key={attachment.id ?? index}
                                        className="bg-[#EBF1F4] rounded-full px-3 py-1 flex gap-2 items-center"
                                    >
                                        <IconFile size={14} />
                                        {attachment.file_path ? (
                                            <a
                                                href={attachment.file_path}
                                                target="_blank"
                                                rel="noopener noreferrer"
                                                download
                                                style={{ textDecoration: 'underline' }}
                                            >
                                                <Text size="xs" lineClamp={1} fw={400} fz={12} c="#1A202C">
                                                    {attachment.name}
                                                </Text>
                                            </a>
                                        ) : (
                                            <Text fw={400} fz={12} c="#1A202C">{attachment.name}</Text>
                                        )}
                                        {(mode === 'create' || canDeleteAttach(attachment)) && (
                                            <ActionIcon
                                                onClick={() => handleAttachmentDelete(attachment.id ?? index)}
                                                variant="transparent"
                                                aria-label="Delete"
                                            >
                                                <IconTrash size={20} stroke={1} color="red" />
                                            </ActionIcon>
                                        )}
                                    </div>
                                ))}
                                {canAddAttachment && (
                                    <div className="attachment w-[30px] h-[30px]">
                                        <FileInput
                                            multiple
                                            variant="unstyled"
                                            rightSection={icon}
                                            rightSectionPointerEvents="none"
                                            clearable
                                            onChange={handleFileUpload}
                                        />
                                    </div>
                                )}
                            </div>
                        </div>

                        {/* ── Gantt toggle ── */}
                        {showGanttToggle && (
                            <FieldRow label={translate('Display on gantt')} zIndex={1}>
                                <Switch
                                    color="orange"
                                    size="md"
                                    onLabel={translate('ON')}
                                    offLabel={translate('OFF')}
                                    checked={effectiveGanttVisible}
                                    disabled={mode === 'edit' ? (isCompleted || !canToggleGantt) : !canToggleGantt}
                                    className={!canToggleGantt ? 'opacity-50 cursor-not-allowed' : ''}
                                    onChange={(e) => {
                                        const enabling = e.currentTarget.checked;
                                        mode === 'create' ? handleGanttCreate(enabling) : handleGanttEdit(enabling);
                                    }}
                                />
                            </FieldRow>
                        )}

                        {/* Gantt alert when enabled but no dates set (edit mode) */}
                        {mode === 'edit' && effectiveGanttVisible && !effectiveStartDate && !effectiveEndDate && (
                            <Alert color="orange" variant="light" icon={<IconAlertCircle size={16} />} mb="sm">
                                {translate('Set at least a start or end date for this task to appear on the Gantt chart.')}
                            </Alert>
                        )}

                        {/* Create mode: TaskDependency appears when gantt is ON */}
                        {mode === 'create' && effectiveGanttVisible && (
                            <FieldRow label={translate('Parent Tasks')} zIndex={1}>
                                <div className="relative w-3/4">
                                    <TaskDependency onChange={setSelectedDependencies} />
                                </div>
                            </FieldRow>
                        )}

                        {/* Edit mode: Parent Tasks + Child Tasks (when gantt visible) */}
                        {mode === 'edit' && showGanttToggle && effectiveGanttVisible && (
                            <>
                                <FieldRow label={translate('Parent Tasks')} zIndex={1}>
                                    <div className="relative w-3/4">
                                        <TaskDependency
                                            taskId={task.id}
                                            currentDependencies={task.dependencies}
                                            disabled={isCompleted}
                                        />
                                    </div>
                                </FieldRow>
                                <FieldRow label={translate('Child Tasks')} zIndex={1}>
                                    <div className="relative w-3/4">
                                        <TaskChildDependency taskId={task.id} disabled={isCompleted} />
                                    </div>
                                </FieldRow>
                            </>
                        )}

                        {/* ── RichTextEditor ── */}
                        <div className="editor-container border border-[#E2E8F0] rounded-md overflow-hidden" style={{ maxHeight: '250px', overflowY: 'auto' }}>
                            <RichTextEditor editor={editor}>
                                <RichTextEditor.Toolbar>
                                    <RichTextEditor.ControlsGroup>
                                        <RichTextEditor.Bold />
                                        <RichTextEditor.Italic />
                                        <RichTextEditor.Underline />
                                        <RichTextEditor.Strikethrough />
                                    </RichTextEditor.ControlsGroup>
                                    <RichTextEditor.ControlsGroup>
                                        <RichTextEditor.H1 />
                                        <RichTextEditor.H2 />
                                        <RichTextEditor.H3 />
                                        <RichTextEditor.H4 />
                                        <RichTextEditor.H5 />
                                    </RichTextEditor.ControlsGroup>
                                    <RichTextEditor.ControlsGroup>
                                        <RichTextEditor.AlignLeft />
                                        <RichTextEditor.AlignRight />
                                        <RichTextEditor.AlignCenter />
                                        <RichTextEditor.AlignJustify />
                                    </RichTextEditor.ControlsGroup>
                                    <RichTextEditor.ControlsGroup>
                                        <RichTextEditor.BulletList />
                                        <RichTextEditor.OrderedList />
                                    </RichTextEditor.ControlsGroup>
                                </RichTextEditor.Toolbar>
                                <RichTextEditor.Content className="prose prose-sm" spellCheck={false} />
                            </RichTextEditor>
                        </div>

                        {/* @mention popover (Mantine Popover, position-fixed anchor) */}
                        <Popover
                            opened={mentionPopoverOpened}
                            trapFocus={false}
                            withinPortal={false}
                            width={300}
                            position="top-start"
                        >
                            <Popover.Target>
                                <div ref={mentionAnchorRef} style={{ position: 'fixed', pointerEvents: 'none' }} />
                            </Popover.Target>
                            <Popover.Dropdown style={{ borderRadius: 8, boxShadow: '0 8px 32px rgba(0,0,0,.12)', border: '1px solid #E2E8F0', padding: 4 }}>
                                <ScrollArea.Autosize mah={250} scrollbarSize={4}>
                                    {mentionItems.map(item => (
                                        <Flex
                                            key={item.id}
                                            align="center"
                                            px="sm"
                                            py={6}
                                            className="hover:bg-[#EBF1F4] rounded cursor-pointer"
                                            onMouseDown={(e) => {
                                                e.preventDefault();
                                                mentionCommand({ id: item.id, label: item.label });
                                                setTimeout(() => editor?.commands.focus(), 0);
                                                setMentionPopoverOpened(false);
                                            }}
                                        >
                                            <Avatar src={item.avatar} size={24} radius="xl" mr={8} />
                                            <Text fz={13} c="#1A202C">{item.label}</Text>
                                        </Flex>
                                    ))}
                                </ScrollArea.Autosize>
                            </Popover.Dropdown>
                        </Popover>

                        {/* Subtasks section (edit mode, provided by wrapper) */}
                        {subtasksSection}

                        {/* TimeTracker addon panel (edit mode only) — between subtasks and comments */}
                        {mode === 'edit' && window.lazytasksTimeTracker?.drawerPanel &&
                            React.createElement(window.lazytasksTimeTracker.drawerPanel, {
                                taskId: task?.id,
                                taskObj: task,   // use fetchTask result — has estimated_hours
                                canManageEntries: hasPermission(loggedInUser, ['timetracker-manage-entries'], projectPermissions, 'project'),
                                canManageEstimates: hasPermission(loggedInUser, ['timetracker-manage-estimates'], projectPermissions, 'project'),
                                currentUserId: loggedInUser?.loggedUserId,
                                isSuperadmin: loggedInUser?.is_superadmin ?? false,
                            })
                        }

                        {/* Comments / Activities section (edit mode, provided by wrapper) */}
                        {commentsSection}

                    </div>
                </ScrollArea>
            </div>
        </div>
    );
};

export default TaskDrawer;
