import {useCallback, useEffect, useRef, useState} from 'react';
import {Share} from 'react-native';
import {useTranslation} from 'react-i18next';
import {File} from 'expo-file-system';
import {ImageSource} from 'expo-image';
import {CameraRoll} from '@react-native-camera-roll/camera-roll';
import {
  format,
  getDocumentPath,
  getFileNameExtension,
  removeQueryParams,
} from '@shared/utils';
import {pathToFileUri} from '@shared/utils/files/path';

interface Params {
  source: ImageSource;
}

export const useImageActions = ({source: {uri: url}}: Params) => {
  const {t} = useTranslation();
  const timeoutRef = useRef<NodeJS.Timeout>(undefined);
  const [snackBarText, setSnackBarText] = useState<string>('');

  const onShareImage = useCallback(async () => {
    try {
      if (url) {
        await Share.share({message: t('general.share_picture'), url});
      }
    } catch (error) {
      // Do nothing
    }
  }, [url, t]);

  const onSaveImage = useCallback(async () => {
    if (!url) {
      return;
    }
    const fileName = `humand_image_${format(
      new Date(),
      'yyyy-MM-dd_HH-mm-ss',
    )}.${getFileNameExtension(removeQueryParams(url)).split('-')[0]}`;
    const localFile = await getDocumentPath(fileName);

    try {
      await File.downloadFileAsync(url, new File(pathToFileUri(localFile)));
      await CameraRoll.saveAsset(localFile);
      setSnackBarText(t('general.image_saved_successfully'));
    } catch (error) {
      // Do nothing
    }
  }, [t, url]);

  const clearSnackBar = useCallback(() => {
    setSnackBarText('');
  }, []);

  useEffect(() => {
    if (snackBarText) {
      timeoutRef.current = setTimeout(() => {
        clearSnackBar();
      }, 3500);
    }

    return () => {
      clearTimeout(timeoutRef.current);
    };
  }, [clearSnackBar, snackBarText]);

  return {onShareImage, onSaveImage, snackBarText, clearSnackBar};
};
