import React, { useRef, useEffect } from 'react'
import {
  LayoutChangeEvent,
  TouchableOpacity,
  View,
  Text,
  StyleSheet,
} from 'react-native'

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

interface Props {
  title: string
  selected: boolean
  disabled: boolean
  onPress: (ref: View) => void
  onSelect: (ref: View) => void
  onLayout: (e: LayoutChangeEvent) => void
}

const styles = StyleSheet.create({
  container: {
    marginRight: 16,
  },
  view: {
    paddingHorizontal: 4,
    paddingVertical: 8,
  },
  normal: {
    color: colors.gray,
  },
  selected: {
    color: colors.white,
  },
  text: {
    textTransform: 'uppercase',
  },
  border: {
    borderBottomWidth: 2,
    borderColor: colors.white,
  },
})

export function TabButton({
  title,
  selected,
  disabled,
  onPress,
  onSelect,
  onLayout,
}: Props) {
  const button = useRef<View>()
  useEffect(() => {
    if (selected) {
      onSelect(button.current)
    }
  }, [selected])
  const textStyle = [
    TextStyles.body,
    TextStyles.micro,
    styles.text,
    selected && !disabled ? styles.selected : styles.normal,
  ]
  return (
    <TouchableOpacity
      disabled={disabled}
      style={styles.container}
      onPress={() => onPress(button.current)}
      onLayout={onLayout}
    >
      <View style={styles.view} ref={button}>
        <Text style={textStyle}>{title}</Text>
      </View>
    </TouchableOpacity>
  )
}
