import { HeaderBackButton } from '@react-navigation/elements'
import {
  CardStyleInterpolators,
  createStackNavigator,
  StackNavigationOptions,
  TransitionSpecs,
} from '@react-navigation/stack'
import * as React from 'react'
import { Platform } from 'react-native'
import { connect } from 'react-redux'
import { screens as appScreens, selectors as appSelectors } from '../../modules/App'
import { RootState } from '../redux/store'
import BackArrowAndroid from './assets/BackArrowAndroid.svg'
import BackArrowIOS from './assets/BackArrowIOS.svg'

interface Props {
  appIsLoading?: boolean
  appIsLoaded?: boolean
}

const BackArrow = Platform.OS === 'ios' ? <BackArrowIOS /> : <BackArrowAndroid />

export const headerLeftBackButton = (navigation: any) => (
  <HeaderBackButton backImage={() => BackArrow} labelVisible={false} onPress={navigation.goBack} />
)

const stackNavigationOptions: StackNavigationOptions = {
  headerBackImage: () => BackArrow,
  headerBackTitleVisible: false,
  headerMode: 'screen',
  title: '',
  detachPreviousScreen: false,
  headerTitleAllowFontScaling: false,
  headerTitleAlign: 'center',
  headerStyle: {
    backgroundColor: 'black',
    shadowOpacity: 0,
    borderBottomWidth: 0,
    elevation: 0,
  },
  headerTintColor: 'white',
  headerTitleStyle: {
    fontWeight: 'bold',
  },
  cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS,
  transitionSpec: {
    open: TransitionSpecs.TransitionIOSSpec,
    close: TransitionSpecs.TransitionIOSSpec,
  },
}

const Stack = createStackNavigator()

const getScreens = (): JSX.Element => {
  return (
    <>
      <Stack.Screen name="Home" component={appScreens.Home} options={{ title: 'Home Screen' }} />
      <Stack.Screen name="SecondScreen" component={appScreens.SecondScreen} options={{ title: 'Second Screen' }} />
      <Stack.Screen name="InitError" component={appScreens.InitError} options={{ headerShown: false }} />
    </>
  )
}

const RootStack: React.FunctionComponent<Props> = () => {
  const screens = getScreens() // you could supply props to getScreens and return screens conditionally
  return <Stack.Navigator screenOptions={stackNavigationOptions}>{screens}</Stack.Navigator>
}

const mapStateToProps = (state: RootState) => ({
  appIsLoading: appSelectors.selectIsAppLoading(state),
  appIsLoaded: appSelectors.selectIsAppLoaded(state),
})

export default connect(mapStateToProps, null)(RootStack)
