import { useNavigation, useRoute } from '@react-navigation/native';
import React, { useState } from 'react';
import { View, Text } from 'react-native';

import { ClickableFlatList } from '../../../../components/List/ClickableList';
import Title from '../../../../components/List/components/Title';
import Loader from '../../../../components/Loader/Loader';
import { NavProps, RouteProps } from '../../../../components/Routes/Routes';
import TextFieldSelect from '../../../../components/TextField/TextFieldSelect';
import { useUserInfo } from '../../../../hooks/useStorage';
import { useUnitMembers } from '../../../../hooks/useUnitMembership';

const UnitMembers = () => {
  const { id } = useRoute<RouteProps<'UnitMembers'>>().params;
  const navigation = useNavigation<NavProps>();

  const [userInfo] = useUserInfo();
  const { categories, units, memberships, isLoading } = useUnitMembers(userInfo.token, id);

  const [selectedUnit, setSelectedUnit] = useState(units[0]);
  const [selectedCategory, setSelectedCategory] = useState(categories[0]);

  return (
    <View className="m-4 flex-1 bg-primary-bg">
      {!isLoading ? (
        <>
          <Title classNames="mb-4" text="Filtr" />
          <View className="space-y-2 rounded bg-secondary-bg p-4">
            <View>
              <TextFieldSelect
                title="Jednotka"
                items={units}
                value={selectedUnit}
                setValue={setSelectedUnit}
              />
            </View>
            <View>
              <TextFieldSelect
                title="Kategorie"
                items={categories}
                value={selectedCategory}
                setValue={setSelectedCategory}
              />
            </View>
          </View>

          <Title classNames="mt-4" text="Členové" />
          <View className="flex-1">
            <ClickableFlatList
              items={memberships
                ?.filter(
                  member =>
                    (member.unit === selectedUnit || selectedUnit === 'Všechny') &&
                    (member.category === selectedCategory.split(' ')[0] ||
                      selectedCategory === 'Všechny'),
                )
                .map(member => {
                  return {
                    title: `${member.person} (${member.category})`,
                    subtitle: member.unit,
                    onPress: () =>
                      navigation.navigate('PersonDetail', {
                        id: member.personId,
                        isFromCatalog: false,
                      }),
                  };
                })}
              emptyElement={
                <Text className="rounded bg-secondary-bg p-4">
                  V jednotce nebyli nalezeni členové.
                </Text>
              }
            />
          </View>
        </>
      ) : (
        <Loader />
      )}
    </View>
  );
};

export default UnitMembers;
