import React, { useEffect } from 'react';
import { Box, Icon, MainButton, Text } from '@nova-hf/ui';
import { ProfileBoxItemLoading } from 'components/profile-list/ProfileBoxItemLoading';
import { ProfileListItemLoading } from 'components/profile-list/ProfileListItemLoading';
import { inject } from 'mobx-react';
import Authentication from 'store/authentication';
import {
  EquipmentRentalStatus,
  EquipmentRentalVariant,
  useEquipmentRentalsQuery,
  useMeAddressQuery,
} from 'typings/graphql';
import { formatPrice, objectToQuery } from 'utils/helpers';
import { useTranslation } from 'utils/i18n';

type EquipmentRentalsProps = {
  isList: boolean;
  nationalId: string;
  authentication?: Authentication;
  hasEquipment?: (length: number) => void;
};
const EquipmentRentals = ({
  isList,
  nationalId,
  authentication,
  hasEquipment,
}: EquipmentRentalsProps) => {
  const { t } = useTranslation('subscription');
  const isNotNationalId = nationalId.length !== 10;
  const { data, loading, error } = useEquipmentRentalsQuery({
    variables: { input: { customerSsn: nationalId } },
    skip: isNotNationalId,
  });

  const { data: meDataAddress } = useMeAddressQuery({
    skip: !authentication?.accountInput,
    variables: { accountInput: authentication?.accountInput ?? {} },
  });

  const findGroupTitle = (arrOfRentals: EquipmentRentalVariant[]) => {
    if (arrOfRentals.length) {
      if (arrOfRentals.find((item) => item?.variant?.name.toLowerCase().includes('kastarinn'))) {
        return t('equipmentRentals.kastarinn');
      }
      if (arrOfRentals.find((item) => item?.variant?.name.toLowerCase().includes('ajax'))) {
        return t('equipmentRentals.sjalfsvorn');
      } else return t('equipmentRentals.defaultTitle');
    }
  };

  const findTotalSum = (arrOfRentals: EquipmentRentalVariant[]): number => {
    return arrOfRentals.reduce(
      (sum, item) =>
        sum +
        (item?.variant?.rentalOptions?.length ? item.variant.rentalOptions[0]?.price ?? 0 : 0),
      0,
    );
  };

  useEffect(() => {
    if (data?.equipmentRentals?.length && hasEquipment) {
      hasEquipment(data?.equipmentRentals?.length);
    }
  }, [data?.equipmentRentals?.length]);

  if (loading)
    return (
      <>
        {isList ? (
          <ProfileListItemLoading color="green" />
        ) : (
          <ProfileBoxItemLoading inGrid color="green" />
        )}
      </>
    );

  if (error || !data || !data.equipmentRentals?.length) return null;

  const activeEquipmentRentals =
    data.equipmentRentals[0]?.__typename === 'EquipmentRentalVariant'
      ? (data.equipmentRentals as EquipmentRentalVariant[]).filter(
          (option) =>
            option?.equipmentRental?.status === EquipmentRentalStatus.Active &&
            !option?.variant?.name.toLowerCase().includes('beinir') &&
            !option?.variant?.name.toLowerCase().includes('ráter') &&
            !option?.variant?.name.toLowerCase().includes('kastari'),
        )
      : null;

  if (!activeEquipmentRentals) return null;

  const equipmentRentalVariantMap = new Map<string, EquipmentRentalVariant[]>();
  activeEquipmentRentals?.map((rentalObject) => {
    if (
      !!rentalObject.equipmentRental?.orderId &&
      typeof rentalObject.equipmentRental.orderId === 'string'
    ) {
      const orderId: string = rentalObject.equipmentRental.orderId;
      if (equipmentRentalVariantMap.has(orderId)) {
        equipmentRentalVariantMap.get(orderId)?.push(rentalObject);
      } else {
        equipmentRentalVariantMap.set(orderId, [rentalObject]);
      }
    }
  });

  return (
    <>
      {Array.from(equipmentRentalVariantMap.values()).map((rentalArr) => {
        const redirectQueryParam = objectToQuery({
          ssn: rentalArr[0].equipmentRental?.customerSsn ?? '',
          orderId: rentalArr[0].equipmentRental?.orderId ?? '',
        });
        return (
          <>
            {isList ? (
              <Box
                width="100%"
                paddingX={3}
                paddingY={4}
                display="flex"
                borderBottomStyle="solid"
                borderColor="grey100"
                borderWidth="1px"
              >
                <Box width="5/12">
                  <Text variant="pLargeBold" color="green">
                    {findGroupTitle(rentalArr)}
                  </Text>
                  <Text renderAs="div">{meDataAddress?.me?.userProfile?.name}</Text>
                </Box>
                <Box width="4/12" marginLeft={-1}>
                  <Text variant="pLargeBold" color="green">{`${rentalArr?.length}x ${t(
                    'equipmentRentals.itemCount',
                  )} `}</Text>
                  <Text renderAs="div">
                    {`${meDataAddress?.me?.userProfile?.streetAddress}, ${meDataAddress?.me?.userProfile?.postalCode}`}
                  </Text>
                </Box>
                <Box width="3/12" paddingRight={5}>
                  <Text variant="pLargeBold" textAlign="right">
                    {formatPrice(findTotalSum(rentalArr) ?? 0)}
                  </Text>
                </Box>
              </Box>
            ) : (
              <Box width={{ sm: '100%', md: '6/12', lg: '4/12' }} paddingX={2} marginBottom={3}>
                <Box background="white" dottedShadow="small" boxShadow="small">
                  <Box background="green" paddingX={5} paddingTop={6} paddingBottom={3}>
                    <Text variant="h6" color="white">
                      {findGroupTitle(rentalArr)}
                    </Text>
                    <Box display="flex" justifyContent="space-between">
                      <Text variant="pLargeRegular" color="white">
                        {`${meDataAddress?.me?.userProfile?.streetAddress}, ${meDataAddress?.me?.userProfile?.postalCode}`}
                      </Text>
                      <Text variant="pLargeRegular" color="white">
                        {formatPrice(findTotalSum(rentalArr) ?? 0)}
                      </Text>
                    </Box>
                  </Box>

                  {rentalArr.map((rentalOption) => {
                    return (
                      <Box
                        key={rentalOption.equipmentRental?.id}
                        padding={3}
                        background="white"
                        display="flex"
                        gap={3}
                        alignItems="center"
                      >
                        <Icon icon="zap" color="green" />
                        <Box>
                          <Text variant="pLargeBold" renderAs="div">
                            {(rentalOption?.variant?.name || rentalOption?.variant?.productName) ??
                              '--'}
                          </Text>
                          <Text renderAs="div">
                            {formatPrice(
                              rentalOption?.variant?.rentalOptions?.length
                                ? (rentalOption.variant.rentalOptions[0]?.price as number) ?? 0
                                : 0,
                            )}
                          </Text>
                        </Box>
                      </Box>
                    );
                  })}
                  {rentalArr.find((item) => item?.variant?.name.toLowerCase().includes('ajax')) && (
                    <Box background="white" display="flex" gap={3} alignItems="center">
                      <MainButton
                        text="Bæta við vöru"
                        dottedShadow="none"
                        colorScheme="white"
                        renderAs="a"
                        href={`https://www.nova.is/sjalfsvorn/komdu/1?${redirectQueryParam}`}
                      />
                    </Box>
                  )}
                </Box>
              </Box>
            )}
          </>
        );
      })}
    </>
  );
};

export default inject('authentication')(EquipmentRentals);
