import React, { useCallback, useRef } from 'react';
import { Dimensions } from 'react-native';
import { SText } from '../../common/s-components/typography/s-text';
import { SRow } from '../../common/s-components/layout/s-row';
import { Placeholder } from '../../common/components/placeholder';
import { SBox } from '../../common/s-components/layout/s-box';
import { SH2 } from '../../common/s-components/typography/s-h2';
import { checkDeviceWithSmallWidth } from '../../common/transducers';

const getWinWidth = () => Dimensions.get('window').width;
const getWinHeight = () => Dimensions.get('window').height;

type TProps = {
  title?: string;
  variant: string;
};

export const ViewErrors: React.FC<TProps> = props => {
  const { variant, title } = props;
  const width = useRef(getWinWidth());
  const height = useRef(getWinHeight());

  const getErrorTitle = useCallback(() => {
    let errorTitle = null;

    switch (variant) {
      case 'network-failed':
        errorTitle = (
          <SH2 mt={-6} mb={12} lineHeight="24px">
            Connection Is Lost
          </SH2>
        );
        break;
      case 'load-failed':
        errorTitle = (
          <SH2 mb={13} lineHeight="24px">
            Failed to Load {'\n'}the {title} Page
          </SH2>
        );
        break;
      case 'load-failed-graph':
        errorTitle = (
          <SH2 mb={12} lineHeight="24px">
            Failed to load {'\n'}
            {title}
          </SH2>
        );
        break;
      default:
        errorTitle = null;
    }

    return errorTitle;
  }, [variant, title]);

  const getErrorText = useCallback(() => {
    let errorText = null;

    switch (variant) {
      case 'network-failed':
        errorText = (
          <SText lineHeight="20px">
            Please check your internet connection and try again.
          </SText>
        );
        break;
      case 'load-failed':
      case 'load-failed-graph':
        errorText = (
          <SText lineHeight="20px">
            We are experiencing some problems. Please try again.
          </SText>
        );
        break;
      default:
        errorText = null;
    }

    return errorText;
  }, [variant]);

  const placeholderWidth = height.current - 32;
  const px = checkDeviceWithSmallWidth(width.current) ? 0 : 46;
  const textWidth = checkDeviceWithSmallWidth(width.current) ? 1 : 0.8;
  const mtErrorText = variant === 'load-failed-graph' ? -22 : 0;

  return (
    <SBox flex={1} justifyContent="center" px={px} mt={-45}>
      <SRow alignItems="center">
        <Placeholder
          variant={variant}
          baseWidth={placeholderWidth}
          baseHeight={220}
        />
        <SBox ml={33} pt={4} mt={mtErrorText} flex={textWidth}>
          {getErrorTitle()}
          {getErrorText()}
        </SBox>
      </SRow>
    </SBox>
  );
};
