import React, { useState } from 'react';
import { IconCheck } from '@tabler/icons-react';
import { Tooltip } from '@mantine/core';
import { useDispatch, useSelector } from 'react-redux';
import dayjs from 'dayjs';
import { notifications } from '@mantine/notifications';
import { editTask } from '../../../../Settings/store/taskSlice';
import { hasPermission, useProjectPermissions } from '../../../../ui/permissions';
import DueDatePicker from '../../../../ui/DueDatePicker';
import { translate } from '../../../../../utils/i18n';

const TaskDueDate = ({ taskId, startDate, dueDate, startDateIsVisible, dueDateIsVisible, isSubtask, isDrawer, disabled, view, onDateUpdate, createdBy_id, assignedTo_id }) => {
  const dispatch = useDispatch();
  const { loggedUserId } = useSelector((state) => state.auth.user);
  const { loggedInUser } = useSelector((state) => state.auth.session);
  const { projectInfo } = useSelector((state) => state.settings.task);
  const projectPermissions = useProjectPermissions(projectInfo?.id);
  const [isSaving, setIsSaving] = useState(false);
  const [isClearing, setIsClearing] = useState(false);

  // Check permission — creator/assignee bypass
  const isCreatorOrAssignee = (createdBy_id != null && createdBy_id == loggedUserId) ||
    (assignedTo_id != null && assignedTo_id == loggedUserId);
  const hasAccess = isCreatorOrAssignee || hasPermission(loggedInUser, ['manage-tasks-by-others'], projectPermissions, 'project');
  const isDisabled = disabled || !hasAccess;

  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(editTask({
      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) {
        if (typeof onDateUpdate === 'function') {
          const savedStart = showStart ? dayjs(start).format('YYYY-MM-DD') : null;
          const savedEnd = showEnd ? dayjs(end).format('YYYY-MM-DD') : null;
          onDateUpdate(savedStart, savedEnd, showStart, showEnd);
        }
        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(editTask({
      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) {
        if (typeof onDateUpdate === 'function') onDateUpdate(null, null);
        notifications.show({
          color: 'green',
          title: 'Success',
          message: 'Due date cleared successfully.',
          icon: <IconCheck />,
          autoClose: 5000,
        });
      }
    }).finally(() => setIsClearing(false));
  };

  const picker = (
    <DueDatePicker
      dueDate={dueDate}
      startDate={startDate}
      startDateIsVisible={startDateIsVisible}
      dueDateIsVisible={dueDateIsVisible}
      disabled={isDisabled}
      showStartDateInPill={isDrawer || view === 'cardView'}
      withinPortal={true}
      singleDateStartOffset={0}
      onSave={handleSave}
      onClear={handleClear}
      isSaving={isSaving}
      isClearing={isClearing}
    />
  );

  const tooltipLabel = hasAccess
    ? translate('Due Date')
    : `${translate('Due Date')}: ${translate('Only the task creator or assignee can perform this action')}`;

  return (
    <Tooltip label={tooltipLabel} position="top" withArrow>
      <span>{picker}</span>
    </Tooltip>
  );
};

export default TaskDueDate;
