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

import IconButton from '../../../../../../components/Button/IconButton';
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 Table from '../../../../../../components/Table/Table';
import { useUserInfo } from '../../../../../../hooks/useStorage';
import { useExportPersonViewGet } from '../../../../../../hooks/useTeplates';
import { sendEmails } from '../../../../../../services/nativeHelpers/sendEmail';
import { sendSmss } from '../../../../../../services/nativeHelpers/sendSms';
import TemplateDownloadModal from './components/TemplateDownloadModal';

const TemplateDetail = () => {
  const { id, templateName } = useRoute<RouteProps<'TemplateDetail'>>().params;
  const navigation = useNavigation<NavProps>();
  const [userInfo] = useUserInfo();

  const { data: templateDetail, isLoading } = useExportPersonViewGet(userInfo.token, id);
  const [selectedRows, setSelectedRows] = useState<string[][]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);

  useLayoutEffect(() => {
    navigation.setOptions({
      title: templateName,
      headerRight: () => {
        return (
          <View className="flex-row items-center">
            <IconButton
              classNames="mr-2"
              variant="secondary"
              onPress={() => setIsModalVisible(true)}
            >
              <FontAwesome5 name="file-download" size={24} />
            </IconButton>
          </View>
        );
      },
    });
  }, [navigation, templateName]);

  const showName = Object.values(templateDetail || {}).some(item => item.name);
  const showEmail = Object.values(templateDetail || {}).some(item => item.email);
  const showPhone = Object.values(templateDetail || {}).some(item => item.phone);

  const tableHeader = [
    ...(showName
      ? [
          {
            title: 'Jméno',
          },
        ]
      : []),
    ...(showEmail
      ? [
          {
            title: 'Email',
          },
        ]
      : []),
    ...(showPhone
      ? [
          {
            title: 'Telefon',
          },
        ]
      : []),
  ];

  const phoneIndex = showName && showEmail ? 2 : showName || showEmail ? 1 : 0;
  const phones = selectedRows.map(row => row[phoneIndex]).filter(phone => phone && phone !== '');

  const emailsIndex = showName ? 1 : 0;
  const emails = selectedRows.map(row => row[emailsIndex]).filter(email => email && email !== '');

  return (
    <View className="mx-4 mb-4 flex-1 bg-primary-bg">
      {!isLoading ? (
        <>
          {showEmail || showPhone ? (
            <>
              <Title text="Hromadné akce" classNames="my-4" />
              <MenuList
                items={[
                  {
                    title: 'Poslat zprávu',
                    icon: <FontAwesome5 name="sms" size={24} />,
                    onPress: () => sendSmss(phones),
                    disabled: phones.length === 0,
                  },
                  {
                    title: 'Poslat email',
                    icon: <FontAwesome name="envelope-o" size={24} />,
                    onPress: () => sendEmails(emails),
                    disabled: emails.length === 0,
                  },
                ]}
              />
            </>
          ) : null}
          <View className="min-h-5 flex-1">
            <Table
              selected={showEmail || showPhone ? selectedRows : undefined}
              onSelect={
                showEmail || showPhone
                  ? (value, item) => {
                      if (value) {
                        setSelectedRows([...selectedRows, item]);
                      } else {
                        setSelectedRows(selectedRows.filter(row => row[0] !== item[0]));
                      }
                    }
                  : undefined
              }
              onSelectAll={
                showEmail || showPhone
                  ? (value, items) => {
                      if (value) {
                        setSelectedRows(items);
                      } else {
                        setSelectedRows([]);
                      }
                    }
                  : undefined
              }
              header={tableHeader.map((item, index) => {
                const width =
                  tableHeader.length === 1
                    ? 'w-[90%]'
                    : tableHeader.length === 2
                    ? 'w-[45%]'
                    : 'w-[30%]';
                return {
                  title: item.title,
                  classNames: `${width} ${
                    index === tableHeader.length - 1 && tableHeader.length > 1 ? 'text-right' : ''
                  }`,
                };
              })}
              items={Object.values(templateDetail || {})?.map(person => [
                ...(showName ? [person.name || ''] : []),
                ...(showEmail ? [person.email || ''] : []),
                ...(showPhone ? [person.phone || ''] : []),
              ])}
              emptyElement={
                <Text className="rounded bg-secondary-bg p-4">
                  Danný export nemá žádné jména, emaily nebo telefony.
                </Text>
              }
            />
          </View>
        </>
      ) : (
        <Loader />
      )}
      <TemplateDownloadModal
        isVisible={isModalVisible}
        setIsVisible={setIsModalVisible}
        exportId={id}
      />
    </View>
  );
};

export default TemplateDetail;
