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

import FormSelectionCard from '@material-hu/components/composed-components/SelectionCard/form';
import CardContainer from '@material-hu/components/design-system/CardContainer';
import RadioButton from '@material-hu/components/design-system/RadioButton/RadioButton';

import useCommunityFeature from 'src/hooks/useCommunityFeature';
import useFeatureFlag from 'src/hooks/useFeatureFlag';
import usePermissions from 'src/hooks/usePermissions';
import { CommunityFeature } from 'src/types/communityFeatures';
import { FeatureFlags } from 'src/types/featureFlags';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { UserPermissions } from 'src/utils/permissions';

import { getEventLiveLocationWarningMessage } from '../../utils';

export const LivestreamLocationForm: FC = () => {
  const { t } = useLokaliseTranslation('events');
  const { watch } = useFormContext();

  const isLivestreamEnabled = useFeatureFlag(
    FeatureFlags.EVENTS_LIVESTREAM_ENABLED,
  );
  const hasCommunityFeature = useCommunityFeature(
    CommunityFeature.VIEW_LIVESTREAM,
  );
  const { hasAll: canCreateLivestream } = usePermissions([
    UserPermissions.CREATE_LIVESTREAM,
  ]);

  const { locationType } = watch();

  if (!isLivestreamEnabled) {
    return null;
  }

  const isDisabled = !hasCommunityFeature || !canCreateLivestream;

  const warningMessage = getEventLiveLocationWarningMessage({
    t,
    hasCommunityFeature,
    canCreateLivestream,
  });

  return (
    <CardContainer
      badge={
        isDisabled
          ? { hasIcon: true, type: 'warning', label: warningMessage }
          : undefined
      }
      sx={{
        mt: 3,
        '& > .MuiCardContent-root': { p: 0 },
      }}
      fullWidth
    >
      <FormSelectionCard
        name="locationType.liveStream"
        isOnlyOption
        disabled={isDisabled}
        sx={{
          border: 'none',
          width: '100%',
          '& > .MuiCardContent-root': {
            cursor: 'default',
            backgroundColor: theme => theme.palette.newBase?.white,
          },
        }}
      >
        <RadioButton
          label={t('create_event_form.livestream_label')}
          description={t('create_event_form.livestream_description')}
          isActive={locationType.liveStream}
          disabled={isDisabled}
        />
      </FormSelectionCard>
    </CardContainer>
  );
};

export default LivestreamLocationForm;
