
import React, { useState, useEffect, Fragment } from 'react';
import { IconGripVertical, IconPlus, IconTrash, IconDotsVertical, IconArchiveFilled, IconArchive } from '@tabler/icons-react';
import { useSelector, useDispatch } from 'react-redux';
import { useParams } from "react-router-dom";
import {
  createTaskSection, deleteTaskSection,
  editSectionSortOrder, editTaskSortOrder,
  fetchTasksByProject, updateChildColumns, updateColumns,
  updateOrdered, archiveSectionTask, fetchTasksBySection,
  updateTaskPriority, updateTaskStatus, updateTaskAssignee, updateTaskDueDate,
  completeTask, activateTask,
} from "../../../Settings/store/taskSlice";
import TaskSectionName from "./Task/TaskSectionName";
import { DragDropContext, Draggable, Droppable } from "react-beautiful-dnd";
import { reorder, reorderQuoteMap } from "./utils";
import TaskBoardContent from "./TaskBoardContent";
import SectionHeaderActions from './SectionHeaderActions';
import { modals } from "@mantine/modals";
import { Avatar, Button, Popover, Text, TextInput, Title, Tooltip, List, Flex } from "@mantine/core";
import { hasPermission, useProjectPermissions } from "../../../ui/permissions";
import AddTaskPopover from "./AddTaskPopover";
import { showNotification } from "@mantine/notifications";
import { updateInputFieldFocus } from "../../../../store/base/commonSlice";
import { useHotkeys } from '@mantine/hooks';

// Maps a due date bucket key to a concrete date string (used when dragging in duedate group-by)
const getNewDateForSection = (sectionKey) => {
  const today = new Date();
  const pad = (n) => String(n).padStart(2, '0');
  const fmt = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
  switch (sectionKey) {
    case 'today': return fmt(today);
    case 'next_seven_days': { const d = new Date(today); d.setDate(d.getDate() + 7); return fmt(d); }
    case 'upcoming': { const d = new Date(today); d.setDate(d.getDate() + 30); return fmt(d); }
    case 'no-date': return null;
    default: return null;
  }
};

const NO_PRIORITY_KEY = 'no-priority';
const NO_STATUS_KEY = 'no-status';
const NO_ASSIGNED_KEY = 'no-assigned';

const TaskBoard = ({ groupByType, columnLabels }) => {
  const { projectInfo, tasks, columns, ordered, taskListSections, childColumns, filterValues, projectPriorities, projectStatuses, boardMembers } = useSelector((state) => state.settings.task);
  const projectPermissions = useProjectPermissions(projectInfo?.id);
  const { loggedUserId } = useSelector((state) => state.auth.user)
  const { loggedInUser } = useSelector((state) => state.auth.session)

  const dispatch = useDispatch();
  const { id } = useParams();

  const [accordionItems, setAccordionItems] = useState([]);
  useEffect(() => {
    if (tasks && tasks.taskListSectionsName) {
      const transformedItems = Object.entries(tasks.taskListSectionsName).map(([key, value]) => ({
        value: key,
        title: value.name,
      }));
      setAccordionItems(transformedItems);
    }
  }, []);
  const userId = loggedInUser ? loggedInUser.loggedUserId : loggedUserId;

  useEffect(() => {
    // In group-by mode the wrapper component manages data loading; skip section auto-fetch
    if (groupByType) return;

    if (ordered && ordered.length > 0 && projectInfo?.id) {
      const search = filterValues?.name || '';
      ordered.forEach((sectionSlug) => {
        const section = taskListSections[sectionSlug];
        if (section?.id && !columns[sectionSlug]) {
          dispatch(fetchTasksBySection({
            projectId: projectInfo.id,
            sectionSlug: sectionSlug,
            limit: 15,
            offset: 0,
            append: true,
            search,
            userId,
          }));
        }
      });
    }
  }, [ordered, projectInfo?.id, filterValues?.name]);


  const [openAddTaskPopoverHotkey, setOpenAddTaskPopoverHotkey] = useState(false);
  useHotkeys([
    ['alt+n', () => {
      setOpenAddTaskPopoverHotkey(true);
      // Optionally, reset after a short delay so it can be triggered again
      setTimeout(() => setOpenAddTaskPopoverHotkey(false), 300);
    }]
  ]);


  const handleTitleChange = (e, itemValue) => {
    const newAccordionItems = accordionItems.map((item) => {
      if (item.value === itemValue) {
        return { ...item, title: e.target.value };
      }
      return item;
    });
    setAccordionItems(newAccordionItems);
  };


  const handleAddSection = () => {
    const newItemValue = `untitle-section-${accordionItems.length + 1}`;
    const newItem = {
      value: newItemValue,
      title: `Type section name here`,
    };
    setAccordionItems([...accordionItems, newItem]);

    const newSection = {
      name: 'Type section name here',
      project_id: projectInfo.id,
      sort_order: ordered.length + 1,
      created_by: loggedUserId
    }

    dispatch(createTaskSection(newSection));
    dispatch(updateInputFieldFocus(true));
  };

  const onDragEnd = (result) => {
    if (!result.destination) {
      return
    }

    const source = result.source
    const destination = result.destination

    if (
      source.droppableId === destination.droppableId &&
      source.index === destination.index
    ) {
      return
    }

    if (result.type === 'COLUMN') {
      // In group-by mode column order is fixed — no reordering
      if (groupByType) return;

      const newOrdered = reorder(ordered, source.index, destination.index)

      const submittedData = {
        orderedList: newOrdered,
        project_id: projectInfo.id
      }
      dispatch(editSectionSortOrder({ data: submittedData }))
      dispatch(updateOrdered(newOrdered))
      return
    }
    if (result.type === 'SUBTASK') {
      const data = reorderQuoteMap({
        quoteMap: childColumns,
        source,
        destination,
      })
      const updateColumnData = {
        ...childColumns,
        ...data.quoteMap,
      }
      const combineUpdateChildData = {
        ...result,
        updateColumnData
      }

      const submittedData = {
        orderedList: combineUpdateChildData,
        project_id: projectInfo.id,
        updated_by: loggedUserId
      }

      dispatch(editTaskSortOrder({ data: submittedData }))
      dispatch(updateChildColumns(updateColumnData))
      return
    }

    const sourceKey = source.droppableId;
    const destKey = destination.droppableId;

    // In group-by mode: handle cross-column drag as an attribute update
    if (groupByType && sourceKey !== destKey) {
      const sourceTasks = [...(columns?.[sourceKey] || [])];
      const [movedTask] = sourceTasks.splice(source.index, 1);
      if (!movedTask) return;

      const destTasks = [...(columns?.[destKey] || [])];
      destTasks.splice(destination.index, 0, movedTask);

      dispatch(updateColumns({ ...columns, [sourceKey]: sourceTasks, [destKey]: destTasks }));

      if (groupByType === 'priority') {
        const prioritiesWithNoPriority = [
          ...(projectPriorities || []),
          { id: NO_PRIORITY_KEY, name: 'No Priority', slug: NO_PRIORITY_KEY },
        ];
        const targetPriority = prioritiesWithNoPriority.find(p => p.slug === destKey);
        dispatch(updateTaskPriority({
          id: movedTask.id,
          data: {
            priority_id: targetPriority?.id === NO_PRIORITY_KEY ? null : targetPriority?.id,
            priority_name: targetPriority?.name || '',
            updated_by: userId,
          },
        }));
      } else if (groupByType === 'status') {
        const statusesWithNone = [
          ...(projectStatuses || []),
          { id: NO_STATUS_KEY, name: 'No Status', slug: NO_STATUS_KEY },
        ];
        const targetStatus = statusesWithNone.find(s => s.slug === destKey);
        const newStatusId = targetStatus?.id === NO_STATUS_KEY ? null : targetStatus?.id;
        dispatch(updateTaskStatus({
          id: movedTask.id,
          data: {
            status_id: newStatusId,
            status_name: targetStatus?.name || '',
            updated_by: userId,
          },
        }));
        const completeStatus = (projectStatuses || []).find(s => s.is_complete_status == 1);
        if (completeStatus && newStatusId === completeStatus.id) {
          // Dragged to the designated complete status → also complete the task
          dispatch(completeTask({
            id: movedTask.id,
            data: { project_id: projectInfo.id, type: 'task', updated_by: userId },
          }));
        } else if (movedTask.status === 'COMPLETED' && (!completeStatus || newStatusId !== completeStatus.id)) {
          // COMPLETED task dragged away from complete status → reopen with section picker
          const regularSections = Object.values(taskListSections || {}).filter(s => s.mark_is_complete === 'regular');
          modals.open({
            title: <Title order={5}>Select Section</Title>,
            centered: true,
            withCloseButton: true,
            children: (
              <Fragment>
                <Text size="sm" mb="md">Move this task to:</Text>
                {regularSections.map(section => (
                  <div
                    key={section.id}
                    className="cursor-pointer p-2 hover:bg-gray-100 rounded mb-1"
                    onClick={() => {
                      modals.closeAll();
                      dispatch(activateTask({
                        id: movedTask.id,
                        data: { project_id: projectInfo.id, task_section_id: section.id, updated_by: userId },
                      }));
                    }}
                  >
                    <Text size="sm">{section.name}</Text>
                  </div>
                ))}
              </Fragment>
            ),
          });
        }
      } else if (groupByType === 'member') {
        dispatch(updateTaskAssignee({
          id: movedTask.id,
          data: {
            assignee_id: destKey === NO_ASSIGNED_KEY ? null : destKey,
            updated_by: userId,
          },
        }));
      } else if (groupByType === 'duedate') {
        if (destKey === 'overdue') return;
        dispatch(updateTaskDueDate({
          id: movedTask.id,
          data: {
            end_date: getNewDateForSection(destKey),
            updated_by: userId,
          },
        }));
      }
      return;
    }

    const data = reorderQuoteMap({
      quoteMap: columns,
      source,
      destination,
    })
    const updateColumnData = {
      ...columns,
      ...data.quoteMap,
    }
    const combineUpdateData = {
      ...result,
      updateColumnData
    }

    const submittedData = {
      orderedList: combineUpdateData,
      project_id: projectInfo.id,
      updated_by: loggedUserId
    }

    dispatch(editTaskSortOrder({ data: submittedData }))
    dispatch(updateColumns(updateColumnData))

    // Sync status badge when dragging to/from the designated complete section
    const completeStatus = projectStatuses?.find(s => s.is_complete_status == 1);
    if (completeStatus && sourceKey !== destKey) {
      const movedTask = columns[sourceKey][source.index];
      const destSection = taskListSections[destKey];
      const srcSection = taskListSections[sourceKey];
      const movedTaskSubtasks = childColumns?.[movedTask.slug] || [];
      if (destSection?.mark_is_complete === 'complete') {
        dispatch(updateTaskStatus({ id: movedTask.id, data: { status_id: completeStatus.id, updated_by: userId } }));
        movedTaskSubtasks.forEach(subtask => {
          dispatch(updateTaskStatus({ id: subtask.id, data: { status_id: completeStatus.id, updated_by: userId } }));
        });
      } else if (srcSection?.mark_is_complete === 'complete') {
        dispatch(updateTaskStatus({ id: movedTask.id, data: { status_id: null, updated_by: userId } }));
        movedTaskSubtasks.forEach(subtask => {
          dispatch(updateTaskStatus({ id: subtask.id, data: { status_id: null, updated_by: userId } }));
        });
      }
    }

  };

  // In group-by mode, derive column order from columnLabels keys to avoid stale
  // state.ordered (from a previous section-based view) causing gibberish headers
  // on the first render before the wrapper's useEffect fires updateOrdered.
  const effectiveOrdered = (groupByType && columnLabels)
    ? Object.keys(columnLabels)
    : ordered;

  return (
    <Fragment>

      <div className="project-cards flex flex-row flex-nowrap gap-4 pe-4 pb-4">
        {effectiveOrdered && effectiveOrdered.length > 0 &&
          <div className="sections-wrapper">
            <DragDropContext onDragEnd={(result) => onDragEnd(result)}>
              <Droppable
                droppableId="droppable"
                type="COLUMN"
                direction="horizontal"
              >
                {(provided) => (
                  <div
                    {...provided.droppableProps}
                    ref={provided.innerRef}
                    className="accordion-sortable flex items-stretch flex-nowrap gap-4 w-auto overflow-x-auto"
                  >
                    {effectiveOrdered && effectiveOrdered.length > 0 && effectiveOrdered.map((taskListSection, index) => {
                      const isDesignatedComplete = !groupByType && taskListSections[taskListSection]?.mark_is_complete === 'complete';
                      return (
                      <Draggable key={taskListSection} draggableId={taskListSection} index={index}>
                        {(provided, snapshot) => (
                          <div
                            key={taskListSection}
                            className="flex-1 projects-card-content w-[310px]"
                            ref={provided.innerRef}
                            {...provided.draggableProps}
                          >
                            <div {...(groupByType ? {} : provided.dragHandleProps)}
                              className="project-section-title px-3 py-2 flex items-center justify-between border-b border-gray-200 rounded-t-lg"
                              style={{
                                backgroundColor: isDesignatedComplete ? '#E8F5E9' : '#EBF1F4',
                                borderLeft: isDesignatedComplete ? '4px solid #4CAF50' : undefined,
                              }}>
                              {groupByType && columnLabels ? (
                                <div className="flex gap-2 items-center">
                                  {columnLabels[taskListSection]?.color && (
                                    <span
                                      className="inline-block w-3 h-3 rounded-full shrink-0"
                                      style={{ backgroundColor: columnLabels[taskListSection].color }}
                                    />
                                  )}
                                  <span className="font-semibold text-sm text-gray-800 truncate">
                                    {columnLabels[taskListSection]?.name || taskListSection}
                                  </span>
                                  <span className="text-xs text-gray-400">
                                    {(columns?.[taskListSection] || []).length}
                                  </span>
                                </div>
                              ) : (
                                <>
                                  <div className="flex gap-1 items-center">
                                    <IconGripVertical
                                      size={20}
                                      stroke={1.25}
                                      className="mr-1 cursor-move" />
                                    <TaskSectionName
                                      taskSectionId={taskListSections[taskListSection] && taskListSections[taskListSection].id}
                                      nameOfTaskSection={taskListSections[taskListSection] && taskListSections[taskListSection].name}
                                      view="cardView"
                                    />
                                  </div>

                                  <div className="flex items-center justify-between cursor-pointer mr-[-5px]">
                                    {hasPermission(loggedInUser, ['create-task', 'config-project', 'manage-section', 'delete-section', 'add-remove-section-to-gantt'], projectPermissions, 'project') &&
                                      <SectionHeaderActions
                                        taskSection={taskListSections[taskListSection]}
                                        taskListSection={taskListSection}
                                      />
                                    }
                                  </div>
                                </>
                              )}
                            </div>
                            <div className="flex items-center"
                              style={{ height: 'calc(100% - 60px)', minHeight: '350px' }}>
                              <TaskBoardContent
                                className={snapshot.isDragging ? 'is-dragging' : ''}
                                listType="CONTENT"
                                snapshot={snapshot}
                                ref={provided.innerRef}
                                view="cardView"
                                taskSection={taskListSection}
                                contents={columns && columns && columns[taskListSection] ? columns[taskListSection] : []}
                              />
                            </div>
                          </div>
                        )}

                      </Draggable>
                      );
                    })}
                    {provided.placeholder}
                  </div>
                )}
              </Droppable>
            </DragDropContext>

          </div>
        }
        {!groupByType && hasPermission(loggedInUser, ['manage-section'], projectPermissions, 'project') &&
          <div style={{ minHeight: '335px', maxHeight: '700px' }} className={`w-[60px] min-w-[60px] shrink-0 rounded-md border border-dashed border-[#ED7D31] flex items-center justify-center transition-colors bg-transparent hover:bg-[#fff6ef]`}>
            <button
              className="w-full h-full cursor-pointer flex items-center justify-center"
              onClick={handleAddSection}
            >
              <span style={{ writingMode: 'vertical-rl', transform: 'rotate(180deg)' }} className="text-lg tracking-widest font-bold text-[#ED7D31] whitespace-nowrap">
                + Add Section
              </span>
            </button>
          </div>
        }
      </div>


    </Fragment>
  );
};

export default TaskBoard;




