import React, {useState} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {BottomModalList, RadioButton, Button, Alert} from '@components';
import {useSafeAreaBottomPadding} from '@hooks/useSafeAreaBottomPadding';
import {
  getPolicyOptions,
  PolicyModalKey,
  PolicyOption,
} from '@modules/group/constants';
import {useTheme} from '@shared/theme';

import {styles} from './styles';

interface Props {
  policyKey: PolicyModalKey;
  onCloseModal: () => void;
  onSave: (key: PolicyModalKey, newValue: string | boolean) => void;
  currentValue: string | boolean;
  isLoading?: boolean;
  disabled?: boolean;
}

function PolicyModal({
  policyKey,
  currentValue,
  isLoading,
  onCloseModal,
  onSave,
  disabled,
}: Props) {
  const {t} = useTranslation();
  const [privacy, setPrivacy] = useState(currentValue);
  const paddingBottom = useSafeAreaBottomPadding();
  const {spacing} = useTheme();

  const {options, titleKey} = getPolicyOptions(policyKey);

  const onSaveChanges = () => onSave(policyKey, privacy);

  const renderItem = ({item, index}: {item: PolicyOption; index: number}) => {
    const isSelected = item.key === privacy;
    const onPressItem = () => setPrivacy(item.key);
    const isLast = index === options.length - 1;
    return (
      <RadioButton
        disabled={disabled}
        title={t(item.title)}
        description={t(item.subtitle)}
        checked={isSelected}
        onPress={onPressItem}
        style={isLast ? {marginBottom: spacing.x18 + paddingBottom} : undefined}
      />
    );
  };

  return (
    <BottomModalList
      isVisible
      onClose={onCloseModal}
      renderItem={renderItem}
      data={options}
      ListHeaderComponent={
        policyKey === PolicyModalKey.MembersCanLeaveKey ? (
          <Alert
            title={t('group.members_can_leave_warning_title')}
            description={t('group.members_can_leave_warning_description')}
          />
        ) : null
      }
      title={t(titleKey)}
      titleNumberOfLines={2}
      bounces={false}
      contentContainerStyle={styles.contentContainer}
      footerComponent={
        <View style={[styles.footerContainer, {paddingBottom}]}>
          <Button
            disabled={privacy === currentValue}
            isLoading={isLoading}
            onPress={onSaveChanges}
            text={t('general.save')}
          />
          <Button
            disabled={isLoading}
            onPress={onCloseModal}
            style={styles.cancelButton}
            text={t('general.cancel')}
            variant="tertiary"
          />
        </View>
      }
    />
  );
}

export default PolicyModal;
