import { View, Text, FlatList } from "react-native";
import React, { useState } from "react";
import CreateLyricsHeader from "../Writing/components/CreateLyricsHeader";
import { FONT_FAMILY } from "../../styles/Fonts";
import { Palette } from "../../styles";
import { CHOOSE_GENRE } from "../../data/data";
import ItemContainer from "../../components/ItemContainer/ItemContainer";
import _ from "lodash";

const ChooseGenre = ({ selected = [], setSelected }) => {
  const [containerLayout, setContainerLayout] = useState(null);

  const onPressSelect = (item) => {
    if (!setSelected) return;
    const value = item?.title;
    const list = _.isArray(selected) ? selected : [];
    const exists = _.includes(list, value);
    if (exists) {
      setSelected(_.filter(list, (v) => !_.isEqual(v, value)));
    } else if (_.size(list) < 2) {
      setSelected([...list, value]);
    }
  };

  return (
    <View style={{ flex: 1, gap: 10, paddingTop: 16 }}>
      <CreateLyricsHeader
        title="Choisis un genre"
        subTitle="Tu peux choisir jusqu’à 2 genres différents"
      />
      <View
        style={{ flex: 1 }}
        onLayout={(event) => setContainerLayout(event.nativeEvent.layout)}
      >
        <ItemContainer height={containerLayout?.height}>
          <FlatList
            data={CHOOSE_GENRE}
            contentContainerStyle={{
              gap: 16,
              flexGrow: 1,
              zIndex: 2,
              paddingTop: 5,
            }}
            renderItem={({ item, index }) => {
              const list = Array.isArray(selected) ? selected : [];
              const selectedItem = _.includes(list, item.title);

              return (
                <View style={{ paddingHorizontal: 5 }}>
                  <CreateLyricsHeader
                    colors={[Palette.tran, Palette.tran]}
                    tint={selectedItem ? "default" : "dark"}
                    onPress={() => onPressSelect(item)}
                    containerStyle={{
                      borderWidth: selectedItem ? 2 : 0,
                      borderColor: selectedItem ? "#F94697" : "transparent",
                    }}
                  >
                    <Text
                      style={{
                        fontSize: 16,
                        color: Palette.white,
                        fontFamily: FONT_FAMILY.InterRegular,
                      }}
                    >
                      <Text style={{ fontFamily: FONT_FAMILY.InterBold }}>
                        {item.title}
                      </Text>{" "}
                      : {item.description}
                    </Text>
                  </CreateLyricsHeader>
                </View>
              );
            }}
          />
        </ItemContainer>
      </View>
    </View>
  );
};

export default ChooseGenre;
