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

import FormButtons from '../../../../../../../../../../components/Button/FormButtons';
import Loader from '../../../../../../../../../../components/Loader/Loader';
import { NavProps, RouteProps } from '../../../../../../../../../../components/Routes/Routes';
import Table from '../../../../../../../../../../components/Table/Table';
import {
  useParticipantCampInsertPost,
  useParticipants,
  usePersonAllEventCampMultiGet,
} from '../../../../../../../../../../hooks/useCamps';
import { useUserInfo } from '../../../../../../../../../../hooks/useStorage';
import { showFeedback } from '../../../../../../../../../../services/feedback/showFeedback';

const CampParticipantAddUnit = () => {
  const { campId } = useRoute<RouteProps<'CampParticipantAddUnit'>>().params;
  const [userInfo] = useUserInfo();
  const navigation = useNavigation<NavProps>();

  const [selectedRows, setSelectedRows] = useState<string[][]>([]);

  const { refetchList } = useParticipants(userInfo.token, campId);
  const {
    data: persons,
    isFetching: isLoading,
    refetch: refetchMultiList,
  } = usePersonAllEventCampMultiGet(userInfo.token, campId);

  const refetch = () => {
    refetchList();
    refetchMultiList();
  };

  const { mutate: addParticipant } = useParticipantCampInsertPost(userInfo?.token, campId, refetch);

  useEffect(() => {
    if (persons) {
      setSelectedRows(
        persons
          .filter(person => person.isParticipant)
          .map(person => [person.displayName, person.category]),
      );
    }
  }, [persons]);

  return (
    <View className="mx-4 mb-4 flex-1 justify-start bg-primary-bg">
      {!isLoading ? (
        <>
          <Table
            selected={selectedRows}
            onSelect={(value, item) => {
              if (value) {
                setSelectedRows(prev => [...prev, item]);
              }
            }}
            onSelectAll={(value, items) => {
              if (value) {
                setSelectedRows(items);
              }
            }}
            header={[
              {
                title: 'Osoba',
                classNames: 'w-[45%]',
              },
              {
                title: 'Výchovná kategorie',
                classNames: 'w-[45%] text-right',
              },
            ]}
            items={persons?.map(person => [person.displayName, person.category]) || []}
            emptyElement={
              <Text className="mt-4 rounded bg-secondary-bg p-4">Oddíl nemá žádné členy.</Text>
            }
          />
        </>
      ) : (
        <Loader />
      )}

      <View>
        <FormButtons
          submitText="Přidat"
          onSubmit={() => {
            const newPersonIds = selectedRows
              .filter(row => {
                const person = persons?.find(person => person.displayName === row[0]);
                return person && !person.isParticipant;
              })
              .map(row => persons?.find(person => person.displayName === row[0])?.id as string);

            let error;
            if (!newPersonIds) error = 'Vyberte nové členy.';
            if (error) {
              showFeedback({
                title: error,
                type: 'danger',
              });
              return;
            }
            newPersonIds.forEach(personId => addParticipant(personId));
            navigation.goBack();
          }}
        />
      </View>
    </View>
  );
};

export default CampParticipantAddUnit;
