import React, {useState} from 'react';
import {Keyboard} from 'react-native';
import {useTranslation} from 'react-i18next';
import {IconMovie, IconPhoto} from '@tabler/icons-react-native';
import {Image as ImageType} from 'react-native-image-crop-picker';
import {Dialog, ListRow} from '@components';
import {ImageOrVideoAttachment} from '@interfaces/attachments';
import {openGallery} from '@shared/utils';
import {SHARED_STRINGS} from '@shared/strings';

import {BottomOptionButton} from '../BottomOptionButton';
import {styles} from './styles';

interface Props {
  disabled?: boolean;
  addImage: (image: ImageType) => void;
  addVideo: (video: ImageOrVideoAttachment) => void;
  onDialogOpen?: () => void;
}

function SelectImageOrVideo({
  disabled = false,
  addImage,
  addVideo,
  onDialogOpen,
}: Props) {
  const [dialogIsOpen, setDialogIsOpen] = useState(false);

  const onCloseDialog = () => {
    setDialogIsOpen(false);
  };
  const onOpenDialog = () => {
    Keyboard.dismiss();
    onDialogOpen?.();
    setDialogIsOpen(true);
  };

  return (
    <>
      <SelectImageOrVideo.BottomOptionButton
        onPress={onOpenDialog}
        disabled={disabled}
      />
      <SelectImageOrVideo.Dialog
        dialogIsOpen={dialogIsOpen}
        addImage={addImage}
        addVideo={addVideo}
        onClose={onCloseDialog}
      />
    </>
  );
}

interface BottomOptionButtonProps {
  onPress: () => void;
  disabled?: boolean;
}

const CustomBottomOptionButton = ({
  onPress,
  disabled,
}: BottomOptionButtonProps) => {
  return (
    <BottomOptionButton
      Icon={IconPhoto}
      onPress={onPress}
      disabled={disabled}
    />
  );
};

interface DialogProps {
  onClose: () => void;
  dialogIsOpen: boolean;
  addImage: (image: ImageType) => void;
  addVideo: (video: ImageOrVideoAttachment) => void;
}

const CustomDialog = ({
  onClose,
  dialogIsOpen,
  addImage,
  addVideo,
}: DialogProps) => {
  const {t} = useTranslation();

  const onAddImage = () => {
    onClose();
    openGallery({save: addImage, options: {cropping: true}});
  };
  const onAddVideo = () => {
    onClose();
    openGallery({save: addVideo, options: {mediaType: 'video'}});
  };

  return (
    <Dialog
      onClose={onClose}
      isVisible={dialogIsOpen}
      title={t(SHARED_STRINGS.GALLERY)}
      contentStyle={styles.content}>
      <ListRow onPress={onAddImage}>
        <ListRow.Avatar Icon={IconPhoto} />
        <ListRow.Title title={t('new_post.select_photo')} />
        <ListRow.SideContent withRightIcon />
      </ListRow>
      <ListRow onPress={onAddVideo}>
        <ListRow.Avatar Icon={IconMovie} />
        <ListRow.Title title={t('new_post.select_video')} />
        <ListRow.SideContent withRightIcon />
      </ListRow>
    </Dialog>
  );
};

SelectImageOrVideo.Dialog = CustomDialog;
SelectImageOrVideo.BottomOptionButton = CustomBottomOptionButton;

export default SelectImageOrVideo;
