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

import FormButtons from '../../../../../../components/Button/FormButtons';
import UnitSelect from '../../../../../../components/CustomSelect/UnitSelect';
import CheckboxList from '../../../../../../components/List/CheckboxList';
import Title from '../../../../../../components/List/components/Title';
import Loader from '../../../../../../components/Loader/Loader';
import { NavProps, RouteProps } from '../../../../../../components/Routes/Routes';
import Switch from '../../../../../../components/Switch/Switch';
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 {
  useCampDetail,
  useCampEdit,
  useEventCampAdd,
  useEventCampAll,
  useEventCampDetail,
} from '../../../../../../hooks/useCamps';
import { useUserInfo } from '../../../../../../hooks/useStorage';
import { EventCampInsertPayload } from '../../../../../../services/api/APIS/Events/types';
import { showFeedback } from '../../../../../../services/feedback/showFeedback';

const CampEdit = () => {
  const {
    id,
    filterName,
    filterIsFuture,
    filterLocation,
    filterRegNumber,
    filterRelationValue,
    filterYear,
  } = useRoute<RouteProps<'CampEdit'>>().params;
  const isEdit = !!id;
  const navigation = useNavigation<NavProps>();
  const [userInfo] = useUserInfo();
  const { camps, campTypes, regions, campPlaces, isLoading } = useCampEdit(
    userInfo.token,
    userInfo.roleId,
  );
  const { data: detail } = useEventCampDetail(userInfo.token, userInfo.roleId, id || '', !isEdit);

  const { refetch: refetchCamps } = useEventCampAll(
    userInfo?.token,
    userInfo.roleId,
    filterName || '',
    filterIsFuture === undefined ? '' : `${filterIsFuture}`,
    filterYear || '',
    filterRelationValue === EVENTS_RELATIONS[1].value ? 'true' : '',
    filterRelationValue === EVENTS_RELATIONS[2].value ? 'true' : '',
    filterRelationValue === EVENTS_RELATIONS[3].value ? 'true' : '',
    filterRegNumber || '',
    filterLocation || '',
  );

  const { refetchCampDetail } = useCampDetail(userInfo?.token, userInfo.roleId, id || '', true);

  const { mutate: mutateCamp } = useEventCampAdd(
    userInfo.token,
    navigation.goBack,
    refetchCamps,
    refetchCampDetail,
    isEdit ? detail?.id : undefined,
  );

  const [selectedCamp, setSelectedCamp] = useState(
    isEdit ? `${detail?.regNumber} - ${detail?.unit}` : camps ? camps[0].sortName : '',
  );
  const [selectedUnitIds, setSelectedUnitIds] = useState<string[]>(
    isEdit ? detail?.unitIds || [] : [],
  );
  const [selectedCampType, setSelectedCampType] = useState<string[]>(
    isEdit ? (detail?.type ? [detail?.type] : []) : [],
  );
  const [name, setName] = useState(isEdit ? detail?.displayName || '' : '');
  const [mobile, setMobile] = useState(isEdit ? detail?.mobile || '' : '');
  const [note, setNote] = useState(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 [campPlace, setCampPlace] = useState(isEdit ? detail?.campPlace : FILTER_PLACEHOLDER);
  const [region, setRegion] = useState(isEdit ? detail?.region : FILTER_PLACEHOLDER);
  const [area, setArea] = useState(isEdit ? detail?.location || '' : '');
  const [postcode, setPostcode] = useState(isEdit ? detail?.postcode : '');
  const [isFlood, setIsFlood] = useState(isEdit ? detail?.isFloodArea || false : false);

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

  return (
    <View className="m-4 flex-1 justify-start bg-primary-bg">
      {!isLoading ? (
        <ScrollView>
          <Title text="Základní informace" />
          {!isEdit && (
            <View className="mt-4">
              <TextFieldSelect
                title="Pořadatel"
                items={camps?.map(camp => camp.sortName) || []}
                value={selectedCamp}
                setValue={setSelectedCamp}
              />
            </View>
          )}

          <UnitSelect
            unitId={camps?.find(camp => camp.sortName === selectedCamp)?.id || ''}
            selectedUnitIds={selectedUnitIds}
            setSelectedUnitIds={setSelectedUnitIds}
          />

          <Text className="mt-4 font-bold">Vybrat jiný typ tábora</Text>
          <View className="rounded bg-secondary-bg py-4">
            <CheckboxList
              items={(campTypes || [])?.map(type => ({
                value: type.id,
                label: type.displayName,
              }))}
              selected={value => selectedCampType.includes(value?.value || '')}
              onPress={value => {
                if (selectedCampType.includes(value?.value || '')) {
                  setSelectedCampType(prev => prev.filter(selected => selected !== value?.value));
                } else {
                  setSelectedCampType([value?.value || '']);
                }
              }}
            />
          </View>

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

          <View className="mb-4">
            <TextField title="Mobilní kontakt (během tábora)" value={mobile} setValue={setMobile} />
          </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">
            <TextFieldSelect
              title="Místo konání"
              items={campPlaces?.map(place => place.displayName) || []}
              value={campPlace}
              setValue={setCampPlace}
            />
          </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="Katastrální území" value={area} setValue={setArea} />
          </View>

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

          <View className="flex-row items-center justify-between">
            <Text className="font-bold">Hrozí povodně</Text>
            <Switch setIsEnabled={setIsFlood} isEnabled={isFlood} />
          </View>

          <View>
            <FormButtons
              submitText={isEdit ? 'Upravit' : 'Vytvořit'}
              onSubmit={() => {
                let error;
                if (!postcode?.length) error = 'Zadejte PSČ.';
                if (!area.length) error = 'Zadejte katastrální území.';
                if (region === FILTER_PLACEHOLDER) error = 'Vyberte región.';
                if (campPlace === FILTER_PLACEHOLDER) error = 'Vyberte místo konání.';
                if (!startDate) error = 'Vyberte datum začátku konání.';
                if (!endDate) error = 'Vyberte datum konce konání.';
                if (!mobile.length) error = 'Zadejte mobilní kontakt.';
                if (!name.length) error = 'Zadejte název tábora.';
                if (selectedUnitIds.length === 0) error = 'Vyberte alespoň jednu 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: EventCampInsertPayload = {
                  displayName: name,
                  unitId: camps?.find(camp => camp.sortName === selectedCamp)?.id || '',
                  region: region === FILTER_PLACEHOLDER ? '' : region || '',
                  regionId:
                    regions?.find(regionItem => regionItem.displayName === region)?.id || '',
                  startDate: (startDate || new Date()).toISOString(),
                  endDate: (endDate || new Date()).toISOString(),
                  location: area,
                  note,
                  mobile: mobile.replace('+420', '').replace(/ /g, ''),
                  postcode: postcode || '',
                  isFloodArea: isFlood,
                  campPlaceId:
                    campPlace === FILTER_PLACEHOLDER
                      ? ''
                      : campPlaces?.find(place => place.displayName === campPlace)?.id || '',
                  subUnitIds: selectedUnitIds,
                  campTypeIds: selectedCampType,
                };
                mutateCamp(payload);
              }}
            />
          </View>
        </ScrollView>
      ) : (
        <Loader />
      )}
    </View>
  );
};

export default CampEdit;
