import { FC, useState } from 'react';
import { Helmet } from 'react-helmet-async';
import { FormProvider, useForm } from 'react-hook-form';
import { useParams, useNavigate } from 'react-router-dom';
import Webcam from 'react-webcam';

import { useModal } from '@material-hu/hooks/useModal';
import ChatBubbleOutlineOutlinedIcon from '@material-hu/icons/material/ChatBubbleOutlineOutlined';
import CloseIcon from '@material-hu/icons/material/Close';
import EmojiEmotionsOutlinedIcon from '@material-hu/icons/material/EmojiEmotionsOutlined';
import RadioButtonCheckedIcon from '@material-hu/icons/material/RadioButtonChecked';
import RemoveRedEyeOutlinedIcon from '@material-hu/icons/material/RemoveRedEyeOutlined';
import SettingsOutlinedIcon from '@material-hu/icons/material/SettingsOutlined';
import VideocamOutlinedIcon from '@material-hu/icons/material/VideocamOutlined';
import WatchLaterOutlinedIcon from '@material-hu/icons/material/WatchLaterOutlined';
import CircularProgress from '@material-hu/mui/CircularProgress';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import Tooltip from '@material-hu/mui/Tooltip';
import Typography from '@material-hu/mui/Typography';

import Button from '@material-hu/components/design-system/Buttons/Button';
import useNewTheme from 'src/hooks/useNewTheme';
import { formatTitle } from 'src/utils/helmetUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';
import FeatureNotAvailableModal from 'src/components/FeatureNotAvailableModal';
import { FormTextField, FormSwitch } from 'src/components/FormInputs';

import { feedRoutes } from '../feed/routes';
import { groupsRoutes } from '../groups/routes';

enum Configuration {
  GENERAL = 'GENERAL',
  CONFIGURATION = 'CONFIGURATION',
}

const liveIcons = [
  { LiveIcon: RemoveRedEyeOutlinedIcon, label: 'VIEWS' },
  { LiveIcon: EmojiEmotionsOutlinedIcon, label: 'REACTIONS' },
  { LiveIcon: ChatBubbleOutlineOutlinedIcon, label: 'COMMENTS' },
];

const { GENERAL, CONFIGURATION } = Configuration;

const DemoLiveStream: FC = () => {
  const navigate = useNavigate();
  const { id: groupId } = useParams();

  const [activeStep, setActiveStep] = useState(GENERAL);
  const [isLive, setIsLive] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [seconds, setSeconds] = useState(0);
  const [usedInterval, setUsedInterval] = useState(null);

  const { t } = useLokaliseTranslation(['livestream', 'general']);

  const NewThemeProvider = useNewTheme();

  const form = useForm({
    defaultValues: {
      title: '',
      description: '',
      allowComments: true,
      withNotification: true,
    },
    mode: 'onChange',
  });

  const steps = {
    [GENERAL]: {
      id: GENERAL,
      label: t('GENERAL'),
      icon: <VideocamOutlinedIcon />,
    },
    [CONFIGURATION]: {
      id: CONFIGURATION,
      label: t('CONFIGURATION'),
      icon: <SettingsOutlinedIcon />,
    },
  };

  const handleGoBack = () =>
    navigate(groupId ? groupsRoutes.detail(groupId) : feedRoutes.feed());

  const {
    modal: featureNotAvailableModal,
    showModal: showfeatureNotAvailableModal,
    closeModal,
  } = useModal(({ featureName }) => (
    <FeatureNotAvailableModal
      featureName={featureName}
      onAccept={() => {
        closeModal();
        handleGoBack();
      }}
    />
  ));

  const handleStepSelect = selectedStep => setActiveStep(selectedStep);

  const startStreaming = () => {
    setIsLive(true);
    setIsLoading(false);
    const interval = setInterval(() => setSeconds(prev => prev + 1), 1000);
    setUsedInterval(interval);
    setTimeout(() => {
      showfeatureNotAvailableModal({ featureName: 'LIVE_STREAM' });
    }, 10000);
  };

  const handleStartStreaming = () => {
    setIsLoading(true);
    setTimeout(() => {
      startStreaming();
    }, 1500);
  };

  const handleEndStreaming = () => {
    clearInterval(usedInterval);
    setUsedInterval(null);
    setSeconds(0);
    setIsLive(false);
  };

  return (
    <NewThemeProvider>
      <Helmet>
        <title>{formatTitle(t('LIVE_STREAM'))}</title>
      </Helmet>
      <Stack
        sx={{
          minHeight: '100%',
        }}
      >
        {featureNotAvailableModal}
        <Stack
          sx={{
            width: '100%',
            zIndex: 200,
            alignItems: 'center',
            flexDirection: 'row',
            backgroundColor: 'white',
            gap: 2,
            py: 2,
            px: 3,
          }}
        >
          <IconButton onClick={handleGoBack}>
            <CloseIcon />
          </IconButton>
          <Typography variant="h5">{t('LIVE_STREAM')}</Typography>
        </Stack>
        <Stack
          sx={{
            flexDirection: 'row',
            justifyContent: 'space-around',
            py: 2,
          }}
        >
          {!isLive && (
            <Stack
              sx={{
                p: 2,
                backgroundColor: 'white',
                borderRadius: '16px',
                width: '240px',
                height: '191px',
              }}
            >
              <Typography
                variant="h5"
                sx={{ mb: 2 }}
              >
                {t('MANAGE_LIVE_STREAM')}
              </Typography>
              {Object.values(steps).map(step => (
                <Button
                  startIcon={step.icon}
                  onClick={() => handleStepSelect(step.id)}
                  key={step.id}
                  variant="text"
                  sx={{
                    justifyContent: 'flex-start',
                    color:
                      activeStep === step.id ? 'primary' : 'text.secondary',
                  }}
                >
                  {step.label}
                </Button>
              ))}
            </Stack>
          )}
          <Stack
            sx={{
              gap: 2,
              p: 3,
              borderRadius: '16px',
              backgroundColor: 'white',
            }}
          >
            <Webcam
              style={{ borderRadius: '12px' }}
              videoConstraints={{
                aspectRatio: 1100 / 500,
              }}
              width={1100}
              height={500}
            />
            {!isLive && (
              <FormProvider {...form}>
                {activeStep === GENERAL && (
                  <Stack sx={{ gap: 2 }}>
                    <FormTextField
                      label={t('TITLE')}
                      name="title"
                      placeholder={t('TITLE_PLACEHOLDER')}
                      inputProps={{ maxLength: 50 }}
                      rules={{ required: true }}
                    />
                    <FormTextField
                      label={t('DESCRIPTION')}
                      name="description"
                      multiline
                      showCounter
                      max={250}
                      placeholder={t('DESCRIPTION_PLACEHOLDER')}
                      inputProps={{
                        maxLength: 250,
                        sx: { minHeight: '120px' },
                      }}
                    />
                  </Stack>
                )}
                {activeStep === CONFIGURATION && (
                  <Stack sx={{ gap: 2 }}>
                    <Stack
                      sx={{
                        flexDirection: 'row',
                        alignItems: 'center',
                        justifyContent: 'space-between',
                      }}
                    >
                      <Stack>
                        <Typography variant="h6">
                          {t('ALLOW_COMMENTS')}
                        </Typography>
                        <Typography variant="body1">
                          {t('ALLOW_COMMENTS_INFO')}
                        </Typography>
                      </Stack>
                      <FormSwitch name="allowComments" />
                    </Stack>
                    <Stack
                      sx={{
                        flexDirection: 'row',
                        alignItems: 'center',
                        justifyContent: 'space-between',
                      }}
                    >
                      <Stack>
                        <Typography variant="h6">
                          {t('NOTIFY_AUDIENCE')}
                        </Typography>
                        <Typography variant="body1">
                          {t('NOTIFY_AUDIENCE_INFO')}
                        </Typography>
                      </Stack>
                      <FormSwitch name="withNotification" />
                    </Stack>
                  </Stack>
                )}
              </FormProvider>
            )}
            {isLive && (
              <Stack sx={{ flexDirection: 'row', gap: 2 }}>
                {liveIcons.map(({ LiveIcon, label }) => (
                  <Stack
                    key={label}
                    sx={{
                      flexDirection: 'row',
                      gap: 1,
                      alignItems: 'center',
                    }}
                  >
                    <Tooltip title={t(label)}>
                      <LiveIcon color="secondary" />
                    </Tooltip>
                    <Typography variant="h6">0</Typography>
                  </Stack>
                ))}
              </Stack>
            )}
            <Stack
              sx={{
                flexDirection: 'row',
                alignItems: 'center',
                gap: 3,
                justifyContent: 'end',
              }}
            >
              {isLive && (
                <Stack
                  sx={{
                    flexDirection: 'row',
                    gap: 1,
                    alignItems: 'center',
                  }}
                >
                  <WatchLaterOutlinedIcon />
                  <Typography variant="h5">{`00:00:${seconds}`}</Typography>
                  <RadioButtonCheckedIcon color="error" />
                </Stack>
              )}
              <Button
                onClick={isLive ? handleEndStreaming : handleStartStreaming}
                variant="contained"
                color={isLive ? 'error' : 'primary'}
                disabled={isLoading}
                endIcon={isLoading ? <CircularProgress size={20} /> : null}
              >
                {t(isLive ? 'END_STREAM' : 'START_STREAM')}
              </Button>
            </Stack>
          </Stack>
        </Stack>
      </Stack>
    </NewThemeProvider>
  );
};

export default DemoLiveStream;
