import { FontAwesome5 } from '@expo/vector-icons';
import { useNavigation, useRoute } from '@react-navigation/native';
import React, { useLayoutEffect, useState } from 'react';
import { View, Text, ScrollView } from 'react-native';

import DetailList from '../../../../../../../../components/List/DetailList';
import Loader from '../../../../../../../../components/Loader/Loader';
import ConfirmationModal from '../../../../../../../../components/Modal/ConfirmationModal';
import { NavProps, RouteProps } from '../../../../../../../../components/Routes/Routes';
import { EventFunctions, EVENT_FUNCTION_NAMES } from '../../../../../../../../constants/custom';
import {
  useEventDetail,
  useEventFunctionAllGeneralGet,
  useEventGeneralUpdateFunction,
} from '../../../../../../../../hooks/useEvents';
import { useUserInfo } from '../../../../../../../../hooks/useStorage';
import { EventFunctionAllCampResponse } from '../../../../../../../../services/api/APIS/Events/types';

const EventTeam = () => {
  const { id, eventName, isRelation } = useRoute<RouteProps<'EventTeam'>>().params;
  const navigation = useNavigation<NavProps>();
  const [userInfo] = useUserInfo();
  const [isDeletedModalVisible, setIsDeletedModalVisible] = useState(false);
  const [selectedFunction, setSelectedFunction] = useState('');
  const { detail } = useEventDetail(userInfo.token, id);

  const {
    data: functions,
    isFetching: isLoading,
    refetch: refetchFunctions,
  } = useEventFunctionAllGeneralGet(userInfo.token, id);

  const { mutate: updateFunction } = useEventGeneralUpdateFunction(
    userInfo.token,
    id,
    refetchFunctions,
  );

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

  const editIcons = (item: EventFunctionAllCampResponse) => [
    {
      element: <FontAwesome5 name="edit" size={24} />,
      onPress: () =>
        navigation.navigate('EventTeamEdit', {
          role: item.role,
          id: item.id,
          name: item.name,
          note: item.note,
          eventId: id,
        }),
    },
    {
      element: <FontAwesome5 name="trash" size={24} />,
      onPress: () => {
        setSelectedFunction(item.role);
        setIsDeletedModalVisible(true);
      },
    },
  ];

  const createIcons = (item: EventFunctionAllCampResponse) => [
    {
      element: <FontAwesome5 name="plus" size={24} />,
      onPress: () => navigation.navigate('EventTeamEdit', { role: item.role, eventId: id }),
    },
  ];

  return (
    <View className="mx-4 mb-4 flex-1 justify-start bg-primary-bg">
      {!isLoading ? (
        <ScrollView>
          {functions?.length !== 0 ? (
            <>
              {functions?.map((item, index) => (
                <DetailList
                  key={`${item.id}-${index}`}
                  title={{
                    text: item.role,
                    icons:
                      !detail.isEditable || !isRelation
                        ? undefined
                        : item.id.length
                        ? editIcons(item)
                        : createIcons(item),
                  }}
                  items={[
                    {
                      title: 'Osoba:',
                      value: item?.name || ' ',
                    },
                    {
                      title: 'Poznámka:',
                      value: item?.note || ' ',
                    },
                  ]}
                />
              ))}
            </>
          ) : (
            <Text className="mt-4 rounded bg-secondary-bg p-4">
              {`Tábor ${eventName} nemá žádný tým.`}
            </Text>
          )}
        </ScrollView>
      ) : (
        <Loader />
      )}
      <ConfirmationModal
        isVisible={isDeletedModalVisible}
        setIsVisible={setIsDeletedModalVisible}
        title="Odstranit člena týmu"
        text="Opravdu se chcete odstranit člena z týmu?"
        onConfirm={() => {
          const payload =
            functions
              ?.filter(filterItem => filterItem.role !== selectedFunction)
              .map(functionItem => ({
                id: functionItem.personId,
                role: EVENT_FUNCTION_NAMES[functionItem.role as keyof EventFunctions],
                note: functionItem.note,
              })) || [];
          updateFunction(payload);
        }}
      />
    </View>
  );
};

export default EventTeam;
