import { type FC, useId, useState } from 'react';

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

import HuAccordion from '@material-hu/components/design-system/Accordion';
import Button from '@material-hu/components/design-system/Buttons/Button';
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 HuSkeleton from '@material-hu/components/design-system/Skeleton';

import {
  type State,
  type Task,
} from 'src/pages/dashboard/serviceManagement/types';
import {
  getSla,
  getStateName,
  getStatusDetails,
} from 'src/pages/dashboard/serviceManagement/utils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { useModuleConfiguration } from '../../../contexts/ModuleConfigurationContext';
import { getPillProps } from '../../../general/StatusBadge';
import useAgentReassignment from '../../../hooks/useAgentReassignment';
import { useStateTransition } from '../hooks/useStateTransition';

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

export type ServiceInformationProps = {
  loading?: boolean;
  taskData?: Task;
  isAgentSide?: boolean;
};

const ServiceInformation: FC<ServiceInformationProps> = ({
  loading = false,
  taskData,
  isAgentSide = false,
}) => {
  const { t } = useLokaliseTranslation('service_management');
  const [anchorEl, setAnchorEl] = useState<HTMLButtonElement | null>(null);
  const isOpenStateChangeMenu = Boolean(anchorEl);
  const agentElemId = useId();

  const {
    states,
    isLoadingUpdate,
    isLoadingStates,
    showStateLoading,
    showStateTransitions,
    showAssignMe,
    terminalSureModal,
    handleUpdateState,
    handleAssignMe,
  } = useStateTransition({ taskData, isAgentSide });

  const {
    SingleAssignmentPopoverComponent,
    singleAssignmentConfirmationModal: confirmReassignModal,
    handleOpenSingleAssignmentMenu: handleOpenMenu,
  } = useAgentReassignment(null);

  const handleOpenReassignMenu = () => {
    const elem = document.getElementById(agentElemId);
    handleOpenMenu(elem, taskData!);
  };

  const {
    moduleQuery: { data: moduleConfiguration },
  } = useModuleConfiguration();

  const hasSlasConfigured = moduleConfiguration?.slaEnabled;
  const sla = taskData ? getSla(taskData.taskSlas, taskData.state) : null;

  const isTerminalState = !!taskData?.state?.terminal;
  const canReassign = isAgentSide && !taskData?.state?.terminal;
  const showStateRow = !isTerminalState && !loading;
  const showSla =
    !!taskData &&
    !!hasSlasConfigured &&
    taskData.taskSlas?.length > 0 &&
    isAgentSide &&
    sla != null;

  return (
    <Stack sx={{ height: '100%', overflow: 'auto' }}>
      {terminalSureModal}
      {confirmReassignModal}
      {showStateRow && (
        <Stack
          sx={{
            p: 2,
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'space-between',
          }}
        >
          <Typography
            variant="globalS"
            fontWeight="fontWeightSemiBold"
          >
            {t('status')}
          </Typography>
          {showAssignMe && (
            <Button
              variant="primary"
              onClick={handleAssignMe}
              loading={isLoadingUpdate || isLoadingStates}
            >
              {t('assign_me')}
            </Button>
          )}
          {showStateTransitions && (
            <>
              <StatusButton
                stateName={getStateName(taskData?.state.name!)}
                loading={showStateLoading}
                endIcon={<IconChevronDown />}
                onClick={e => setAnchorEl(e.currentTarget)}
              >
                <Typography
                  variant="globalXS"
                  fontWeight="fontWeightSemiBold"
                  sx={{
                    color: theme => theme.palette.new.text.neutral.inverted,
                  }}
                >
                  {t(
                    getStatusDetails(getStateName(taskData?.state.name!))
                      ?.title,
                  )}
                </Typography>
              </StatusButton>
              <HuMenu
                open={isOpenStateChangeMenu}
                anchorEl={anchorEl}
                onClose={() => setAnchorEl(null)}
                position="right"
              >
                {states?.map(state => (
                  <HuMenuItem
                    key={state.stateId}
                    onClick={() => {
                      handleUpdateState(state);
                      setAnchorEl(null);
                    }}
                  >
                    <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>
            </>
          )}
        </Stack>
      )}
      {loading && (
        <Stack
          sx={{ flexDirection: 'row', alignItems: 'center', gap: 1, p: 3 }}
        >
          <HuSkeleton
            variant="circular"
            width={40}
            height={35}
          />
          <HuSkeleton
            variant="text"
            width="100%"
            height={40}
          />
        </Stack>
      )}
      {!loading && (
        <Stack sx={{ gap: 2 }}>
          <HuAccordion
            title={t('service_information')}
            elevation={0}
            defaultExpanded={true}
            avatar={{ Icon: IconInbox }}
            customDetail={
              <Stack sx={{ gap: 2 }}>
                <Stack
                  sx={{
                    p: 2,
                    pr: 2,
                    borderRadius: 1,
                    backgroundColor: ({ palette }) =>
                      palette.new.background.layout.default,
                  }}
                >
                  <Typography
                    variant="globalS"
                    sx={{ wordBreak: 'break-word' }}
                  >
                    {taskData?.catalogItem?.description}
                  </Typography>
                </Stack>
                {taskData?.catalogItem?.category && (
                  <Stack
                    sx={{
                      p: 2,
                      pr: 1,
                      gap: 1,
                      borderRadius: 1,
                      backgroundColor: ({ palette }) =>
                        palette.new.background.layout.default,
                    }}
                  >
                    <Stack
                      sx={{
                        flexDirection: 'row',
                        justifyContent: 'space-between',
                        gap: 2,
                      }}
                    >
                      <Typography
                        variant="globalS"
                        fontWeight="fontWeightSemiBold"
                      >
                        {t('category')}
                      </Typography>
                      <Typography variant="globalS">
                        {taskData?.catalogItem?.category?.name}
                      </Typography>
                    </Stack>
                  </Stack>
                )}
              </Stack>
            }
          />
          <HuAccordion
            title={t('request_information')}
            elevation={0}
            defaultExpanded={true}
            avatar={{ Icon: IconStack2 }}
            customDetail={
              <RequestInfoDetail
                taskData={taskData!}
                agentElemId={agentElemId}
                canReassign={canReassign}
                showSla={showSla}
                handleOpenReassignMenu={handleOpenReassignMenu}
              />
            }
          />
        </Stack>
      )}
      {SingleAssignmentPopoverComponent}
    </Stack>
  );
};

export default ServiceInformation;
