import React, { useContext, useRef, useState } from 'react';
import { StyleSheet, View } from 'react-native';
import FastImage from 'react-native-fast-image';
import styles from './styles';
import {
  ApplicationContext,
  ComponentContext,
  MiniAppContext,
  SkeletonContext,
} from '../Context';
import { Skeleton } from '../Skeleton';
import { Icon } from '../Icon';
import { Styles } from '../Consts';
import { ImageProps } from './types';

type Status = 'success' | 'loading' | 'error';

export const getImageName = (source: any): string => {
  const parts = source?.uri?.split?.('/');
  if (parts?.length > 0) {
    return parts?.[parts.length - 1];
  }
  return '';
};

const Image: React.FC<ImageProps> = ({
  style,
  source,
  loading = true,
  children,
  ...rest
}) => {
  const { theme } = useContext(ApplicationContext);
  const component: any = useContext(ComponentContext);
  const context = useContext<any>(MiniAppContext);
  const skeleton = useContext(SkeletonContext);
  const error = useRef(false);
  const [status, setStatus] = useState<Status>('success');

  const showBaseLineDebug = context?.features?.showBaseLineDebug ?? false;

  let accessibilityLabel: any = `img|${getImageName(source)}`;
  if (component?.componentId) {
    accessibilityLabel = `${component?.componentId}|img|${getImageName(
      source,
    )}`;
  }
  /**
   * render content loading | fail | rendered
   */
  const renderContent = () => {
    if (status === 'loading' || status === 'error') {
      let content = <Skeleton />;
      if (status === 'error') {
        content = (
          <Icon source="media_fail" color={theme.colors.text.disable} />
        );
      }
      return (
        <View style={[StyleSheet.absoluteFill, Styles.flexCenter]}>
          {content}
        </View>
      );
    }

    if (skeleton.loading) {
      return (
        <View style={[StyleSheet.absoluteFill, Styles.flexCenter]}>
          <Skeleton />
        </View>
      );
    }

    return children;
  };

  return (
    <FastImage
      {...rest}
      {...{ accessibilityLabel: rest.accessibilityLabel ?? accessibilityLabel }}
      source={source}
      style={[
        styles.container,
        style,
        showBaseLineDebug && styles.debugBaseLine,
      ]}
      onProgress={() => {
        error.current = false;
        if (status !== 'loading' && loading) {
          setStatus('loading');
        }
      }}
      onLoadStart={() => {
        error.current = false;
      }}
      onLoad={() => {
        error.current = false;
      }}
      onLoadEnd={() => {
        let current: Status = 'success';
        if (error.current) {
          current = 'error';
        }
        setStatus(prevState => (prevState !== current ? current : prevState));
      }}
      onError={() => {
        error.current = true;
      }}
    >
      {renderContent()}
    </FastImage>
  );
};

export { Image };
