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

import FormButtons from '../../../../../../../../../../components/Button/FormButtons';
import PersonSelect from '../../../../../../../../../../components/CustomSelect/PersonSelect';
import { NavProps, RouteProps } from '../../../../../../../../../../components/Routes/Routes';
import TextFieldSelect from '../../../../../../../../../../components/TextField/TextFieldSelect';
import {
  useParticipantCampInsertPost,
  useParticipants,
} from '../../../../../../../../../../hooks/useCamps';
import { Person } from '../../../../../../../../../../hooks/useSearchPerson';
import { useUserInfo } from '../../../../../../../../../../hooks/useStorage';
import { showFeedback } from '../../../../../../../../../../services/feedback/showFeedback';

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

  const { refetchList } = useParticipants(userInfo.token, campId);
  const { mutate: addParticipant } = useParticipantCampInsertPost(
    userInfo?.token,
    campId,
    refetchList,
    navigation.goBack,
  );

  const [personList, setPersonList] = useState<Person[]>([]);
  const [selectedPerson, setSelectedPerson] = useState<string>('');

  return (
    <View className="m-4 flex-1 justify-start bg-primary-bg">
      <ScrollView>
        <PersonSelect
          setPersonList={setPersonList}
          selectedPerson={selectedPerson}
          setSelectedPerson={setSelectedPerson}
        />

        <View className="mt-4">
          <TextFieldSelect
            title="Nalezené osoby"
            items={personList.map(person => person.name)}
            value={selectedPerson}
            setValue={setSelectedPerson}
            fullHeight={personList?.length > 20}
            onWarning={
              !personList.length
                ? () =>
                    showFeedback({
                      type: 'warning',
                      title: 'Nejdříve vyhledejte osobu',
                    })
                : undefined
            }
          />
        </View>

        <View>
          <FormButtons
            submitText="Přidat"
            onSubmit={() => {
              let error;
              if (!selectedPerson) error = 'Vyberte osobu.';
              if (error) {
                showFeedback({
                  title: error,
                  type: 'danger',
                });
                return;
              }
              addParticipant(personList.find(person => person.name === selectedPerson)?.id || '');
            }}
          />
        </View>
      </ScrollView>
    </View>
  );
};

export default CampParticipantAddSearch;
