import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Text, Box, Pill, Select, ActionIcon } from '@mantine/core';
import { useDisclosure } from '@mantine/hooks';
import { IconChevronDown, IconEye } from '@tabler/icons-react';

import TaskAssignTo from './Task/TaskAssignTo';
import TaskFollower from './Task/TaskFollower';
import TaskDueDate from './Task/TaskDueDate';
import TaskPriority from './Task/TaskPriority';
import TaskStatus from './Task/TaskStatus';
import TaskTag from './Task/TaskTag';
import TaskName from './Task/TaskName';
import TaskActionsMenu from './Task/TaskActionsMenu';
import TaskComment from './TaskComment';
import TaskActivity from './TaskActivity';
import TaskCommentAndActivity from './TaskCommentAndActivity';

import {
    closeTaskEditDrawer,
    createAttachment,
    createTask,
    deleteAttachment,
    editTask,
    fetchTask,
    setEditableTask,
} from '../../../Settings/store/taskSlice';
import { hasPermission, useProjectPermissions } from '../../../ui/permissions';
import { translate } from '../../../../utils/i18n';
import TaskDrawer, { FieldRow } from '../../../ui/TaskDrawer';

const EditTaskDrawer = (props) => {
    const { taskObj, taskId, taskEditDrawerOpen } = props;
    const dispatch = useDispatch();

    const { loggedInUser } = useSelector(s => s.auth.session);
    const { loggedUserId }  = useSelector(s => s.auth.user);
    const { projectInfo, task } = useSelector(s => s.settings.task);
    const projectPermissions = useProjectPermissions(projectInfo?.id);

    const isCompleted = taskObj?.status === 'COMPLETED';

    const [subTask, setSubTask] = useState(task.children || []);
    const [newlyCreatedSubtaskId, setNewlyCreatedSubtaskId] = useState(null);
    const [isSubtasksExpanded, setIsSubtasksExpanded] = useState(true);

    const [isVisibleGantt, setIsVisibleGantt]                 = useState(!!(task?.ganttIsVisible === 1));
    const [localStartDate, setLocalStartDate]                  = useState(task.start_date ?? null);
    const [localEndDate, setLocalEndDate]                      = useState(task.end_date ?? null);
    const [localStartDateIsVisible, setLocalStartDateIsVisible] = useState(!!(task.start_date_is_visible));
    const [localDueDateIsVisible, setLocalDueDateIsVisible]    = useState(!!(task.end_date_is_visible));

    const [selectedValue, setSelectedValue] = useState('Comments & Activities');
    const [commentDropdownOpened, { toggle }] = useDisclosure();
    const [visible, setVisible] = useState(false);

    const members = (taskObj?.project?.members || []).map(u => ({
        id: u.id, label: u.name, avatar: u.avatar,
    }));

    // Fetch task when taskId, comment view, or drawer open-state changes (ensures fresh data on reopen)
    useEffect(() => {
        if (taskId && taskEditDrawerOpen) {
            dispatch(fetchTask({ id: taskId })).then(response => {
                if (response.payload?.status === 200) {
                    setVisible(false);
                    setSubTask(response.payload.data.children || []);
                } else {
                    // Task not found or API error — hide loading overlay and close drawer
                    setVisible(false);
                    dispatch(closeTaskEditDrawer());
                }
            });
        }
    }, [taskId, selectedValue, taskEditDrawerOpen]);

    // Sync gantt + date state when active task changes (drawer stays mounted)
    useEffect(() => {
        setIsVisibleGantt(!!(task?.ganttIsVisible === 1));
        setLocalStartDate(task.start_date ?? null);
        setLocalEndDate(task.end_date ?? null);
        setLocalStartDateIsVisible(!!(task.start_date_is_visible));
        setLocalDueDateIsVisible(!!(task.end_date_is_visible));
        setSubTask(task.children || []);
    }, [task.id]);

    // Loading overlay on drawer open
    useEffect(() => {
        if (taskEditDrawerOpen === true) setVisible(true);
        setSubTask(task.children || []);
    }, [taskEditDrawerOpen]);

    // ── Attachment callbacks ──────────────────────────────────────────────────
    const handleAttachmentUpload = async (files) => {
        const formData = new FormData();
        files.forEach((file, i) => formData.append(`attachments${i}`, file));
        formData.append('task_id', task.id);
        formData.append('user_id', loggedInUser?.loggedUserId || loggedUserId);
        const response = await dispatch(createAttachment({ data: formData }));
        return response.payload;
    };

    const handleAttachmentDelete = async (id) => {
        const response = await dispatch(deleteAttachment({
            id,
            data: { task_id: task.id, deleted_by: loggedInUser?.loggedUserId || loggedUserId },
        }));
        return response.payload;
    };

    // ── Name / description save ───────────────────────────────────────────────
    const handleNameSave = (name) => {
        dispatch(editTask({ id: task.id, data: { name, updated_by: loggedInUser?.loggedUserId || loggedUserId } }));
        dispatch(setEditableTask({ ...task, name }));
    };

    const handleDescriptionSave = (description, mentionedUsers) => {
        dispatch(editTask({
            id: task.id,
            data: { description, mention_users: mentionedUsers, updated_by: loggedInUser?.loggedUserId || loggedUserId },
        }));
        dispatch(setEditableTask({ ...task, description }));
    };

    // ── Gantt toggle ──────────────────────────────────────────────────────────
    const handleGanttToggle = (isVisible) => {
        dispatch(editTask({ id: task.id, data: { is_visible: isVisible ? 1 : 0 } }));
        setIsVisibleGantt(isVisible);
        dispatch(setEditableTask({ ...task, ganttIsVisible: isVisible ? 1 : 0 }));
    };

    // ── Add subtask ───────────────────────────────────────────────────────────
    const addSubtask = () => {
        dispatch(fetchTask({ id: taskId })).then(response => {
            if (response.payload?.status !== 200) return;
            const children = response.payload.data.children || [];
            setSubTask(children);
            const placeholder = children.find(s => s.name === '' || s.name === 'Type task name here');
            if (placeholder) { setNewlyCreatedSubtaskId(placeholder.id); return; }

            dispatch(createTask({
                name: 'Type task name here',
                parent: task,
                task_section_id: task.task_section_id,
                project_id: task.project_id,
                type: 'sub-task',
                created_by: loggedInUser?.loggedUserId || loggedUserId,
                status: 'ACTIVE',
            })).then(res => {
                if (res.payload?.status === 200) {
                    dispatch(fetchTask({ id: taskId })).then(refreshRes => {
                        if (refreshRes.payload?.status === 200) {
                            setSubTask(refreshRes.payload.data.children || []);
                            if (res.payload.data?.id) setNewlyCreatedSubtaskId(res.payload.data.id);
                        }
                    });
                }
            });
        });
    };

    // ── Field rows (uses TasksElements/Task/* which dispatch to taskSlice) ────
    const dueDateLabel = localStartDate && localStartDateIsVisible ? translate('Date') : translate('Due Date');

    const editFields = (
        <>
            <FieldRow label={translate('Assigned')} zIndex={7}>
                <div className="relative">
                    <TaskAssignTo taskId={task.id} assigned={task.assigned_to} disabled={isCompleted} createdBy_id={task.createdBy_id} assignedTo_id={task.assignedTo_id} />
                </div>
            </FieldRow>
            <FieldRow label={translate('Following')} zIndex={6}>
                <div className="relative">
                    <TaskFollower taskId={task.id} followers={task.members} disabled={isCompleted} />
                </div>
            </FieldRow>
            <FieldRow label={dueDateLabel} zIndex={5}>
                <TaskDueDate
                    taskId={task.id}
                    startDate={localStartDate}
                    dueDate={localEndDate}
                    startDateIsVisible={localStartDateIsVisible}
                    dueDateIsVisible={localDueDateIsVisible}
                    isDrawer
                    disabled={isCompleted}
                    createdBy_id={task.createdBy_id}
                    assignedTo_id={task.assignedTo_id}
                    onDateUpdate={(start, end, startVis, endVis) => {
                        setLocalStartDate(start);
                        setLocalEndDate(end);
                        setLocalStartDateIsVisible(!!startVis);
                        setLocalDueDateIsVisible(!!endVis);
                    }}
                />
            </FieldRow>
            <FieldRow label={translate('Priority')} zIndex={4}>
                <TaskPriority taskId={task.id} priority={task.priority} disabled={isCompleted} createdBy_id={task.createdBy_id} assignedTo_id={task.assignedTo_id} />
            </FieldRow>
            <FieldRow label={translate('Status')} zIndex={3}>
                <TaskStatus taskId={task.id} status={task.internal_status} taskDbStatus={task.status} createdBy_id={task.createdBy_id} assignedTo_id={task.assignedTo_id} />
            </FieldRow>
            <FieldRow label={translate('Tags')} zIndex={2}>
                <div className="relative">
                    <TaskTag taskId={task.id} taskTags={task.tags} disabled={isCompleted} createdBy_id={task.createdBy_id} assignedTo_id={task.assignedTo_id} />
                </div>
            </FieldRow>
        </>
    );

    // ── Subtasks section ──────────────────────────────────────────────────────
    const subtasksSection = task?.parent === null ? (
        <div className="mb-6 rounded-xl border border-[#E2E8F0] bg-[#F8FAFC]">
            <div className="flex items-center justify-between px-4 py-3 border-b border-[#E2E8F0] rounded-t-xl">
                <div className="flex items-center gap-2">
                    {subTask.length > 0 && (
                        <ActionIcon variant="transparent" onClick={() => setIsSubtasksExpanded(v => !v)} color="gray">
                            <IconChevronDown
                                size={18}
                                style={{
                                    transform: isSubtasksExpanded ? 'rotate(180deg)' : 'rotate(0deg)',
                                    transition: 'transform 200ms ease',
                                }}
                            />
                        </ActionIcon>
                    )}
                    <Text fw={600} fz={14} c="#0F172A">Subtasks</Text>
                    {subTask.length > 0 && (
                        <div className="bg-[#E2E8F0] text-[#475569] px-2 py-0.5 rounded-md text-sm font-bold">
                            {subTask.length}
                        </div>
                    )}
                </div>
                {!isCompleted && subTask.length > 0 && (() => {
                    const isCreator  = task?.createdBy_id == loggedInUser?.loggedUserId;
                    const isAssignee = task?.assignedTo_id == loggedInUser?.loggedUserId;
                    const canAdd = hasPermission(loggedInUser, ['create-task'], projectPermissions, 'project')
                        && (isCreator || isAssignee || hasPermission(loggedInUser, ['manage-tasks-by-others'], projectPermissions, 'project'));
                    return (
                        <button
                            className={`text-[#39758D] text-sm font-semibold px-2 py-1 rounded-md transition-colors ${!canAdd ? 'opacity-50 cursor-not-allowed' : 'hover:bg-[#EBF1F4]'}`}
                            onClick={canAdd ? addSubtask : undefined}
                            disabled={!canAdd}
                        >
                            + Add subtask
                        </button>
                    );
                })()}
            </div>

            {subTask.length > 0 ? (
                isSubtasksExpanded && (
                    <div className="flex flex-col gap-0 bg-white rounded-b-xl">
                        {subTask.map((subtask, index) => (
                            <Box
                                key={index}
                                onDoubleClickCapture={() => dispatch(setEditableTask(subtask))}
                                className={`border-b border-[#F1F5F9] last:border-b-0 p-3 hover:bg-[#F8FAFC] transition-colors ${subtask.status === 'COMPLETED' ? 'opacity-70 bg-[#F8FAFC]' : ''}`}
                            >
                                <div className="flex justify-between items-center w-full gap-2">
                                    <Box className="flex-1 pr-2 flex items-center gap-2">
                                        <ActionIcon
                                            variant="subtle"
                                            color="gray"
                                            size="sm"
                                            onClick={() => dispatch(setEditableTask(subtask))}
                                            aria-label="View subtask"
                                            title="View subtask"
                                        >
                                            <IconEye size={16} stroke={1.5} />
                                        </ActionIcon>
                                        <Box className="flex-1">
                                            <TaskName
                                                task={subtask}
                                                taskId={subtask.id}
                                                view="cardView"
                                                isSubtask
                                                nameOfTask={subtask.name || ''}
                                                disabled={subtask.status === 'COMPLETED'}
                                                autoFocus={String(subtask.id) === String(newlyCreatedSubtaskId)}
                                            />
                                        </Box>
                                    </Box>
                                    <div className="flex items-center gap-2">
                                        {subtask.status && (
                                            <span
                                                className="px-2 py-0.5 rounded bg-gray-100 text-xs font-medium uppercase"
                                                style={{
                                                    backgroundColor: subtask.statusInfo?.color ? `${subtask.statusInfo.color}20` : '#F1F5F9',
                                                    color: subtask.statusInfo?.color || '#475569',
                                                }}
                                            >
                                                {subtask.status?.name || (typeof subtask.status === 'string' ? subtask.status : '')}
                                            </span>
                                        )}
                                        {subtask.priority && (
                                            <span
                                                className="px-2 py-0.5 rounded bg-gray-100 text-xs font-medium uppercase"
                                                style={{
                                                    backgroundColor: subtask.priorityInfo?.color ? `${subtask.priorityInfo.color}20` : '#F1F5F9',
                                                    color: subtask.priorityInfo?.color || '#475569',
                                                }}
                                            >
                                                {subtask.priority?.name || (typeof subtask.priority === 'string' ? subtask.priority : '')}
                                            </span>
                                        )}
                                        <div className="border-l border-gray-200 h-5 mx-1" />
                                        <TaskDueDate
                                            taskId={subtask.id}
                                            startDate={subtask.start_date || null}
                                            dueDate={subtask.end_date || null}
                                            startDateIsVisible={subtask.start_date_is_visible}
                                            dueDateIsVisible={subtask.end_date_is_visible}
                                            isSubtask
                                            isDrawer
                                            disabled={subtask.status === 'COMPLETED'}
                                            createdBy_id={subtask?.createdBy_id}
                                            assignedTo_id={subtask?.assignedTo_id}
                                        />
                                        <TaskAssignTo
                                            taskId={subtask.id}
                                            view="cardView"
                                            assigned={subtask.assigned_to || null}
                                            disabled={subtask.status === 'COMPLETED'}
                                            createdBy_id={subtask?.createdBy_id}
                                            assignedTo_id={subtask?.assignedTo_id}
                                        />
                                    </div>
                                </div>
                            </Box>
                        ))}
                    </div>
                )
            ) : (
                <div className="p-4 bg-white rounded-b-xl flex justify-center">
                    {!isCompleted && (() => {
                        const isCreator  = task?.createdBy_id == loggedInUser?.loggedUserId;
                    const isAssignee = task?.assignedTo_id == loggedInUser?.loggedUserId;
                    const canAdd = hasPermission(loggedInUser, ['create-task'], projectPermissions, 'project')
                        && (isCreator || isAssignee || hasPermission(loggedInUser, ['manage-tasks-by-others'], projectPermissions, 'project'));
                        return (
                            <button
                                className={`w-full rounded-lg border border-dashed border-[#CBD5E1] p-2 flex justify-center items-center transition-colors text-[#64748B] ${!canAdd ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer hover:bg-[#F8FAFC]'}`}
                                onClick={canAdd ? addSubtask : undefined}
                                disabled={!canAdd}
                            >
                                <div className="w-4 h-4 rounded-full bg-[#64748B] text-white flex items-center justify-center mr-2 text-xs font-bold leading-none pb-[2px]">+</div>
                                <span className="font-semibold text-sm">Add a subtask</span>
                            </button>
                        );
                    })()}
                </div>
            )}
        </div>
    ) : null;

    // ── Comments section ──────────────────────────────────────────────────────
    const commentsSection = (
        <div className="commentbox bg-[#F8FAFC] border border-[#E2E8F0] rounded-xl p-4 mt-2">
            <div className="mb-4">
                {!commentDropdownOpened ? (
                    <div className="cursor-pointer flex items-center gap-1 text-[#0F172A]" onClick={toggle}>
                        <Text fw={600} fz={14} c="#0F172A">{selectedValue || 'Comments & Activities'}</Text>
                        <IconChevronDown size={16} className="text-[#64748B]" />
                    </div>
                ) : null}
                {commentDropdownOpened && (
                    <Select
                        variant="unstyled"
                        placeholder="Comments"
                        data={[translate('Only Comments'), translate('Only Activities'), translate('Comments & Activities')]}
                        style={{ width: '200px' }}
                        comboboxProps={{ transitionProps: { transition: 'pop', duration: 200 } }}
                        dropdownOpened={commentDropdownOpened}
                        onChange={(value) => { setSelectedValue(value); toggle(); }}
                    />
                )}
            </div>
            {selectedValue === 'Only Comments'         && <TaskComment task={task} selectedValue={selectedValue} />}
            {selectedValue === 'Only Activities'       && <TaskActivity task={task} selectedValue={selectedValue} />}
            {selectedValue === 'Comments & Activities' && <TaskCommentAndActivity task={task} selectedValue={selectedValue} />}
        </div>
    );

    // ── Actions menu ──────────────────────────────────────────────────────────
    const actionsMenu = task ? (
        task.parent === null ? (
            <TaskActionsMenu
                actions={['complete', 'changeSection', 'archive', 'delete', 'changeVisibility', 'duplicateTask', 'ganttTask']}
                isDrawer
                taskData={task}
            />
        ) : (
            <TaskActionsMenu
                actions={['convert', 'subtask-complete', 'ganttTask', 'delete']}
                isSubtask
                isDrawer
                taskData={task}
            />
        )
    ) : null;

    return (
        <TaskDrawer
            mode="edit"
            user={{ loggedInUser, loggedUserId }}
            projectPermissions={projectPermissions}
            members={members}
            task={task}
            taskObj={taskObj}
            onClose={() => dispatch(closeTaskEditDrawer())}
            onNameSave={handleNameSave}
            onDescriptionSave={handleDescriptionSave}
            onAttachmentUpload={handleAttachmentUpload}
            onAttachmentDelete={handleAttachmentDelete}
            onGanttToggle={handleGanttToggle}
            isGanttVisible={isVisibleGantt}
            localStartDate={localStartDate}
            localEndDate={localEndDate}
            attachmentsInit={task.attachments || []}
            actionsMenu={actionsMenu}
            editFields={editFields}
            subtasksSection={subtasksSection}
            commentsSection={commentsSection}
            isCompleted={isCompleted}
            isLoading={visible}
            showCreatedBy
            showGanttToggle
            buttonLabel={translate('Update')}
        />
    );
};

export default EditTaskDrawer;
