import * as Linking from 'expo-linking';
import React, { memo, useCallback } from 'react';
import { Alert, Dimensions, Platform, StatusBar } from 'react-native';
import { Button } from '../../common/components/button';
import { SBox } from '../../common/s-components/layout/s-box';
import { SCentered } from '../../common/s-components/layout/s-centered';
import { SImage } from '../../common/s-components/s-image';
import { SH2 } from '../../common/s-components/typography/s-h2';
import { SH4 } from '../../common/s-components/typography/s-h4';
import { TState, TToggleUpdateSplash } from '../types';
// import { checkDeviceWithSmallWidth } from '../../common/transducers';

const updateSplashImage = require('../../../assets/update-splash/update-splash.png');

const isIOS = Platform.OS === 'ios';

const DEFAULT_TEXT =
  'Download the latest update to Apollo Insights\n for new features.';

const { width } = Dimensions.get('window');

type TProps = {
  shouldShowRemindButton: boolean;
  changelog?: TState['changelog'];
  toggleUpdateSplash: TToggleUpdateSplash;
  isLandscape?: boolean | null;
};

export const UpdateSplash: React.FC<TProps> = memo(props => {
  const {
    toggleUpdateSplash,
    isLandscape,
    shouldShowRemindButton,
    changelog,
  } = props;
  const openErrorAlert = () =>
    Alert.alert(
      'Error',
      'Error occured trying to open link for downloading newest version of ApolloInsights',
      [
        {
          text: 'OK',
        },
      ]
    );

  const handleRemindTomorrowPress = () => {
    toggleUpdateSplash(false);
  };

  const handleOpenAppLink = async () => {
    const APP_STORE_LINK =
      'itms-apps://itunes.apple.com/us/app/apple-store/1482330393?mt=8';
    //'itms-apps://itunes.apple.com/us/app/apple-store/com.sonymusic.apollogo?mt=8';
    const PLAY_MARKET_LINK = 'market://details?id=com.sonymusic.apollogo';
    const linkToApp = isIOS ? APP_STORE_LINK : PLAY_MARKET_LINK;
    let canOpen;
    try {
      canOpen = await Linking.canOpenURL(linkToApp);
    } catch (e) {
      canOpen = false;
    }

    if (!canOpen) {
      return openErrorAlert();
    }

    return Linking.openURL(linkToApp)
      .then(() => toggleUpdateSplash(null))
      .catch(() => openErrorAlert());
  };

  const goToStoreButton = () => (
    <SBox width={178} mt={27}>
      <Button
        testID="update-splash-button"
        variant="primary"
        onPress={handleOpenAppLink}
        width={1}
        px={isIOS ? undefined : 10}
      >
        Update
      </Button>
    </SBox>
  );

  const remindButton = () => (
    <SBox width={178} mt={16}>
      <Button
        testID="next-time-button"
        variant="request"
        onPress={handleRemindTomorrowPress}
        width={1}
        px={isIOS ? undefined : 10}
      >
        Next Time
      </Button>
    </SBox>
  );

  const renderSplashImage = () => {
    let maxWidth = 343;
    let resizeMode = 'cover';

    if (!isIOS && isLandscape && width < 700) {
      maxWidth = 290;
      resizeMode = 'contain';
    }

    return (
      <SImage
        source={updateSplashImage}
        maxHeight={265}
        maxWidth={maxWidth}
        resizeMode={resizeMode}
      />
    );
  };

  const renderPortrait = useCallback(() => {
    const marginTop = shouldShowRemindButton ? -32 : -29;
    return (
      <SBox
        position="absolute"
        width="100%"
        height="100%"
        zIndex={1000}
        bg="ebonyClay"
      >
        <SCentered bg="ebonyClay">
          <StatusBar barStyle="light-content" translucent />
          <SBox pl={16} pr={16} alignItems="center" mt={marginTop}>
            <SBox>{renderSplashImage()}</SBox>
            <SBox mt={22}>
              <SBox alignItems="center">
                <SH2 lineHeight="24px">New Version Available</SH2>
              </SBox>
              <SBox mt={11}>
                <SH4
                  normal
                  lineHeight="20px"
                  numberOfLines={3}
                  textAlign="center"
                >
                  {changelog || DEFAULT_TEXT}
                </SH4>
              </SBox>
            </SBox>
            <SBox ml={-1}>
              {goToStoreButton()}
              {shouldShowRemindButton && remindButton()}
            </SBox>
          </SBox>
        </SCentered>
      </SBox>
    );
  }, [shouldShowRemindButton, changelog]);

  const renderLandscape = useCallback(() => {
    const paddingTop = shouldShowRemindButton ? 29 : 57;
    return (
      <SBox
        position="absolute"
        width="100%"
        height="100%"
        zIndex={1000}
        bg="ebonyClay"
        alignItems="center"
        justifyContent="center"
      >
        <SBox flexDirection="row" pt={1}>
          {renderSplashImage()}
          <SBox width={375}>
            <SBox pl={32} pt={paddingTop}>
              <SH2 lineHeight="24px">New Version Available</SH2>
              <SBox mt={12}>
                <SH4 normal lineHeight="20px" numberOfLines={3}>
                  {changelog || DEFAULT_TEXT}
                </SH4>
              </SBox>
              {goToStoreButton()}
              {shouldShowRemindButton && remindButton()}
            </SBox>
          </SBox>
        </SBox>
      </SBox>
    );
  }, [shouldShowRemindButton, changelog]);

  if (isLandscape === null) {
    return null;
  }
  return isLandscape ? renderLandscape() : renderPortrait();
});

UpdateSplash.defaultProps = {
  isLandscape: null,
  changelog: null,
};
