import React, { FC, useEffect, useState } from 'react';
import { TouchableOpacity, Text, FlatList } from 'react-native';

import { getUNMastersTypes, type TypeData } from '../../../../database/unMastersService';

import { HorizontalSelectStyles } from './styles';

const HorizontalSelect: FC<HorizontalSelectTypes> = ({ selectedType }) => {
  const [unMastersTypes, setUnMastersTypes] = useState<TypeData[]>([]);
  const [activeButtonIndex, setActiveButtonIndex] = useState(0);

  useEffect(() => {
    const types = getUNMastersTypes();
    if (types) {
      setUnMastersTypes(types);
    }
  }, []);

  const Button: FC<ButtonTypes> = ({ label, index, selectedButtonIndex }) => {
    return (
      <TouchableOpacity
        style={[
          HorizontalSelectStyles.wrapper,
          index === activeButtonIndex
            ? HorizontalSelectStyles.selected
            : HorizontalSelectStyles.notSelected
        ]}
        onPress={() => selectedButtonIndex(index)}
      >
        <Text
          style={[
            HorizontalSelectStyles.text,
            index === activeButtonIndex
              ? HorizontalSelectStyles.activeText
              : HorizontalSelectStyles.notActiveText
          ]}
        >
          {label}
        </Text>
      </TouchableOpacity>
    );
  };

  return (
    <FlatList
      data={unMastersTypes}
      showsHorizontalScrollIndicator={false}
      contentContainerStyle={{ gap: 5 }}
      renderItem={({ item, index }) => (
        <Button
          index={index}
          selectedButtonIndex={(i) => {
            setActiveButtonIndex(i);
            selectedType && selectedType(item);
          }}
          label={item.name}
        />
      )}
      horizontal={true}
    />
  );
};

type HorizontalSelectTypes = {
  selectedType?: (type: TypeData) => void;
};

type ButtonTypes = {
  label: string;
  index: number;
  selectedButtonIndex: (index: number) => void;
};

export default HorizontalSelect;
