import React, { useState } from 'react'
import { LayoutChangeEvent, Pressable, Text } from 'react-native'
import { ScrollView } from 'react-native-gesture-handler'

import { colors } from '../Colors'
import { TextStyles } from '../Styles'
import { AutoLayout } from './AutoLayout'

/*
 * Generic selector component
 */
interface SelectorProps<T> {
  options: readonly T[]
  onSelect: (option: T) => void
  selectedOption: T
  labelExtractor: (option: T) => string
  keyExtractor: (option: T) => string
}

export function Selector<T extends string>({
  options,
  onSelect,
  selectedOption,
  labelExtractor,
}: SelectorProps<T>): React.ReactElement {
  const [contentWidth, setContentWidth] = useState(0)
  const [scrollViewWidth, setScrollViewWidth] = useState(0)
  const scrollEnabled = contentWidth > scrollViewWidth // Enable scroll only when options wouldn't fit

  return (
    <ScrollView
      style={{ height: 60, flexGrow: 0 }}
      contentContainerStyle={{
        justifyContent: 'center',
        flexGrow: 1,
      }}
      horizontal
      showsHorizontalScrollIndicator={false}
      onContentSizeChange={(width, height) => {
        setContentWidth(width)
      }}
      onLayout={(e: LayoutChangeEvent) => {
        setScrollViewWidth(e.nativeEvent.layout.width)
      }}
      scrollEnabled={scrollEnabled}
    >
      <AutoLayout
        style={{
          flexDirection: 'row',
          justifyContent: 'center',
          alignItems: 'center',
          paddingHorizontal: 0,
        }}
        gap={8}
      >
        {options.map((option) => (
          <Pressable
            key={option}
            onPress={() => onSelect(option)}
            style={[
              {
                paddingHorizontal: 8,
                paddingTop: 9,
                paddingBottom: 11,
                borderRadius: 4,
                justifyContent: 'center',
                alignItems: 'center',
              },
              option === selectedOption
                ? { backgroundColor: colors.metals.metal1 }
                : null,
            ]}
          >
            <Text
              style={[
                TextStyles.bodyMedium,
                { color: colors.white, textTransform: 'uppercase' },
              ]}
            >
              {labelExtractor(option)}
            </Text>
          </Pressable>
        ))}
      </AutoLayout>
    </ScrollView>
  )
}
