import { useNavigation, useRoute } from '@react-navigation/native';
import React, { useLayoutEffect } 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 { useUserInfo } from '../../../../hooks/useStorage';
import { useUnitDetail, useUnitFunctions } from '../../../../hooks/useUnit';

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

  const [userInfo] = useUserInfo();
  const { data: functions, isLoading } = useUnitFunctions(userInfo.token, id);
  const { data: unit } = useUnitDetail(userInfo.token, id);

  useLayoutEffect(() => {
    navigation.setOptions({
      title: unit?.displayName,
    });
  }, [navigation, unit]);

  return (
    <View className="mx-4 mb-4 flex-1 bg-primary-bg">
      {!isLoading ? (
        <>
          <Title classNames="mt-4" text="Obsazení funkcí" />
          <ClickableFlatList
            items={functions?.map(fnc => {
              return {
                title: fnc.person,
                subtitle: fnc.functionType,
                onPress: () =>
                  navigation.navigate('PersonDetail', {
                    id: fnc.id,
                    isFromCatalog: false,
                  }),
              };
            })}
            emptyElement={
              <Text className="rounded bg-secondary-bg p-4">Nebyly nalezeny žádní činovníci.</Text>
            }
          />
        </>
      ) : (
        <Loader />
      )}
    </View>
  );
};

export default UnitFunctions;
