import { type FC } from 'react';
import { useFormContext } from 'react-hook-form';
import { useMutation } from 'react-query';

import { ParticipantView, useCallStateHooks } from '@stream-io/video-react-sdk';
import { useModal } from '@material-hu/hooks/useModal';
import { IconId, IconMovieOff, IconTrash } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import HuDialog from '@material-hu/components/design-system/Dialog';
import HuList from '@material-hu/components/design-system/List';
import HuListItem from '@material-hu/components/design-system/List/components/ListItem';

import useGeneralError from 'src/hooks/useGeneralError';
import {
  Configuration,
  ShareScreenStatus,
  StreamStatus,
  TrackType,
  UserTypeStream,
  VideoOrigin,
} from 'src/types/stream';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { HOST_SIDEBAR_WIDTH } from '../../constants';
import { useStreamDestination } from '../../hooks/useStreamDestination';
import { Background } from '../../ViewerPlayer';
import CustomVideoPlaceholder from '../../ViewerPlayer/CustomVideoPlaceholder';

import CustomParticipantView from './CustomParticipantView';
import ShareScreenControls from './controls/ShareScreenControls';
import FormConfigurationLiveStream from './FormConfiguration';
import HostInterationsUsers from './HostInteractionsUsers';

type HostContentProps = {
  postId?: number;
  streamId: string;
  streamStatus: StreamStatus;
  activeStep: Configuration;
  onReady: () => void;
};
const propertiesToHideVideo = {
  position: 'absolute',
  visibility: 'hidden',
  width: 0,
  height: 0,
};

const HostContent: FC<HostContentProps> = props => {
  const { postId, streamId, streamStatus, activeStep, onReady } = props;
  const { t } = useLokaliseTranslation(['livestream', 'general']);
  const { useParticipants, useScreenShareState } = useCallStateHooks();
  const { status } = useScreenShareState();
  const { watch } = useFormContext();
  const { actions: destinationActions, details: destinationDetails } =
    useStreamDestination();
  const participants = useParticipants();
  const showGeneralError = useGeneralError();
  const theme = useTheme();

  const { videoOrigin } = watch();
  const isFinish = streamStatus === StreamStatus.Finished;
  const isConfiguration = activeStep === Configuration.CONFIGURATION;
  const isStreaming = streamStatus === StreamStatus.Streaming;

  const goToPostDetail = (id: number) => destinationActions.viewPost(id);

  const deleteMutation = useMutation(
    (variables: { id: number }) => destinationActions.deletePost(variables.id),
    {
      onSuccess: () => {
        destinationActions.goToDestination();
      },
      onError: err => {
        showGeneralError(err, t('ERROR_DELETE_POST'));
      },
    },
  );

  const handleAcceptDialog = (id: number) => deleteMutation.mutate({ id });

  const isSoftwareStreamConnected = participants.some(participant =>
    participant.userId.split('-').includes(UserTypeStream.RTMP),
  );

  const softwareStreamingDisconnected =
    videoOrigin === VideoOrigin.SOFTWARE_STREAMING &&
    !isSoftwareStreamConnected;

  const softwareParticipant =
    videoOrigin === VideoOrigin.SOFTWARE_STREAMING &&
    participants.find(participant =>
      participant.userId.split('-').includes(UserTypeStream.RTMP),
    );

  const hostParticipant = participants.find(
    participant =>
      !participant.userId.split('-').includes(UserTypeStream.VIEWER) &&
      !participant.userId.split('-').includes(UserTypeStream.RTMP),
  );

  const {
    modal: deleteModal,
    showModal: showDeleteModal,
    closeModal: closeDeleteModal,
  } = useModal(
    ({ id }: { id: number }) => (
      <HuDialog
        onClose={closeDeleteModal}
        title={t('DELETE_VIDEO_TITLE')}
        textBody={t('DELETE_VIDEO_DESCRIPTION')}
        primaryButtonProps={{
          children: t('general:delete'),
          onClick: () => {
            handleAcceptDialog(id);
            closeDeleteModal();
          },
        }}
        secondaryButtonProps={{
          children: t('general:cancel'),
          onClick: closeDeleteModal,
        }}
      />
    ),
    {
      onClose: () => closeDeleteModal(),
    },
  );

  return (
    <Stack
      sx={{
        flex: 1,
        ml: HOST_SIDEBAR_WIDTH,
        py: theme.spacing(4),
        gap: theme.spacing(3),
        alignItems: 'center',
        height: '100%',
        overflow: 'hidden',
        '& .str-video__participant-view': {
          aspectRatio: 16 / 9,
          '& .str-video__video': {
            objectFit:
              status === ShareScreenStatus.ENABLED ? 'contain' : 'cover',
          },
        },
        '& .str-video__participant-view--speaking': {
          outline: 'none',
        },
      }}
    >
      {isFinish && postId && (
        <HuCardContainer
          sx={{
            width: '80%',
            py: theme.spacing(1),
          }}
        >
          <Typography
            variant="globalM"
            fontWeight="fontWeightSemiBold"
          >
            {t('QUICK_ACTIONS')}
          </Typography>
          <HuList sx={{ mt: theme.spacing(2) }}>
            {!destinationDetails?.hideViewPostButton && (
              <HuListItem
                text={{
                  title: t('SEE_POST'),
                }}
                avatar={{
                  Icon: IconId,
                  color: 'primary',
                }}
                onClick={() => goToPostDetail(postId)}
                sx={{
                  '& .MuiListItemButton-root': {
                    p: 0,
                    mb: theme.spacing(2),
                    borderRadius: 1,
                  },
                }}
              />
            )}
          </HuList>
          <HuList>
            <HuListItem
              text={{
                title: t('DELETE_POST'),
              }}
              avatar={{
                Icon: IconTrash,
                color: 'primary',
              }}
              onClick={() => showDeleteModal({ id: postId })}
              sx={{
                '& .MuiListItemButton-root': {
                  p: 0,
                  borderRadius: 1,
                },
              }}
            />
          </HuList>
        </HuCardContainer>
      )}
      <HuCardContainer
        sx={{
          width: '80%',
          '& .str-video__participant-view': {
            borderRadius: 2,
          },
          py: 1,
          ...(isConfiguration && propertiesToHideVideo),
        }}
      >
        {!isFinish && hostParticipant && (
          <ParticipantView
            trackType={
              status === ShareScreenStatus.ENABLED
                ? TrackType.SCREEN_SHARE_TRACK
                : TrackType.VIDEO_TRACK
            }
            participant={
              videoOrigin === VideoOrigin.SOFTWARE_STREAMING &&
              softwareParticipant
                ? softwareParticipant
                : hostParticipant
            }
            VideoPlaceholder={propsVideoPlaceholder => (
              <CustomVideoPlaceholder
                isConnectSoftwareStreaming={softwareStreamingDisconnected}
                {...propsVideoPlaceholder}
              />
            )}
            ParticipantViewUI={
              <CustomParticipantView
                activeStep={activeStep}
                streamStatus={streamStatus}
                onReady={onReady}
                isConnectSoftwareStreaming={softwareStreamingDisconnected}
                isSoftwareStreamConnected={isSoftwareStreamConnected}
              />
            }
          />
        )}
        {isStreaming && videoOrigin !== VideoOrigin.SOFTWARE_STREAMING && (
          <ShareScreenControls />
        )}
        {isFinish && (
          <Background
            sx={{
              aspectRatio: 16 / 9,
              width: '100%',
              height: '100%',
              background: theme.palette.new.background.elements.inverted,
            }}
          >
            <IconMovieOff color={theme.palette.new.text.neutral.inverted} />
            <Typography
              variant="globalS"
              fontWeight="fontWeightSemiBold"
              color="new.text.neutral.inverted"
            >
              {t('YOUR_LIVE_END')}
            </Typography>
            <Typography
              variant="globalXS"
              color="new.text.neutral.inverted"
            >
              {t('YOUR_LIVE_END_DESCRIPTION')}
            </Typography>
          </Background>
        )}
      </HuCardContainer>
      <FormConfigurationLiveStream
        postId={postId}
        streamId={streamId}
        streamStatus={streamStatus}
        activeStep={activeStep}
        disabledWebCamOption={!!softwareParticipant}
      />
      {(isStreaming || isFinish) && postId && (
        <HostInterationsUsers
          postId={postId}
          activeStep={activeStep}
          streamId={streamId}
          streamStatus={streamStatus}
        />
      )}
      {deleteModal}
    </Stack>
  );
};

export default HostContent;
