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

import Stack from '@material-hu/mui/Stack';

import { EVENTS_SOCKETS } from 'src/constants/sockets';
import { useSocket } from 'src/contexts/SocketContext';
import { getForm } from 'src/pages/dashboard/serviceManagement/services';
import {
  ServiceItemTypes,
  type Task,
} from 'src/pages/dashboard/serviceManagement/types';
import { isApprovalTask } from 'src/pages/dashboard/serviceManagement/utils';

import useTaskCommentsUpdater from '../../../hooks/useTaskCommentsUpdater';
import { serviceManagementKeys } from '../../../queries';

import Activities from './Activities';
import Comments from './Comments';
import FormAnswer from './FormAnswer';

type RequestTabProps = {
  taskData: Task;
  isAgentSide: boolean;
  loading: boolean;
};

const RequestTab: FC<RequestTabProps> = ({
  taskData,
  isAgentSide,
  loading,
}) => {
  const socket = useSocket();
  const [showCommentsBubble, setShowCommentsBubble] = useState(false);
  const [showUnreadMessage, setShowUnreadMessage] = useState(true);
  const task = isApprovalTask(taskData)
    ? ({
        ...taskData?.parentTask,
        state: taskData?.state,
        type: ServiceItemTypes.APPROVAL,
        approvalGroupTask: taskData?.approvalGroupTask,
      } as Task)
    : taskData;

  const source = !isApprovalTask(taskData) ? taskData : taskData?.parentTask;
  const { catalogItem, formAnswerId, formAnswerToken } = source ?? {};

  /* Form answers are immutable — staleTime: Infinity prevents unnecessary
     refetches on tab switches, so an expired cached token never reaches the server. */
  const { data: formData, isLoading: loadingFormData } = useQuery(
    [serviceManagementKeys.form.detail(catalogItem?.formTag!), formAnswerId],
    () => getForm(catalogItem?.formTag!, formAnswerId!, formAnswerToken!),
    {
      enabled:
        !!taskData &&
        !!catalogItem?.formTag &&
        !!formAnswerId &&
        !!formAnswerToken,
      select: response => response.data,
      keepPreviousData: true,
      staleTime: Infinity,
    },
  );

  /* Comments socket updater */
  useTaskCommentsUpdater({
    socket,
    event: EVENTS_SOCKETS.SERVICE_MANAGER_TASK_NEW_COMMENT,
    callback: () => {
      setShowCommentsBubble(true);
      setShowUnreadMessage(true);
    },
  });

  return (
    <Stack sx={{ flexDirection: 'row', height: '100%', overflow: 'hidden' }}>
      <Stack
        sx={{
          flex: 1,
          borderRight: theme =>
            `1px solid ${theme.palette.new.border.neutral.divider}`,
          minWidth: {
            xs: '200px',
            md: '200px',
            xl: '400px',
          },
        }}
      >
        <FormAnswer
          key={task?.id}
          formData={formData}
          loading={loadingFormData || loading}
          isAgentSide={isAgentSide}
          taskData={task}
        />
      </Stack>
      <Stack
        sx={{
          flex: 2,
          overflow: 'hidden',
        }}
      >
        <Comments
          isAgentSide={isAgentSide}
          task={task}
          showBubble={showCommentsBubble}
          setShowBubble={setShowCommentsBubble}
          showUnreadMessage={showUnreadMessage}
          setShowUnreadMessage={setShowUnreadMessage}
        />
      </Stack>
      {!isAgentSide && (
        <Stack
          sx={{
            flex: 1,
            borderLeft: theme =>
              `1px solid ${theme.palette.new.border.neutral.divider}`,
          }}
        >
          <Activities
            taskData={task}
            isAgentSide={isAgentSide}
          />
        </Stack>
      )}
    </Stack>
  );
};

export default RequestTab;
