/* eslint-disable react-native/no-inline-styles */
import {StyleSheet} from 'react-native';
import Image from 'react-native-fast-image';
import Video from 'react-native-video';
import React, {memo, useCallback, useEffect, useMemo, useState} from 'react';
import {Surface} from 'react-native-paper';
import {Slot} from '@s20.ai/copilot-camera-sdk/src/types/AOP';
import RNFS from 'react-native-fs';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import FastImage from 'react-native-fast-image';

type Props = {
  slot: Slot;
  size?: 'small' | 'medium' | 'original';
  volume?: number | undefined;
};

const smallImg = '?tr=w-100,h-100';
const mediumImg = '?tr=w-300,h-300';
const originalImg = '';

const getImgReSizeQueryParam = (size?: 'small' | 'medium' | 'original') => {
  switch (size) {
    case 'small':
      return smallImg;
    case 'medium':
      return mediumImg;
    case 'original':
    default:
      return originalImg;
  }
};

const DisplayMedia = (props: Props) => {
  const [fileExists, setFileExists] = useState(false);
  const [filePath, setFilePath] = useState({s3url: '', imageKitUrl: ''});

  const extractUrl = useCallback(async () => {
    if (props.slot.isComplete) {
      if (props.slot.isUploaded) {
        setFileExists(true);
        let url = props.slot.uploadURL as string;
        if (props.slot.action?.captureType === 'Video') {
          url = props.slot.uploadURL!.replace('.mp4', '_480p.mp4');
          setFilePath({s3url: url, imageKitUrl: url});
        } else {
          url = url
            .replace(
              'safecam360-mobile-images.s3.amazonaws.com',
              'ik.imagekit.io/copilotcamera',
            )
            .replace(/[+]/g, '%20')
            .replace(/%26/g, '&')
            .replace(/%2B/g, '+')
            .replace(/%2C/g, ',');
          setFilePath({s3url: props.slot.uploadURL!, imageKitUrl: url});
        }
      } else if (props.slot.action && props.slot.action.actionData) {
        const exists = await RNFS.exists(props.slot.action.actionData.path);
        if (exists) {
          setFileExists(true);
          let url = props.slot.action.actionData.path as string;
          setFilePath({s3url: url, imageKitUrl: url});
          // if (props.slot.action?.captureType === "Video") {
          //   url = props.slot.uploadURL!.replace(".mp4", "_480p.mp4");
          //   setFilePath({ s3url: url, imageKitUrl: url });
          // } else {
          //   url = url
          //     .replace("safecam360-mobile-images.s3.amazonaws.com", "ik.imagekit.io/copilotcamera")
          //     .replace(/[+]/g, "%20")
          //     .replace(/%26/g, "&")
          //     .replace(/%2B/g, "+")
          //     .replace(/%2C/g, ",");
          //   setFilePath({ s3url: props.slot.uploadURL!, imageKitUrl: url });
          // }
        }
      }
    } else {
      setFilePath({s3url: '', imageKitUrl: ''});
    }
  }, [props.slot]);

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

  // const videoProxyURL = useCallback((url: string) => convertToProxyURL(url), []);

  const memoizedVideo = useMemo(() => {
    return (
      <Video
        volume={props.volume || 0}
        source={{
          // uri: "https://safecam360-mobile-images.s3.amazonaws.com/27316445-88d7-4717-b2be-dfbe1d746fdb_Spin_Exterior+360_480p.mp4",
          // uri: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/WhatCarCanYouGetForAGrand.mp4",
          uri: filePath.s3url,
        }}
        // onError={(_) => {
        //   if (props.slot.action && props.slot.action.actionData) {
        //     setFilePath((d) => ({
        //       imageKitUrl: d.imageKitUrl,
        //       s3url: (props.slot.action!.actionData!.path as string) || "",
        //     }));
        //   }
        // }}
        repeat
        style={{
          width: '100%',
          height: '100%',
          alignItems: 'center',
          justifyContent: 'center',
          backgroundColor: '#ffffff',
        }}
        resizeMode="cover"
      />
    );
  }, [filePath.s3url, props.volume]);

  const MemoizedVideoComponent = () => memoizedVideo;
  return (
    <Surface style={styles.fillStyles}>
      {(fileExists && props.slot.action && (
        <>
          {props.slot.action.captureType === 'Image' ? (
            <Image
              source={{
                uri: filePath.imageKitUrl + getImgReSizeQueryParam(props.size),
                // uri: filePath.s3url,
                priority: FastImage.priority.high,
                // cache: FastImage.cacheControl.immutable,
              }}
              onError={() => {
                setFilePath(d => ({
                  s3url: d.s3url,
                  imageKitUrl: d.s3url,
                }));
              }}
              resizeMode="cover"
              style={styles.fillStyles}
            />
          ) : (
            <MemoizedVideoComponent />
          )}
        </>
      )) || (
        <>
          {props.slot.action && props.slot.action.captureType === 'Image' ? (
            <Icon name="camera-off" color="#e4e4e4" size={20} />
          ) : (
            <Icon name="video-off" color="#e4e4e4" size={20} />
          )}
        </>
      )}
    </Surface>
  );
};

const styles = StyleSheet.create({
  fillStyles: {
    width: '100%',
    height: '100%',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#ffffff',
  },
});

export default memo(DisplayMedia);
