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

import IconButton from '../../components/Button/IconButton';
import DetailList from '../../components/List/DetailList';
import PhoneDetail from '../../components/List/components/PhoneDetail';
import Title from '../../components/List/components/Title';
import Loader from '../../components/Loader/Loader';
import { RouteProps } from '../../components/Routes/Routes';
import { usePerson } from '../../hooks/usePerson';
import { useUserInfo } from '../../hooks/useStorage';
import { addContact } from '../../services/nativeHelpers/addContact';
import { openMapApp } from '../../services/nativeHelpers/openMapApp';
import { sendEmail } from '../../services/nativeHelpers/sendEmail';

const PersonDetail = () => {
  const { id, isFromCatalog } = useRoute<RouteProps<'PersonDetail'>>().params;
  const [userInfo] = useUserInfo();

  const { person, isLoading } = usePerson(userInfo.token, id, isFromCatalog);

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

            <View className="flex grow space-y-4">
              <View className="flex-row items-center">
                <Title classNames="mr-4" text={`${person?.firstName} ${person?.lastName}`} />
                <IconButton variant="secondary" onPress={() => addContact(person)}>
                  <FontAwesome name="address-book-o" size={20} />
                </IconButton>
              </View>

              {(person?.email || person?.phone) && (
                <View className="flex grow rounded bg-secondary-bg p-2">
                  {person?.phone && (
                    <View className="p-2">
                      <PhoneDetail value={person.phone?.displayValue} />
                    </View>
                  )}
                  {person?.email && (
                    <View className="flex-row rounded-sm bg-primary-bg p-2">
                      <TouchableOpacity onPress={() => sendEmail(person.email?.value)}>
                        <Text className="text-secondary">{person.email?.value}</Text>
                      </TouchableOpacity>
                    </View>
                  )}
                </View>
              )}
            </View>
          </View>

          <DetailList
            items={[
              person?.displayBirthday || !isFromCatalog
                ? { title: 'Datum narození:', value: person?.birthday }
                : undefined,
              person?.identificationCodeHasPermission || !isFromCatalog
                ? { title: 'Rodné číslo:', value: person?.identificationCode }
                : undefined,
              {
                title: 'Jednotka:',
                value: person?.membership?.find(u => u.membershipTypeId === 'radne')?.unit,
              },
              { title: 'Pohlaví:', value: person?.sex },
              { title: 'Přezdívka:', value: person?.nickName },
            ]}
          />

          {(person?.displayAddress || !isFromCatalog) && (
            <DetailList
              title={{
                text: 'Trvalé bydliště',
                icons: [
                  {
                    element: <FontAwesome5 name="map-marked-alt" size={24} />,
                    onPress: () => openMapApp(`${person?.city}, ${person?.street}`),
                  },
                ],
              }}
              items={[
                { title: 'Ulice:', value: person?.street },
                { title: 'Obec:', value: `${person?.city}, ${person?.postcode}` },
              ]}
            />
          )}

          <DetailList
            title={{ text: 'Kontakty osoby' }}
            items={person?.contacts?.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,
              };
            })}
          />

          {!isFromCatalog && (
            <DetailList
              title={{ text: 'Zdravotní údaje' }}
              items={[
                { title: 'Zdravotní pojišťovna:', value: person?.assurance },
                { title: 'Číslo pojišťence:', value: person?.insuranceNumber },
                { title: 'Alergie:', value: person?.allergy },
                { title: 'Prášky:', value: person?.drugs },
                { title: 'Zdravotní limity:', value: person?.healthLimitation },
                { title: 'Poznámka:', value: person?.note },
              ]}
            />
          )}

          {(!isFromCatalog || person?.displayFunction) && (
            <DetailList
              title={{ text: 'Činovnické funkce' }}
              items={person?.function?.map(item => ({ title: item.unit, value: item.function }))}
            />
          )}

          {(!isFromCatalog || person?.displayQualification) && (
            <DetailList
              title={{ text: 'Výpis kvalifikací' }}
              items={person?.qualification?.map(item => ({
                title: item.qualificationType,
                value: ' ',
              }))}
            />
          )}

          {(!isFromCatalog || person?.displayOffer) && (
            <DetailList
              title={{ text: 'Nabídky a vzdělání' }}
              items={person?.offer?.map(item => ({
                title: item.offerType,
                value: ' ',
              }))}
            />
          )}

          {(!isFromCatalog || person?.displayMembership) && (
            <DetailList
              title={{ text: 'Členem v jednotkách' }}
              items={person?.membership?.map(item => ({
                title: `${item.unit}:`,
                value: item.membershipType,
              }))}
            />
          )}
        </ScrollView>
      ) : (
        <Loader />
      )}
    </View>
  );
};

export default PersonDetail;
