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

import FormButtons from '../../../../../../components/Button/FormButtons';
import Loader from '../../../../../../components/Loader/Loader';
import { NavProps, RouteProps } from '../../../../../../components/Routes/Routes';
import TextField from '../../../../../../components/TextField/TextField';
import TextFieldSelect from '../../../../../../components/TextField/TextFieldSelect';
import { SEXES } from '../../../../../../constants/custom';
import { useUserInfo } from '../../../../../../hooks/useStorage';
import {
  useUnitAdvertisingCategory,
  useUnitAdvertisingCategoryAdd,
  useUnitAdvertisingCategoryAll,
  useUnitAdvertisingMeetingDateAll,
} from '../../../../../../hooks/useUnitAdvertising';
import { AdvertisingCategoryDetailResponse } from '../../../../../../services/api/APIS/OrganizationUnit/types';
import { showFeedback } from '../../../../../../services/feedback/showFeedback';

const UnitAdvertisingCategoryEdit = () => {
  const { id } = useRoute<RouteProps<'UnitAdvertisingCategoryEdit'>>().params;
  const isEdit = !!id;

  const [userInfo] = useUserInfo();
  const navigation = useNavigation<NavProps>();

  const { refetch: refetchCategories } = useUnitAdvertisingCategoryAll(
    userInfo.token,
    userInfo.unitId,
    true,
  );

  const {
    data: category,
    isLoading: isCategoryLoading,
    refetch: refetchCategory,
  } = useUnitAdvertisingCategory(userInfo.token, id || '');

  const { mutate: addCategory } = useUnitAdvertisingCategoryAdd(
    userInfo.token,
    userInfo.unitId,
    refetchCategories,
    navigation.goBack,
    id,
    refetchCategory,
  );

  const { data: meetingDates, isLoading: isMeetingDatesLoading } = useUnitAdvertisingMeetingDateAll(
    userInfo.token,
    userInfo.unitId,
    true,
  );

  const [ageFrom, setAgeFrom] = useState<string>(category?.ageFrom || '');
  const [ageTo, setAgeTo] = useState<string>(category?.ageTo || '');
  const [sex, setSex] = useState<string>(category?.sex || '');
  const [meetingDate, setMeetingDate] = useState<string>(
    isEdit
      ? meetingDates?.find(date => date.id === category?.meetingDateId)?.displayName || ''
      : '',
  );
  const [note, setNote] = useState<string>(category?.note || '');

  const isLoading = isMeetingDatesLoading;

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

  return (
    <View className="m-4 flex-1 justify-start space-y-4 bg-primary-bg">
      {!isLoading && (!isEdit || (isEdit && !isCategoryLoading)) ? (
        <>
          <View>
            <TextField title="Věk od" value={ageFrom} setValue={setAgeFrom} number />
          </View>
          <View>
            <TextField title="Věk do" value={ageTo} setValue={setAgeTo} number />
          </View>
          <View>
            <TextFieldSelect
              title="Pohlaví"
              items={SEXES.map(sex => sex.sex)}
              value={sex}
              setValue={setSex}
            />
          </View>
          <View>
            <TextFieldSelect
              title="Termín schůzky"
              items={meetingDates?.map(date => date.displayName || '') || []}
              value={meetingDate}
              setValue={setMeetingDate}
            />
          </View>
          <View>
            <TextField title="Poznámka" value={note} setValue={setNote} multiline />
          </View>
          <FormButtons
            onSubmit={() => {
              let error;
              if (!meetingDate) error = 'Vyberte termín schůzky.';
              if (!sex) error = 'Vyberte pohlaví.';
              if (!ageTo) error = 'Vyplňte věk do.';
              if (!ageFrom) error = 'Vyplňte věk od.';
              if (Number(ageTo) < Number(ageFrom)) error = 'Věk do musí být větší než věk od.';
              if (error) {
                showFeedback({
                  title: error,
                  type: 'danger',
                });
                return;
              }
              if (!ageFrom || !ageTo || !sex || !meetingDate) return;
              const newCategory: AdvertisingCategoryDetailResponse = {
                sexId: SEXES.find(s => s.sex === sex)?.id || '',
                sex,
                ageFrom,
                ageTo,
                note,
                meetingDateId:
                  meetingDates?.find(date => date.displayName === meetingDate)?.id || '',
              };
              addCategory(newCategory);
            }}
          />
        </>
      ) : (
        <Loader />
      )}
    </View>
  );
};

export default UnitAdvertisingCategoryEdit;
