import React, { useState } from 'react';
import { IconCheck } from '@tabler/icons-react';
import { useDispatch, useSelector } from 'react-redux';
import dayjs from 'dayjs';
import { notifications } from '@mantine/notifications';
import { editMyTask } from '../../Settings/store/myTaskSlice';
import { hasPermission } from '../../ui/permissions';
import DueDatePicker from '../../ui/DueDatePicker';

const TaskDueDate = ({ task, taskId, startDate, dueDate, startDateIsVisible, dueDateIsVisible, isSubtask, isDrawer }) => {
  const dispatch = useDispatch();
  const { loggedUserId } = useSelector((state) => state.auth.user);
  const { loggedInUser } = useSelector((state) => state.auth.session);
  const [isSaving, setIsSaving] = useState(false);
  const [isClearing, setIsClearing] = useState(false);

  // MyTask permissions come from the task object, not from Redux projectInfo
  const projectPermissions = task?.project?.permissions?.permissions ?? [];
  const isCreatorOrAssignee = task && (task.createdBy_id == loggedInUser?.loggedUserId || task.assignedTo_id == loggedInUser?.loggedUserId);
  const hasAccess = isCreatorOrAssignee || hasPermission(loggedInUser, ['manage-tasks-by-others'], projectPermissions, 'project');

  const handleSave = (dateData) => {
    if (!taskId || taskId === 'undefined') return;
    if (!dateData?.dates?.[0] || !dateData?.dates?.[1]) return;

    const [start, end] = dateData.dates;
    const { startDateIsVisible: showStart, dueDateIsVisible: showEnd } = dateData.visibility;

    setIsSaving(true);
    return dispatch(editMyTask({
      id: taskId,
      data: {
        start_date: showStart ? dayjs(start).format('YYYY-MM-DD') : (showEnd ? dayjs(end).format('YYYY-MM-DD') : 'empty'),
        start_date_is_visible: showStart ? 1 : 0,
        end_date: showEnd ? dayjs(end).format('YYYY-MM-DD') : 'empty',
        end_date_is_visible: showEnd ? 1 : 0,
        updated_by: loggedInUser ? loggedInUser.loggedUserId : loggedUserId,
      },
    })).then((response) => {
      if (response.payload?.status === 200) {
        notifications.show({
          color: 'green',
          title: 'Success',
          message: 'Due date updated successfully.',
          icon: <IconCheck />,
          autoClose: 5000,
        });
      }
      return response;
    }).finally(() => setIsSaving(false));
  };

  const handleClear = () => {
    if (!taskId || taskId === 'undefined') return;

    setIsClearing(true);
    dispatch(editMyTask({
      id: taskId,
      data: {
        start_date: 'empty',
        start_date_is_visible: 0,
        end_date: 'empty',
        end_date_is_visible: 0,
        updated_by: loggedInUser ? loggedInUser.loggedUserId : loggedUserId,
      },
    })).then((response) => {
      if (response.payload?.status === 200) {
        notifications.show({
          color: 'green',
          title: 'Success',
          message: 'Due date cleared successfully.',
          icon: <IconCheck />,
          autoClose: 5000,
        });
      }
    }).finally(() => setIsClearing(false));
  };

  return (
    <DueDatePicker
      dueDate={dueDate}
      startDate={startDate}
      startDateIsVisible={startDateIsVisible}
      dueDateIsVisible={dueDateIsVisible}
      disabled={!hasAccess}
      showStartDateInPill={false}
      withinPortal={false}
      singleDateStartOffset={-1}
      onSave={handleSave}
      onClear={handleClear}
      isSaving={isSaving}
      isClearing={isClearing}
    />
  );
};

export default TaskDueDate;
