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

import FormButtons from '../../../../../../../../../../components/Button/FormButtons';
import PersonSelect from '../../../../../../../../../../components/CustomSelect/PersonSelect';
import Title from '../../../../../../../../../../components/List/components/Title';
import { NavProps, RouteProps } from '../../../../../../../../../../components/Routes/Routes';
import TextField from '../../../../../../../../../../components/TextField/TextField';
import TextFieldSelect from '../../../../../../../../../../components/TextField/TextFieldSelect';
import { CampFunctions, CAMP_FUNCTION_NAMES } from '../../../../../../../../../../constants/custom';
import {
  useEventCampUpdateFunction,
  useEventFunctionAllCamp,
} from '../../../../../../../../../../hooks/useCamps';
import { Person } from '../../../../../../../../../../hooks/useSearchPerson';
import { useUserInfo } from '../../../../../../../../../../hooks/useStorage';
import { showFeedback } from '../../../../../../../../../../services/feedback/showFeedback';

const CampTeamEdit = () => {
  const { id, role, name, note, campId } = useRoute<RouteProps<'CampTeamEdit'>>().params;
  const isEdit = !!id;
  const navigation = useNavigation<NavProps>();
  const [userInfo] = useUserInfo();

  const [personList, setPersonList] = useState<Person[]>([]);
  const [selectedPerson, setSelectedPerson] = useState<string>(isEdit ? name || '' : '');
  const [currentNote, setCurrentNote] = useState<string>(isEdit ? note || '' : '');

  const { data: functions, refetch: refetchFunctions } = useEventFunctionAllCamp(
    userInfo.token,
    userInfo.roleId,
    campId,
  );

  const { mutate: updateFunction } = useEventCampUpdateFunction(
    userInfo.token,
    campId,
    refetchFunctions,
    navigation.goBack,
  );

  useLayoutEffect(() => {
    navigation.setOptions({
      title: `${isEdit ? 'Upravit' : 'Přidat'} ${role}`,
    });
  }, [navigation, role]);

  return (
    <View className="m-4 flex-1 justify-start bg-primary-bg">
      <ScrollView>
        <PersonSelect
          setPersonList={setPersonList}
          selectedPerson={selectedPerson}
          setSelectedPerson={setSelectedPerson}
        />
        <Title text={`${isEdit ? 'Upravit' : 'Přidat'} ${role}`} classNames="mt-4" />
        <View className="mt-4 rounded bg-secondary-bg p-4">
          <View className="mb-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 className="mb-4">
            <TextField title="Poznámka" value={currentNote} setValue={setCurrentNote} multiline />
          </View>
          <FormButtons
            onSubmit={() => {
              let error;
              if (!currentNote?.length) error = 'Zadejte poznámku.';
              if (!selectedPerson) error = 'Vyberte osobu.';
              if (error) {
                showFeedback({
                  title: error,
                  type: 'danger',
                });
                return;
              }

              const payload =
                functions?.map(functionItem =>
                  functionItem.role === role
                    ? {
                        id: personList.find(person => person.name === selectedPerson)?.id || '',
                        role: CAMP_FUNCTION_NAMES[role as keyof CampFunctions],
                        note: currentNote,
                      }
                    : {
                        id: functionItem.personId,
                        role: CAMP_FUNCTION_NAMES[functionItem.role as keyof CampFunctions],
                        note: functionItem.note,
                      },
                ) || [];

              updateFunction(payload);
            }}
          />
        </View>
      </ScrollView>
    </View>
  );
};

export default CampTeamEdit;
