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 OrganizerUnitSelect from '../../../../../../components/CustomSelect/OrganizerUnitSelect';
import Title from '../../../../../../components/List/components/Title';
import Loader from '../../../../../../components/Loader/Loader';
import { NavProps, RouteProps } from '../../../../../../components/Routes/Routes';
import TextField from '../../../../../../components/TextField/TextField';
import TextFieldDate from '../../../../../../components/TextField/TextFieldDate';
import TextFieldSelect from '../../../../../../components/TextField/TextFieldSelect';
import { EVENTS_RELATIONS, FILTER_PLACEHOLDER } from '../../../../../../constants/custom';
import {
  useEventAddPost,
  useEventDetail,
  useEventEdit,
  useEventGeneralAllGet,
} from '../../../../../../hooks/useEvents';
import { useUserInfo } from '../../../../../../hooks/useStorage';
import { EventGeneralInsertPayload } from '../../../../../../services/api/APIS/Events/types';
import { showFeedback } from '../../../../../../services/feedback/showFeedback';

const EventEdit = () => {
  const {
    id,
    filterIsFuture,
    filterYear,
    filterRelationValue,
    filterTypeId,
    filterStateId,
    filterScopeId,
  } = useRoute<RouteProps<'EventEdit'>>().params;
  const isEdit = !!id;
  const navigation = useNavigation<NavProps>();
  const [userInfo] = useUserInfo();

  const { types, scopes, regions, isLoading } = useEventEdit(userInfo.token);

  const { refetch, detail } = useEventDetail(userInfo?.token, id || '', !isEdit);

  const { refetch: refetchEvents } = useEventGeneralAllGet(
    userInfo?.token,
    filterIsFuture === undefined ? '' : `${filterIsFuture}`,
    filterYear || '',
    filterRelationValue === EVENTS_RELATIONS[1].value ? 'true' : '',
    filterRelationValue === EVENTS_RELATIONS[2].value ? 'true' : '',
    filterRelationValue === EVENTS_RELATIONS[3].value ? 'true' : '',
    filterTypeId || '',
    filterStateId || '',
    filterScopeId || '',
  );

  const { mutate: updateEvent } = useEventAddPost(
    userInfo?.token,
    navigation.goBack,
    refetchEvents,
    refetch,
    id,
  );

  const [unitId, setUnitId] = useState<string>(
    isEdit ? detail?.unitId || '' : userInfo?.unitId || '',
  );
  const [name, setName] = useState<string>(isEdit ? detail?.displayName || '' : '');
  const [type, setType] = useState<string>(isEdit ? detail?.type || '' : FILTER_PLACEHOLDER);
  const [scope, setScope] = useState<string>(isEdit ? detail?.scope || '' : FILTER_PLACEHOLDER);
  const [note, setNote] = useState<string>(isEdit ? detail?.note || '' : '');
  const [startDate, setStartDate] = useState<Date | undefined>(
    isEdit ? new Date(detail?.startDate || '') : undefined,
  );
  const [endDate, setEndDate] = useState<Date | undefined>(
    isEdit ? new Date(detail?.endDate || '') : undefined,
  );
  const [region, setRegion] = useState<string>(isEdit ? detail?.region || '' : FILTER_PLACEHOLDER);
  const [location, setLocation] = useState<string>(isEdit ? detail?.location || '' : '');
  const [postcode, setPostcode] = useState<string>(isEdit ? detail?.postcode || '' : '');

  useLayoutEffect(() => {
    navigation.setOptions({
      title: `${isEdit ? 'Upravit' : 'Vytvořit'} akci`,
    });
  }, [navigation, isEdit]);

  return (
    <View className="m-4 flex-1 justify-start bg-primary-bg">
      {!isLoading ? (
        <ScrollView>
          {!isEdit && (
            <View className="mb-4">
              <OrganizerUnitSelect
                selectedUnitId={isEdit ? `${detail.regNumber} - ${detail.unit}` : ''}
                setSelectedUnitId={setUnitId}
              />
            </View>
          )}
          <Title text="Základní informace" />

          <View className="my-4">
            <TextField title="Název akce" value={name} setValue={setName} />
          </View>

          <View className="mb-4">
            <TextFieldSelect
              title="Typ"
              items={types?.map(item => item.displayName) || []}
              value={type}
              setValue={setType}
            />
          </View>

          <View className="mb-4">
            <TextFieldSelect
              title="Rozsah"
              items={scopes?.map(item => item.displayName) || []}
              value={scope}
              setValue={setScope}
            />
          </View>

          <View className="mb-4">
            <TextField title="Poznámka" value={note} setValue={setNote} multiline />
          </View>

          <View className="mb-4">
            <TextFieldDate title="Datum začátku tábora" value={startDate} setValue={setStartDate} />
          </View>

          <View className="mb-4">
            <TextFieldDate title="Datum konce tábora" value={endDate} setValue={setEndDate} />
          </View>

          <Title text="Lokace" classNames="mb-4" />

          <View className="mb-4">
            <TextField title="Katastrální území" value={location} setValue={setLocation} />
          </View>

          <View className="mb-4">
            <TextFieldSelect
              title="Kraj"
              items={regions?.map(place => place.displayName) || []}
              value={region}
              setValue={setRegion}
            />
          </View>

          <View className="mb-4">
            <TextField title="PSČ obce" value={postcode} setValue={setPostcode} number />
          </View>

          <View>
            <FormButtons
              submitText={isEdit ? 'Upravit' : 'Vytvořit'}
              onSubmit={() => {
                let error;
                if (!postcode?.length) error = 'Zadejte PSČ.';
                if (region === FILTER_PLACEHOLDER) error = 'Vyberte región.';
                if (!location?.length) error = 'Zadejte katastrální území.';
                if (!startDate) error = 'Vyberte datum začátku konání.';
                if (!endDate) error = 'Vyberte datum konce konání.';
                if (scope === FILTER_PLACEHOLDER) error = 'Vyberte rozsah.';
                if (type === FILTER_PLACEHOLDER) error = 'Vyberte typ.';
                if (!name.length) error = 'Zadejte název akce.';
                if (unitId === '') error = 'Vyberte jednotku.';
                if (startDate && endDate && startDate > endDate) {
                  error = 'Datum začátku musí být dříve než datum konce.';
                }
                if (error) {
                  showFeedback({
                    title: error,
                    type: 'danger',
                  });
                  return;
                }
                const payload: EventGeneralInsertPayload = {
                  unitId,
                  displayName: name,
                  typeId: types?.find(item => item.displayName === type)?.id || '',
                  scopeId: scopes?.find(item => item.displayName === scope)?.id || '',
                  note,
                  startDate: startDate?.toISOString() || '',
                  endDate: endDate?.toISOString() || '',
                  region: region === FILTER_PLACEHOLDER ? '' : region,
                  location,
                  postcode,
                };
                updateEvent(payload);
              }}
            />
          </View>
        </ScrollView>
      ) : (
        <Loader />
      )}
    </View>
  );
};

export default EventEdit;
