import React, {useMemo} from 'react';
import {useTranslation} from 'react-i18next';
import {shallowEqual, useDispatch} from 'react-redux';
import {useNavigation} from '@react-navigation/native';
import {IconAccessPoint} from '@tabler/icons-react-native';
import {Button} from '@components';
import {useStreamActions} from '@modules/livestream/hooks';
import {StreamDestination} from '@modules/livestream/interfaces';
import {ShortedGroupInfo} from '@modules/group/interfaces';
import {
  updateStreamDestination,
  resetStreamDestinationState,
} from '@modules/livestream/store/slices/destinationSlice';
import {resetHostData, resetStreamPost} from '@modules/livestream/store';
import {useAppSelector} from '@redux/utils';
import {Screens} from '@shared/constants';
import {useTheme} from '@shared/theme';

import {getButtonStyle} from './styles';

interface Props {
  group?: ShortedGroupInfo;
  destination?: StreamDestination;
  onPress?: () => void;
}

export function StartStreamButton({
  destination = StreamDestination.Feed,
  group,
  onPress,
}: Props) {
  const {t} = useTranslation();
  const dispatch = useDispatch();
  const navigation = useNavigation();
  const {theme} = useTheme();
  const canCreateLive = useAppSelector(
    ({user}) =>
      user.permissions.VIEW_LIVESTREAM && user.permissions.CREATE_LIVESTREAM,
    shallowEqual,
  );

  const buttonStyle = useMemo(
    () => getButtonStyle(theme.primaryBorder),
    [theme.primaryBorder],
  );

  const {createStream, isCreateLoading} = useStreamActions({
    onCreate: data => {
      dispatch(
        updateStreamDestination({
          targetModule: destination,
          ...(group && {targetModuleData: group, targetModuleId: group.id}),
        }),
      );

      navigation.navigate(Screens.LIVESTREAM_HOST, {
        providerStreamId: data.providerStreamId,
      });
    },
  });

  const onStartPress = () => {
    onPress?.();
    // Reset any previous livestream state before creating a new stream
    dispatch(resetHostData());
    dispatch(resetStreamPost());
    dispatch(resetStreamDestinationState());
    createStream();
  };

  return canCreateLive ? (
    <Button
      IconLeft={IconAccessPoint}
      variant="secondary"
      size="sm"
      text={t('livestream.start_stream')}
      onPress={onStartPress}
      isLoading={isCreateLoading}
      style={buttonStyle}
    />
  ) : null;
}
