import { useState } from 'react';
import { useMutation, useQuery } from 'react-query';

import { IconChevronDown } from '@material-hu/icons/tabler';
import Button from '@material-hu/mui/Button';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import HTMLBody from '@material-hu/components/composed-components/HTMLBody';
import Accordion from '@material-hu/components/design-system/Accordion';
import Avatar from '@material-hu/components/design-system/Avatar';
import Link from '@material-hu/components/design-system/Link';
import HuMenu from '@material-hu/components/design-system/Menu';
import HuMenuItem from '@material-hu/components/design-system/Menu/components/MenuItem';
import HuPills from '@material-hu/components/design-system/Pills';

import { useAuth } from 'src/contexts/JWTContext';
import {
  getTransitionsStates,
  updateState,
} from 'src/pages/dashboard/serviceManagement/services';
import {
  type State,
  type StateTransition,
  type Task,
} from 'src/pages/dashboard/serviceManagement/types';
import {
  getStateName,
  getStatusDetails,
  getTaskID,
} from 'src/pages/dashboard/serviceManagement/utils';
import { formatLocalizedDate } from 'src/utils/date';
import { useLokaliseTranslation } from 'src/utils/i18n';

import StatusBadge, { getPillProps } from '../../../general/StatusBadge';
import { serviceManagementKeys } from '../../../queries';
import { serviceManagementRoutes } from '../../../routes';
import { getUserDisplayName } from '../../../utils';

import UserTooltip from './Information/UserTooltip';
import StatusButton from './StatusButton';

const USERNAME_MAX_WIDTH = 200; // px

type SubtaskDrawerProps = {
  parentData: any;
  taskData: Task;
  showParentTask?: boolean;
  onClose: () => void;
};

const SubtaskDetailDrawer = ({
  parentData,
  taskData,
  showParentTask = false,
}: SubtaskDrawerProps) => {
  const { t } = useLokaliseTranslation('service_management');
  const { user: loggedUser } = useAuth();
  const [anchorEl, setAnchorEl] = useState<HTMLButtonElement | null>(null);
  const [currentState, setCurrentState] = useState<State | undefined>(
    taskData?.state,
  );
  const isOpenStateChangeMenu = Boolean(anchorEl);

  const handleOpenStateChangeMenu = (
    event: React.MouseEvent<HTMLButtonElement>,
  ) => {
    setAnchorEl(event.currentTarget);
  };

  const handleCloseStateChangeMenu = () => {
    setAnchorEl(null);
  };

  const { data: states, isLoading: isLoadingStates } = useQuery(
    serviceManagementKeys.states.list(currentState?.id ?? ''),
    () => getTransitionsStates(currentState?.id ?? ''),
    {
      enabled: !!currentState?.id,
      select: response => response.data,
    },
  );

  const { mutate: update, isLoading: isLoadingUpdate } = useMutation(
    (body: { stateId?: string }) => updateState(taskData.id, body),
    {
      onSuccess: response => {
        const newState = response.data.state;
        if (newState) {
          setCurrentState(newState);
        }
      },
    },
  );

  const handleUpdateState = (newState: StateTransition) => {
    update({
      stateId: newState.stateId,
    });
  };

  const isCurrentUserAgent = loggedUser?.id === taskData?.assignee?.id;
  const isTerminalState = currentState?.terminal;
  const canChangeState = isCurrentUserAgent && !isTerminalState;

  return (
    <Stack sx={{ gap: 2, p: 1 }}>
      <Stack
        sx={{
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
          backgroundColor: theme =>
            theme.palette?.new.background?.layout?.default,
          p: 2,
          borderRadius: 1,
        }}
      >
        <Typography
          variant="globalS"
          fontWeight="fontWeightSemiBold"
        >
          {t('status')}
        </Typography>
        {canChangeState ? (
          <>
            <StatusButton
              stateName={getStateName(currentState?.name ?? '')}
              loading={isLoadingUpdate || isLoadingStates}
              endIcon={<IconChevronDown />}
              onClick={handleOpenStateChangeMenu}
            >
              <Typography
                variant="globalXS"
                fontWeight="fontWeightSemiBold"
                sx={{ color: theme => theme.palette.new.text.neutral.inverted }}
              >
                {t(
                  getStatusDetails(getStateName(currentState?.name ?? ''))
                    ?.title,
                )}
              </Typography>
            </StatusButton>
            <HuMenu
              open={isOpenStateChangeMenu}
              anchorEl={anchorEl}
              onClose={handleCloseStateChangeMenu}
              position="right"
            >
              {states?.map(state => (
                <HuMenuItem
                  key={state.stateId}
                  onClick={() => {
                    handleUpdateState(state);
                    handleCloseStateChangeMenu();
                  }}
                >
                  <Stack
                    sx={{
                      cursor: 'pointer',
                      flexDirection: 'row',
                      alignItems: 'center',
                      gap: 1,
                    }}
                  >
                    <Typography
                      variant="globalS"
                      fontWeight="fontWeightSemiBold"
                    >
                      {t('send_to')} →
                    </Typography>
                    <HuPills
                      label={t(
                        getStatusDetails(getStateName(state.stateName))?.title,
                      )}
                      sx={{ cursor: 'pointer !important' }}
                      type={
                        getPillProps({
                          id: state.stateId,
                          name: state.stateName,
                          terminal: false,
                        } as State).type
                      }
                      size="medium"
                      hasIcon={false}
                    />
                  </Stack>
                </HuMenuItem>
              ))}
            </HuMenu>
          </>
        ) : (
          <StatusBadge state={currentState ?? undefined} />
        )}
      </Stack>
      <Stack
        sx={{
          backgroundColor: theme =>
            theme.palette?.new.background?.layout?.default,
          borderRadius: 1,
          p: 2,
          gap: 3,
        }}
      >
        <Stack
          sx={{
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'space-between',
          }}
        >
          <Typography
            variant="globalS"
            fontWeight="fontWeightSemiBold"
          >
            {t('number')}
          </Typography>
          <Typography variant="globalS">{getTaskID(taskData)}</Typography>
        </Stack>
        <Stack
          sx={{
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'space-between',
          }}
        >
          <Typography
            variant="globalS"
            fontWeight="fontWeightSemiBold"
          >
            {t('subtasks.request_date')}
          </Typography>
          <Typography variant="globalS">
            {formatLocalizedDate(taskData?.createdAt || '', {
              includeTime: true,
            })}
          </Typography>
        </Stack>
        {taskData?.parentTask?.initiator && (
          <Stack
            sx={{
              width: '100%',
              gap: 1,
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
            }}
          >
            <Typography
              variant="globalS"
              fontWeight="fontWeightSemiBold"
            >
              {t('requester')}
            </Typography>
            <UserTooltip
              user={taskData?.parentTask?.initiator}
              tooltipProps={{ direction: 'left' }}
            >
              <Button sx={{ cursor: 'default' }}>
                <Stack
                  sx={{
                    flexDirection: 'row',
                    alignItems: 'center',
                    gap: 1,
                    cursor: 'pointer',
                  }}
                >
                  <Avatar
                    sx={{
                      width: '28px',
                      height: '28px',
                    }}
                    src={taskData?.parentTask?.initiator?.profilePicture}
                  />
                  <Typography
                    variant="globalXS"
                    sx={{
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      whiteSpace: 'nowrap',
                      maxWidth: USERNAME_MAX_WIDTH,
                      display: 'inline-block',
                    }}
                  >
                    {getUserDisplayName(
                      taskData?.parentTask?.initiator,
                      loggedUser,
                      t,
                    )}
                  </Typography>
                </Stack>
              </Button>
            </UserTooltip>
          </Stack>
        )}
        {showParentTask && (
          <Stack
            sx={{
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
            }}
          >
            <Typography
              variant="globalS"
              fontWeight="fontWeightSemiBold"
            >
              {t('subtasks.request')}
            </Typography>
            <Link
              href={`${serviceManagementRoutes.agentSide.detail(
                parentData?.parentTask?.id ?? '',
              )}?tab=tasks`}
              target="_blank"
              hasIcon={true}
            >
              {getTaskID(parentData?.parentTask)}
              {' • '}
              {parentData?.parentTask?.catalogItem?.name}
            </Link>
          </Stack>
        )}
      </Stack>
      <Stack
        sx={{
          p: 2,
          pr: 1,
          gap: 1,
          borderRadius: 1,
          backgroundColor: theme =>
            theme.palette?.new.background?.layout?.default,
        }}
      >
        <Stack sx={{ gap: 2 }}>
          {taskData?.assignee && (
            <Stack
              sx={{
                width: '100%',
                gap: 1,
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'space-between',
              }}
            >
              <Typography
                variant="globalS"
                fontWeight="fontWeightSemiBold"
              >
                {t('agent')}
              </Typography>
              <UserTooltip
                user={taskData?.assignee}
                tooltipProps={{ direction: 'left' }}
              >
                <Button sx={{ cursor: 'default' }}>
                  <Stack
                    sx={{
                      flexDirection: 'row',
                      alignItems: 'center',
                      gap: 1,
                    }}
                  >
                    <Avatar
                      sx={{
                        width: '28px',
                        height: '28px',
                      }}
                      src={taskData?.assignee?.profilePicture}
                    />
                    <Typography
                      variant="globalXS"
                      sx={{
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap',
                        maxWidth: USERNAME_MAX_WIDTH,
                        cursor: 'default',
                        display: 'inline-block',
                      }}
                    >
                      {getUserDisplayName(taskData?.assignee, loggedUser, t)}
                    </Typography>
                  </Stack>
                </Button>
              </UserTooltip>
            </Stack>
          )}
        </Stack>
      </Stack>
      {taskData?.description && (
        <Stack
          sx={{
            p: 2,
            gap: 1,
            borderRadius: 1,
            backgroundColor: theme =>
              theme.palette?.new.background?.layout?.default,
          }}
        >
          <Accordion
            title={t('description')}
            elevation={0}
            defaultExpanded={true}
            hasPadding={false}
            customDetail={
              <Stack sx={{ py: 1 }}>
                <Typography
                  variant="globalS"
                  sx={{ wordBreak: 'break-word' }}
                >
                  <HTMLBody body={taskData?.description} />
                </Typography>
              </Stack>
            }
            sx={{
              backgroundColor: theme =>
                theme.palette?.new.background?.layout?.default,
            }}
          />
        </Stack>
      )}
    </Stack>
  );
};

export default SubtaskDetailDrawer;
