import {useCallback, useEffect, useState} from 'react';
import {Platform} from 'react-native';
import {
  CameraRoll,
  PhotoIdentifier,
} from '@react-native-camera-roll/camera-roll';
import {check, request, PERMISSIONS, RESULTS} from 'react-native-permissions';

export const useRecentMedia = (limit: number = 20) => {
  const [media, setMedia] = useState<PhotoIdentifier[]>([]);
  const [loading, setLoading] = useState(true);
  const [hasPermission, setHasPermission] = useState(false);

  const checkPermission = async () => {
    const permission =
      Platform.OS === 'ios'
        ? PERMISSIONS.IOS.PHOTO_LIBRARY
        : Number(Platform.Version) >= 33
        ? PERMISSIONS.ANDROID.READ_MEDIA_IMAGES
        : PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE;

    const result = await check(permission);

    if (result === RESULTS.GRANTED || result === RESULTS.LIMITED) {
      setHasPermission(true);
      return true;
    }

    if (result === RESULTS.DENIED) {
      const requestResult = await request(permission);
      const granted =
        requestResult === RESULTS.GRANTED || requestResult === RESULTS.LIMITED;
      setHasPermission(granted);
      return granted;
    }

    setHasPermission(false);
    return false;
  };

  const fetchMedia = useCallback(async () => {
    try {
      const hasAccess = await checkPermission();
      if (!hasAccess) {
        setLoading(false);
        return;
      }

      const result = await CameraRoll.getPhotos({
        first: limit,
        assetType: 'All',
        include: ['imageSize', 'playableDuration'],
      });

      setMedia(result.edges);
    } catch (error) {
      // need to handle thius
    } finally {
      setLoading(false);
    }
  }, [limit]);

  useEffect(() => {
    fetchMedia();
  }, [fetchMedia]);

  const refresh = () => {
    setLoading(true);
    fetchMedia();
  };

  return {
    media,
    loading,
    hasPermission,
    refresh,
  };
};
