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

import IconButton from '../../../../components/Button/IconButton';
import ClickableList from '../../../../components/List/ClickableList';
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 { NavProps, RouteProps } from '../../../../components/Routes/Routes';
import { useUserInfo } from '../../../../hooks/useStorage';
import { useUnit } from '../../../../hooks/useUnit';
import { openMapApp } from '../../../../services/nativeHelpers/openMapApp';
import { sendEmail } from '../../../../services/nativeHelpers/sendEmail';

const UnitInfo = () => {
  const { id } = useRoute<RouteProps<'UnitInfo'>>().params;
  const [userInfo] = useUserInfo();
  const navigation = useNavigation<NavProps>();
  const { unit, isLoading } = useUnit(userInfo.token, id);

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

  return (
    <View className="mx-4 mb-4 flex-1 justify-start bg-primary-bg">
      {!isLoading ? (
        <ScrollView>
          <DetailList
            title={{ text: 'Kontakty' }}
            items={unit?.contacts
              ?.filter(contact => contact.contactType.includes('hlavní'))
              .map(item => {
                const value = item?.value.includes('@') ? item.value : item.displayValue;
                return {
                  title: item.contactType,
                  value,
                  classNames: item?.value.includes('@') ? 'text-secondary' : '',
                  onPress: item?.value.includes('@') ? () => sendEmail(item?.value) : undefined,
                };
              })}
          />

          {unit?.addressExists && (
            <DetailList
              title={{
                text: 'Adresa jednoty',
                icons: [
                  {
                    element: <FontAwesome5 name="map-marked-alt" size={24} />,
                    onPress: () => openMapApp(`${unit?.city}, ${unit?.street}`),
                  },
                ],
              }}
              items={[
                { title: 'Ulice:', value: unit?.street },
                { title: 'Obec:', value: `${unit?.city}, ${unit?.postcode}` },
              ]}
            />
          )}

          {unit?.postalAddressExists && (
            <DetailList
              title={{
                text: 'Korespondenční adresa',
                icons: [
                  {
                    element: <FontAwesome5 name="map-marked-alt" size={24} />,
                    onPress: () => openMapApp(`${unit?.postalCity}, ${unit?.postalStreet}`),
                  },
                ],
              }}
              items={[
                { title: 'Ulice:', value: unit?.postalStreet },
                { title: 'Obec:', value: `${unit?.postalCity}, ${unit?.postalPostcode}` },
              ]}
            />
          )}

          <View className="mt-4">
            <ClickableList
              title={{
                text: 'Obsazení funkcí',
                icon: {
                  element: <Text className="text-md font-bold">Vše</Text>,
                  onPress: () => navigation.navigate('UnitFunctions', { id }),
                },
              }}
              items={unit.mainFunctions?.map(fnc => {
                return {
                  title: fnc.person,
                  subtitle: fnc.functionType,
                  onPress: () =>
                    navigation.navigate('PersonDetail', {
                      id: fnc.id,
                      isFromCatalog: false,
                    }),
                };
              })}
              emptyElement={
                <View className="mt-4 flex rounded bg-secondary-bg p-4">
                  <Text>Nepovedlo se načíst seznam činovníků.</Text>
                  <IconButton
                    classNames="font-bold"
                    variant="secondary"
                    onPress={() => navigation.navigate('UnitFunctions', { id })}
                  >
                    Zobrazit vše
                  </IconButton>
                </View>
              }
            />
          </View>

          {unit?.parentUnitId && (
            <>
              <Title classNames="my-4" text="Nadřazená OJ" />
              <MenuList
                items={[
                  {
                    title: unit.parentUnitName,
                    onPress: () =>
                      navigation.navigate('UnitDetail', { id: unit.parentUnitId || '' }),
                  },
                ]}
              />
            </>
          )}

          <View className="mt-4">
            <ClickableList
              title={{
                text: 'Podřízené jednotky',
              }}
              items={unit.unitTree?.map(u => {
                return {
                  title: u.unit,
                  subtitle: u.registrationNumber,
                  onPress: () => navigation.navigate('UnitDetail', { id: u.id }),
                };
              })}
              emptyElement={
                <View className="mt-4 flex rounded bg-secondary-bg p-4">
                  <Text>Tato jednotka nemá žádné podjednotky</Text>
                </View>
              }
            />
          </View>
        </ScrollView>
      ) : (
        <Loader />
      )}
    </View>
  );
};

export default UnitInfo;
