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

import IconButton from '../../../../../../components/Button/IconButton';
import DetailList from '../../../../../../components/List/DetailList';
import MenuList from '../../../../../../components/List/MenuList';
import Loader from '../../../../../../components/Loader/Loader';
import ConfirmationModal from '../../../../../../components/Modal/ConfirmationModal';
import { NavProps, RouteProps } from '../../../../../../components/Routes/Routes';
import { EVENTS_RELATIONS } from '../../../../../../constants/custom';
import { getDateAsString } from '../../../../../../helpers/stringHelpers';
import {
  useEventDelete,
  useEventDetail,
  useEventGeneralAllGet,
} from '../../../../../../hooks/useEvents';
import { useUserInfo } from '../../../../../../hooks/useStorage';
import { openMapApp } from '../../../../../../services/nativeHelpers/openMapApp';

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

  const { detail, isLoading } = useEventDetail(userInfo.token, id);

  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: deleteEvent } = useEventDelete(userInfo.token, refetchEvents, navigation.goBack);
  const [isDeleteModalVisible, setIsDeleteModalVisible] = useState(false);

  useLayoutEffect(() => {
    navigation.setOptions({
      title: detail?.displayName || eventName,
      headerRight: () => {
        if (!detail.isEditable || !isRelation) return null;
        return (
          <View className="flex-row items-center">
            <IconButton
              classNames="mr-2"
              variant="secondary"
              onPress={() =>
                navigation.navigate('EventEdit', {
                  id,
                  filterIsFuture,
                  filterYear,
                  filterRelationValue,
                  filterTypeId,
                  filterStateId,
                  filterScopeId,
                })
              }
            >
              <FontAwesome5 name="edit" size={24} />
            </IconButton>
            <IconButton variant="secondary" onPress={() => setIsDeleteModalVisible(true)}>
              <FontAwesome name="trash" size={28} />
            </IconButton>
          </View>
        );
      },
    });
  }, [navigation, eventName, detail]);

  return (
    <View className="m-4 flex-1 justify-start bg-primary-bg">
      <ScrollView>
        <MenuList
          items={[
            {
              title: 'Tým',
              icon: <FontAwesome5 name="user-friends" size={24} />,
              onPress: () => navigation.navigate('EventTeam', { id, eventName, isRelation }),
            },
            {
              title: 'Účastníci',
              icon: <FontAwesome5 name="users" size={24} />,
              onPress: () =>
                navigation.navigate('EventParticipants', { id, eventName, isRelation }),
            },
            {
              title: 'Zpráva z akce',
              icon: <FontAwesome5 name="envelope" size={24} />,
              onPress: () => navigation.navigate('EventMessage', { id, eventName, isRelation }),
            },
            {
              title: 'Stav a odevzdání',
              icon: <FontAwesome5 name="paragraph" size={24} />,
              onPress: () => navigation.navigate('EventState', { id, eventName, isRelation }),
            },
          ]}
        />
        {!isLoading ? (
          <View>
            <DetailList
              title={{
                text: 'Obecná akce',
              }}
              items={[
                {
                  title: 'Pořádatel:',
                  value: `${detail?.regNumber} - ${detail?.unit}`,
                  classNames: 'text-secondary',
                  onPress: () =>
                    navigation.navigate('UnitInfo', {
                      id: detail?.unitId || '',
                    }),
                },
                ...(detail?.eduUnitRegNumber
                  ? [
                      {
                        title: 'Oddíl/družina:',
                        value: `${detail?.eduUnitRegNumber} - ${detail?.eduUnit}`,
                        classNames: 'text-secondary',
                        onPress: () =>
                          navigation.navigate('UnitInfo', {
                            id: detail?.eduUnitId || '',
                          }),
                      },
                    ]
                  : []),
                {
                  title: 'Stav:',
                  value: detail?.state,
                },
                ...(detail?.personClosed
                  ? [
                      {
                        title: 'Osoba, která akci uzavřela:',
                        value: detail?.personClosed,
                      },
                    ]
                  : []),
                ...(detail?.dateClosed
                  ? [
                      {
                        title: 'Datum uzavření:',
                        value: getDateAsString(new Date(detail.dateClosed)),
                      },
                    ]
                  : []),
                {
                  title: 'Termín akce:',
                  value:
                    !detail?.startDate || !detail.endDate
                      ? 'Bez omezení'
                      : `od ${getDateAsString(new Date(detail.startDate))} do ${getDateAsString(
                          new Date(detail.endDate),
                        )}`,
                },
                {
                  title: 'Typ akce:',
                  value: detail?.type,
                },
                {
                  title: 'Rozsah akce:',
                  value: detail?.scope,
                },
                {
                  title: 'Poznámka:',
                  value: detail?.note,
                },
              ]}
            />

            <DetailList
              title={{
                text: 'Místo konání',
                icons: [
                  {
                    element: <FontAwesome5 name="map-marked-alt" size={24} />,
                    onPress: () =>
                      openMapApp(
                        detail?.latitude &&
                          detail.longitude &&
                          detail.latitude !== '0' &&
                          detail.longitude !== '0'
                          ? `${detail?.latitude}, ${detail.longitude}`
                          : detail?.location || '',
                      ),
                  },
                ],
              }}
              items={[
                {
                  title: 'Katastrální území:',
                  value: detail?.location,
                },
                {
                  title: 'PSČ obce:',
                  value: detail?.postcode,
                },
                {
                  title: 'Region:',
                  value: detail?.region,
                },
              ]}
            />
          </View>
        ) : (
          <Loader />
        )}
      </ScrollView>
      <ConfirmationModal
        isVisible={isDeleteModalVisible}
        setIsVisible={setIsDeleteModalVisible}
        title="Smazat akci"
        text="Opravdu chcete tuto akci smazat? Akce bude smazána permanentně."
        onConfirm={() => deleteEvent(id)}
      />
    </View>
  );
};

export default EventDetail;
