import { FontAwesome5, FontAwesome } from '@expo/vector-icons';
import { useNavigation, useRoute } from '@react-navigation/native';
import React, { useLayoutEffect, useState } from 'react';
import { View, Text, ScrollView, TouchableOpacity } 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 {
  useCampDetail,
  useEventCampAll,
  useEventCampDelete,
} from '../../../../../../hooks/useCamps';
import { useUserInfo } from '../../../../../../hooks/useStorage';
import { openMapApp } from '../../../../../../services/nativeHelpers/openMapApp';

const CampDetail = () => {
  const {
    id,
    isRelation,
    campName,
    filterName,
    filterIsFuture,
    filterLocation,
    filterRegNumber,
    filterRelationValue,
    filterYear,
  } = useRoute<RouteProps<'CampDetail'>>().params;
  const navigation = useNavigation<NavProps>();
  const [userInfo] = useUserInfo();

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

  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 { mutate: deleteCamp } = useEventCampDelete(
    userInfo.token,
    refetchCamps,
    navigation.goBack,
  );
  const [isDeleteModalVisible, setIsDeleteModalVisible] = useState(false);

  useLayoutEffect(() => {
    navigation.setOptions({
      title: detail.displayName || campName,
      headerRight: () => {
        if (!detail.isEditable || !isRelation) return null;
        return (
          <View className="flex-row items-center">
            <IconButton
              classNames="mr-2"
              variant="secondary"
              onPress={() =>
                navigation.navigate('CampEdit', {
                  id,
                  filterName,
                  filterIsFuture,
                  filterLocation,
                  filterRegNumber,
                  filterRelationValue,
                  filterYear,
                })
              }
            >
              <FontAwesome5 name="edit" size={24} />
            </IconButton>
            <IconButton variant="secondary" onPress={() => setIsDeleteModalVisible(true)}>
              <FontAwesome name="trash" size={28} />
            </IconButton>
          </View>
        );
      },
    });
  }, [navigation, campName, 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('CampTeam', { id, campName, isRelation }),
            },
            {
              title: 'Účastníci',
              icon: <FontAwesome5 name="users" size={24} />,
              onPress: () => navigation.navigate('CampParticipants', { id, campName, isRelation }),
            },
            {
              title: 'Stav a odevzdání',
              icon: <FontAwesome5 name="paragraph" size={24} />,
              onPress: () => navigation.navigate('CampState', { id, campName, isRelation }),
            },
          ]}
        />
        {!isLoading ? (
          <View>
            <DetailList
              title={{
                text: 'Tábor',
              }}
              items={[
                {
                  title: 'Pořádatel:',
                  value: `${detail?.regNumber} - ${detail?.unit}`,
                  classNames: 'text-secondary',
                  onPress: () =>
                    navigation.navigate('UnitInfo', {
                      id: detail?.unitId || '',
                    }),
                },
                {
                  title: 'Oddíly:',
                  children: (
                    <View className="flex-warp flex">
                      {detail?.units?.map(unit => (
                        <TouchableOpacity
                          key={unit?.id}
                          onPress={() =>
                            navigation.navigate('UnitInfo', {
                              id: unit?.id || '',
                            })
                          }
                        >
                          <Text className="text-right text-secondary">{`${unit?.regNumber} - ${unit?.displayName}`}</Text>
                        </TouchableOpacity>
                      ))}
                    </View>
                  ),
                },
                {
                  title: 'Stav:',
                  value: detail?.state,
                },
                {
                  title: 'Typ:',
                  value: detail?.type || 'Bez omezení',
                },
                {
                  title: 'Termín tábora:',
                  value:
                    !detail.startDate || !detail.endDate
                      ? 'Bez omezení'
                      : `od ${getDateAsString(new Date(detail.startDate))} do ${getDateAsString(
                          new Date(detail.endDate),
                        )}`,
                },
                {
                  title: 'Celkem dnů:',
                  value: detail?.totalDays,
                },
                ...(detail?.isRecovering
                  ? [
                      {
                        title: 'Zotavovací akce:',
                        value: detail?.isRecovering ? 'Ano' : 'Ne',
                      },
                    ]
                  : []),
                {
                  title: 'Mobilní kontakt:',
                  value: detail?.mobile,
                },
              ]}
            />

            <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: 'Místo, kde se tábor koná:',
                  value: detail?.campPlace,
                },
                {
                  title: 'Kraj:',
                  value: detail?.region,
                },
                {
                  title: 'Katastrální území:',
                  value: detail?.location,
                },
                {
                  title: 'PSČ obce:',
                  value: detail?.postcode,
                },
                ...(detail?.isFloodArea
                  ? [
                      {
                        title: 'Hrozí povodně:',
                        value: detail?.isFloodArea ? 'Ano' : 'Ne',
                      },
                    ]
                  : []),
                {
                  title: 'Poznámka:',
                  value: detail?.note,
                },
              ]}
            />
          </View>
        ) : (
          <Loader />
        )}
      </ScrollView>
      <ConfirmationModal
        isVisible={isDeleteModalVisible}
        setIsVisible={setIsDeleteModalVisible}
        title="Smazat tábor"
        text="Opravdu chcete tento tábor smazat? Tábor bude smazána permanentně."
        onConfirm={() => deleteCamp(id)}
      />
    </View>
  );
};

export default CampDetail;
