import { FontAwesome5, FontAwesome } from '@expo/vector-icons';
import { useNavigation, useRoute } from '@react-navigation/native';
import cn from 'classnames';
import React, { useEffect, useLayoutEffect, useState } from 'react';
import { View, Image, ScrollView } from 'react-native';

import DetailList from '../../../../../../components/List/DetailList';
import MenuList from '../../../../../../components/List/MenuList';
import Title from '../../../../../../components/List/components/Title';
import Loader from '../../../../../../components/Loader/Loader';
import ConfirmationModal from '../../../../../../components/Modal/ConfirmationModal';
import { NavProps, RouteProps } from '../../../../../../components/Routes/Routes';
import { SKAUTIS_EDU_EVENT_ENROLL_URL } from '../../../../../../constants/api';
import { getDateAsString } from '../../../../../../helpers/stringHelpers';
import {
  useEducationDetail,
  useEnrollReminderDelete,
  useEnrollReminderDetail,
} from '../../../../../../hooks/useEducation';
import { useUserInfo } from '../../../../../../hooks/useStorage';
import { openMapApp } from '../../../../../../services/nativeHelpers/openMapApp';
import { openURL } from '../../../../../../services/nativeHelpers/openURL';
import { sendEmail } from '../../../../../../services/nativeHelpers/sendEmail';
import NotificationDetailModal from './components/NotificationDetailModal';

const EducationDetail = () => {
  const { id, educationName, logo, reminderId, educationCourseId, hasNoAPiReminder } =
    useRoute<RouteProps<'EducationDetail'>>().params;
  const [userInfo] = useUserInfo();
  const navigation = useNavigation<NavProps>();
  const [first, setFirst] = useState(true);

  const { courses, detail, enrollId, termWithLocations, isLoading } = useEducationDetail(
    userInfo.token,
    id,
  );

  const [isCancelModalVisible, setIsCancelModalVisible] = useState(false);

  const [currentEnrollId, setCurrentEnrollId] = useState(
    hasNoAPiReminder ? enrollId : reminderId || '',
  );

  useEffect(() => {
    if (first && enrollId) {
      setCurrentEnrollId(enrollId);
      setFirst(false);
    }
  }, [enrollId]);

  const { mutate: cancelNotification } = useEnrollReminderDelete(
    userInfo.token,
    setCurrentEnrollId,
  );

  const { data: remindHours } = useEnrollReminderDetail(
    userInfo.token,
    currentEnrollId || '',
    !currentEnrollId && hasNoAPiReminder,
  );

  const enroll = async () => {
    const skuatIsUrl = `${SKAUTIS_EDU_EVENT_ENROLL_URL}?ID_EventEducationCourse=${educationCourseId}&ID_EventEducation=${detail?.id}`;
    let url =
      !detail?.loginLocation.length || detail.loginSkautis ? skuatIsUrl : detail?.loginLocation;
    if (!url.startsWith('http://') && !url.startsWith('https://')) {
      url = 'http://' + url;
    }
    await openURL(url);
  };

  const canEnroll =
    (detail?.loginSkautis || detail?.loginLocation.length) &&
    (!detail?.loginTo.length || new Date(detail?.loginTo) > new Date()) &&
    (!detail?.loginFrom.length || new Date(detail?.loginFrom) <= new Date());

  const canSetNotification =
    (!detail?.loginFrom.length || new Date(detail?.loginFrom) > new Date()) &&
    !!detail?.startDate &&
    !!detail?.endDate &&
    detail?.loginSkautis === 'true';

  const [isNotificationModalOpen, setIsNotificationModalOpen] = useState(false);

  useLayoutEffect(() => {
    navigation.setOptions({
      title: educationName,
    });
  }, [navigation, educationName]);

  return (
    <View className="m-4 flex-1 justify-start bg-primary-bg">
      {!isLoading ? (
        <ScrollView>
          <View className="flex-row items-center justify-center">
            {!!logo?.length && (
              <Image
                className="h-[60px] w-[60px] rounded"
                source={{ uri: `data:image/png;base64,${logo}` }}
              />
            )}
          </View>

          <MenuList
            classNames={cn('mb-4', { 'mt-4': !!logo?.length })}
            items={[
              {
                title: 'Přihlásit se',
                icon: <FontAwesome name="sign-in" size={24} />,
                onPress: () => enroll(),
                disabled: !canEnroll,
              },
              {
                title: currentEnrollId ? 'Zrušit notifikaci' : 'Nastavit notifikaci',
                icon: <FontAwesome name={`${currentEnrollId ? 'bell-slash' : 'bell'}`} size={24} />,
                onPress: () =>
                  currentEnrollId
                    ? setIsCancelModalVisible(true)
                    : setIsNotificationModalOpen(true),
                disabled: !canSetNotification,
              },
              {
                title: 'Další údaje',
                icon: <FontAwesome5 name="info-circle" size={24} />,
                onPress: () =>
                  navigation.navigate('EducationOtherDetail', {
                    id,
                    educationName,
                  }),
              },
              {
                title: 'Stav a odevzdání',
                icon: <FontAwesome5 name="user-check" size={24} />,
                onPress: () => navigation.navigate('EducationStatus', { id, educationName }),
              },
            ]}
          />

          <DetailList
            title={{
              text: 'Vzdělávací akce',
            }}
            items={[
              {
                title: 'Pořádající jednotka:',
                value: `${detail?.registrationNumber} - ${detail?.unit}`,
                classNames: 'text-secondary',
                onPress: () =>
                  navigation.navigate('UnitInfo', {
                    id: detail?.unitId || '',
                  }),
              },
              { title: 'Místo konání:', value: detail?.location },
            ]}
          />

          <DetailList
            title={{
              text: 'Kontakty',
            }}
            items={[
              ...(detail?.web.split(',').map((u, index) => {
                return {
                  title: `Web akce${detail?.web.split(',').length ? ` ${index + 1}` : ''}:`,
                  value: u.trim(),
                  classNames: 'text-secondary',
                  onPress: () => openURL(u.trim()),
                };
              }) || []),
              {
                title: 'Kontaktní email:',
                value: detail?.contactEmail,
                classNames: 'text-secondary',
                onPress: () => sendEmail(detail?.contactEmail),
              },
              {
                title: 'Kontaktní telefon:',
                value: detail?.contactPhone.replace(/(\d{3})(\d{3})(\d{3})/, `+$1 $2 $3`),
              },
              {
                title: 'Poznámka:',
                value: detail?.note,
              },
            ]}
          />

          {!!courses?.length && <Title classNames="mt-4" text="Kurzy" center />}

          {courses?.map((course, index) => (
            <DetailList
              key={index}
              title={{
                text: course.type,
              }}
              items={[
                {
                  title: 'Obsazenost:',
                  value: course.capacity,
                },
                ...(course.courseCapacity
                  ? [
                      {
                        title: 'Kapacita kurzu:',
                        value: course.courseCapacity,
                      },
                    ]
                  : []),
                ...(course.substituteCapacity
                  ? [
                      {
                        title: 'Kapacita náhradníků:',
                        value: course.substituteCapacity,
                      },
                    ]
                  : []),
                ...(course.estimateCapacity
                  ? [
                      {
                        title: 'Odhad počtu účastníků:',
                        value: course.estimateCapacity,
                      },
                    ]
                  : []),
                ...(course.deadline
                  ? [
                      {
                        title: 'Uzávěrka přihlášek:',
                        value: getDateAsString(new Date(course.deadline)),
                      },
                    ]
                  : []),
                {
                  title: 'Osobodny:',
                  value: course.personDays,
                },
                {
                  title: 'Poznámka:',
                  value: course.note,
                },
              ]}
            />
          ))}

          {!!termWithLocations?.length && (
            <Title classNames="mt-4" text="Termíny a umístění kurzu" center />
          )}
          {termWithLocations?.map((term, index) => (
            <DetailList
              key={index}
              title={{
                text: term.course,
                icons: [
                  {
                    element: <FontAwesome5 name="map-marked-alt" size={24} />,
                    onPress: () =>
                      openMapApp(
                        term.locationInfo?.latitude &&
                          term.locationInfo.longitude &&
                          term.locationInfo?.latitude !== '0' &&
                          term.locationInfo?.longitude !== '0'
                          ? `${term.locationInfo?.latitude}, ${term.locationInfo.longitude}`
                          : term.location,
                      ),
                  },
                ],
              }}
              items={[
                {
                  title: 'Umístění kurzu:',
                  value: term.location,
                },
                {
                  title: 'Termín:',
                  value: term.date,
                },
                ...(term.locationInfo?.firstLine
                  ? [
                      {
                        title: 'První řádka:',
                        value: term.locationInfo?.firstLine,
                      },
                    ]
                  : []),
                ...(term.locationInfo?.street
                  ? [
                      {
                        title: 'Ulice a číslo:',
                        value: term.locationInfo?.street,
                      },
                    ]
                  : []),
                ...(term.locationInfo?.postcode
                  ? [
                      {
                        title: 'PSČ obce:',
                        value: term.locationInfo?.postcode,
                      },
                    ]
                  : []),
                ...(term.locationInfo?.city
                  ? [
                      {
                        title: 'Město:',
                        value: term.locationInfo?.city,
                      },
                    ]
                  : []),
                ...(term.locationInfo?.region
                  ? [
                      {
                        title: 'Kraj:',
                        value: term.locationInfo?.region,
                      },
                    ]
                  : []),
                ...(term.locationInfo?.note
                  ? [
                      {
                        title: 'Poznámka:',
                        value: term.locationInfo?.note,
                      },
                    ]
                  : []),
              ]}
            />
          ))}
        </ScrollView>
      ) : (
        <Loader />
      )}
      <NotificationDetailModal
        isVisible={isNotificationModalOpen}
        setIsVisible={setIsNotificationModalOpen}
        reminderId={currentEnrollId}
        setReminderId={setCurrentEnrollId}
        educationId={educationCourseId}
        id={detail?.id || ''}
      />
      <ConfirmationModal
        isVisible={isCancelModalVisible}
        setIsVisible={setIsCancelModalVisible}
        title="Zrušit upozornění"
        text={`Opravdu se chcete zrušit upozernění? Momentálně máte nastaveno upozornění na ${remindHours} hodin před začátkem akce.`}
        onConfirm={() => {
          cancelNotification(currentEnrollId || '');
        }}
      />
    </View>
  );
};

export default EducationDetail;
