import React, { useContext } from 'react'
import { Text, TouchableOpacity, View } from 'react-native'

import { colors } from '../Colors'
import { ReactNavigationProps } from '../Navigation'
import { TextStyles } from '../Styles'
import { CommonScreenContainer } from '../components/CommonScreenContainer'
import { ErrorBoundary } from '../components/ErrorBoundary'
import { FilterText } from '../components/Filter'
import { HeaderNav } from '../components/HeaderNav'
import { InfoModal } from '../components/InfoModal'
import {
  ProductListContainer,
  ProductSortFn,
  sortProductByName,
  sortProductByReleaseDate,
} from '../components/ProductListContainer'
import { ProductListItem } from '../components/listitems/ProductListItem'
import { ScreenNames } from '../constants/ScreenNames'
import { ArtistContext } from '../contexts/ArtistContext'
import { EventType, sendAnalyticsEvent } from '../hooks/useAnalytics'
import { useProducts } from '../hooks/useProducts'
import { useScreenRefreshControl } from '../hooks/useScreenRefreshControl'
import { useScreenTimeInterval } from '../hooks/useScreenTimeInterval'
import { Strings } from '../i18n'
import { Product } from '../types/Product'
import { defaultTimeInterval } from '../types/TimeInterval'
import { Mode } from '../types/helpers'

const BetaTag: React.FC = () => (
  <View
    style={{
      backgroundColor: colors.offWhite,
      paddingHorizontal: 5,
      paddingTop: 5,
      paddingBottom: 4,
      borderRadius: 6,
    }}
  >
    <Text
      style={[
        TextStyles.tinyCaps,
        {
          color: colors.metals.metal2,
        },
      ]}
    >
      Beta
    </Text>
  </View>
)

const AlbumsEPsAndLPsHeading = () => (
  <View style={{ flexDirection: 'row', alignItems: 'center' }}>
    <Text
      ellipsizeMode="tail"
      numberOfLines={1}
      style={{
        ...TextStyles.h4,
        color: colors.midWhite,
        textAlign: 'left',
        paddingVertical: 12,
        paddingLeft: 12,
        paddingRight: 6,
      }}
    >
      {Strings.ProductScreen.AlbumsEPsAndLPs}
    </Text>
    <InfoModal
      title={Strings.ProductScreen.AlbumsEPsAndLPsDisclaimerTitle}
      body={{
        type: 'string',
        text: Strings.ProductScreen.AlbumsEPsAndLPsDisclaimerBody,
      }}
    >
      {(open) => (
        <TouchableOpacity onPress={open}>
          <BetaTag />
        </TouchableOpacity>
      )}
    </InfoModal>
  </View>
)

export const ProductsScreen: React.FC<
  ReactNavigationProps<ScreenNames.Products>
> = ({ navigation, route }) => {
  const screenName = 'Products Screen'
  const artist = useContext(ArtistContext)

  const modeOptions: Record<
    Mode.RELEASE | Mode.ALL,
    {
      sortFn: ProductSortFn
      title: string
    }
  > = {
    [Mode.RELEASE]: {
      sortFn: sortProductByReleaseDate,
      title: Strings.Shared.NewestReleases,
    },
    [Mode.ALL]: {
      sortFn: sortProductByName,
      title: Strings.Shared.AllProducts,
    },
  }

  const options = modeOptions[route.params.mode as Mode.RELEASE | Mode.ALL]

  const [timeInterval] = useScreenTimeInterval(defaultTimeInterval, {
    screenName,
    artistName: artist.name,
    entityId: artist.sonyArtistId,
  })

  const { albums, showToast, error, retry, refreshing } = useProducts()

  const onPullToRefresh = () => {
    sendAnalyticsEvent(EventType.PULL_TO_REFRESH, {
      artist_selected: artist.name,
      timeframe_selected: timeInterval,
      page: screenName,
      subject: 'user',
      verb: 'refreshed',
      object: 'products',
    })
    retry()
  }

  const { refreshControl } = useScreenRefreshControl(
    onPullToRefresh,
    refreshing
  )

  const productsByCategory = albums
    ? [
        {
          title: <AlbumsEPsAndLPsHeading />,
          data: albums,
        },
      ]
    : undefined

  return (
    <CommonScreenContainer screenName={screenName}>
      <HeaderNav
        title={options.title}
        showToast={showToast}
        navigation={navigation}
        style={{
          zIndex: 10,
        }}
        top={<FilterText>{Strings.Shared.AllTime}</FilterText>}
      />
      <ErrorBoundary error={error} refreshControl={refreshControl}>
        <View
          style={{
            flex: 1,
            paddingHorizontal: 8,
          }}
        >
          <ProductListContainer
            productsByCategory={productsByCategory}
            onPressProduct={(product: Product) =>
              navigation.navigate(ScreenNames.ProductDetail, {
                product_id: product.productId,
                time_interval: timeInterval,
              })
            }
            refreshControl={refreshControl}
            ListItem={ProductListItem}
            {...options}
          />
        </View>
      </ErrorBoundary>
    </CommonScreenContainer>
  )
}
