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 TextFieldTime from '../../../../../../components/TextField/TextFieldTime';
import { WEEKDAYS } from '../../../../../../constants/custom';
import { useUserInfo } from '../../../../../../hooks/useStorage';
import {
  useUnitAdvertisingMeetingDate,
  useUnitAdvertisingMeetingDateAdd,
  useUnitAdvertisingMeetingDateAll,
  useUnitPlaces,
} from '../../../../../../hooks/useUnitAdvertising';
import { MeetingDateDetailResponse } from '../../../../../../services/api/APIS/OrganizationUnit/types';
import { showFeedback } from '../../../../../../services/feedback/showFeedback';

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

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

  const {
    data: meetingDate,
    isLoading: isMeetingDateLoading,
    refetch: refetchMeetingDate,
  } = useUnitAdvertisingMeetingDate(userInfo.token, id || '');

  const { places, isLoading } = useUnitPlaces(userInfo.token, userInfo.unitId);
  const { refetch: refetchMeetingDates } = useUnitAdvertisingMeetingDateAll(
    userInfo.token,
    userInfo.unitId,
    true,
  );
  const { mutate: addMeetingDate } = useUnitAdvertisingMeetingDateAdd(
    userInfo.token,
    userInfo.unitId,
    refetchMeetingDates,
    navigation.goBack,
    id,
    refetchMeetingDate,
  );

  const [selectedDay, setSelectedDay] = useState<string>(meetingDate?.weekDay || '');
  const [timeFrom, setTimeFrom] = useState<Date | undefined>(meetingDate?.timeFrom);
  const [timeTo, setTimeTo] = useState<Date | undefined>(meetingDate?.timeTo);
  const [periodicity, setPeriodicity] = useState<string>(meetingDate?.periodicity || '');
  const [occupation, setOccupation] = useState<string>(
    isEdit
      ? places.find(
          o => o.id === meetingDate?.occupationId || (!o.id && !meetingDate?.occupationId.length),
        )?.displayName || ''
      : '',
  );

  useLayoutEffect(() => {
    navigation.setOptions({
      title: `${isEdit ? 'Upravit' : 'Přidat'} termín schůzky`,
    });
  }, [navigation]);

  return (
    <View className="m-4 flex-1 justify-start space-y-4 bg-primary-bg">
      {!isLoading && (!isEdit || (isEdit && !isMeetingDateLoading)) ? (
        <>
          <View>
            <TextFieldSelect
              title="Den v týdnu"
              items={WEEKDAYS.map(day => day.day)}
              value={selectedDay}
              setValue={setSelectedDay}
            />
          </View>
          <View>
            <TextFieldTime title="Čas začátku" value={timeFrom} setValue={setTimeFrom} />
          </View>
          <View>
            <TextFieldTime title="Čas konce" value={timeTo} setValue={setTimeTo} />
          </View>
          <View>
            <TextField title="Pravidelnost" value={periodicity} setValue={setPeriodicity} />
          </View>
          <View>
            <TextFieldSelect
              title="Klubovna"
              items={places.map(place => place.displayName)}
              value={occupation}
              setValue={setOccupation}
            />
          </View>
          <FormButtons
            onSubmit={() => {
              let error;
              if (!occupation) error = 'Vyberte klubovnu.';
              if (!timeTo) error = 'Vyberte čas konce.';
              if (!timeFrom) error = 'Vyberte čas začátku.';
              if (!selectedDay) error = 'Vyberte den v týdnu.';
              if (timeFrom && timeTo && timeFrom > timeTo)
                error = 'Čas začátku musí být menší než čas konce.';
              if (error) {
                showFeedback({
                  title: error,
                  type: 'danger',
                });
                return;
              }
              if (!selectedDay || !timeFrom || !timeTo || !occupation) return;
              const newMeetingDate: MeetingDateDetailResponse = {
                weekDayId: WEEKDAYS.find(day => day.day === selectedDay)?.id || '',
                weekDay: selectedDay,
                timeFrom,
                timeTo,
                periodicity,
                occupationId: places.find(place => place.displayName === occupation)?.id || '',
              };
              addMeetingDate(newMeetingDate);
            }}
          />
        </>
      ) : (
        <Loader />
      )}
    </View>
  );
};

export default UnitAdvertisingMeetingDateEdit;
