import React from 'react';
import { Box, Icon, IconButton, Menu, Pill, Text, ThemeColorType } from '@nova-hf/ui';
import { ProfileBoxItemLoading } from 'components/profile-list/ProfileBoxItemLoading';
import { ProfileListItemLoading } from 'components/profile-list/ProfileListItemLoading';
import { inject } from 'mobx-react';
import { useRouter } from 'next/router';
import Authentication from 'store/authentication';
import {
  Contract,
  ContractItemType,
  ContractStatus,
  DeviceContractItem,
  EquipmentRentalStatus,
  ServiceContractItem,
  useContractQuery,
  useCurrentPeriodTotalChargeQuery,
  useCustomerIdByNationalIdQuery,
} from 'typings/graphql';
import { formatDate, formatPrice } from 'utils/helpers';
import { useTranslation } from 'utils/i18n';

type ContractProfileListItemProps = {
  color: ThemeColorType;
  contractId: string;
  isListView: boolean;
  authentication: Authentication;
  terminated?: Date | null;
};

export const ContractProfileListItem = ({
  color,
  contractId,
  isListView,
  authentication,
  terminated,
}: ContractProfileListItemProps) => {
  const router = useRouter();

  const { data: customerData } = useCustomerIdByNationalIdQuery({
    variables: {
      input: {
        nationalId: router?.query?.ssn?.toString() ?? '',
      },
    },
    skip: !router?.query?.ssn,
  });

  const customerId = customerData?.customerByNationalId?.id;

  const { t } = useTranslation('subscriptions');
  const isStaff = authentication?.isStaff;

  const { data: contractData, loading: loadingContract } = useContractQuery({
    variables: {
      input: {
        id: contractId,
        show_inactive_contract_items: true,
      },
    },
  });

  const contract = contractData?.contract as Contract;
  const isCustomerPayer = contract?.payerId == customerId;

  const { data: periodData } = useCurrentPeriodTotalChargeQuery({
    variables: {
      input: {
        id: contractData?.contract?.id,
      },
    },
    skip: !contractData || !isCustomerPayer,
  });

  if (loadingContract) {
    return (
      <>
        {isListView ? (
          <ProfileListItemLoading color={color} />
        ) : (
          <ProfileBoxItemLoading inGrid color={color} />
        )}
      </>
    );
  }

  if (!contractData || !contractData.contract) {
    return null;
  }

  // should filter from backend;
  const isContractAlltSaman = contract.variant?.id?.includes('allt-saman-');

  const serviceContractItem = contractData?.contract?.contractItems?.find(
    (item) => item.type === ContractItemType.Service,
  ) as ServiceContractItem | undefined;

  // the contract knows this...
  const isInAlltSaman = serviceContractItem?.variantId?.includes('thjonusta-as');

  // check this for allt saman
  const monthlyCharge = periodData?.currentPeriod?.totalCharge;

  const hasRestriction = contract?.hasActiveDefault;

  const deviceContractItems = contract.contractItems.filter(
    (contractItem) => contractItem.type === ContractItemType.Device,
  );

  const hasActiveDevice = (deviceContractItems as DeviceContractItem[])?.find(
    (contractItem) => contractItem.status === 'Active',
  );

  const hasActiveOrPendingRouter = (deviceContractItems as DeviceContractItem[])?.find(
    (contractItem) =>
      contractItem.variant?.id?.includes('router') &&
      (contractItem.status === 'Active' || contractItem.status === 'Pending'),
  );

  const deviceHeaderForStaff =
    isStaff && !serviceContractItem && hasActiveDevice?.rentalInfo?.trackingCode
      ? hasActiveDevice.rentalInfo?.trackingCode
      : hasActiveOrPendingRouter
      ? t('router')
      : t('extender');

  const getFirstName = (fullName: string) => {
    const words = fullName.split(' ');
    return words[0];
  };

  const isContractCancelled = contract.status === ContractStatus.Cancelled;
  const isContractEmpty =
    contract.contractItems.filter((i) => i.status !== 'Inactive').length === 0;

  const hasNothing = contract.contractItems.length === 0;

  const hasOnlyDevices =
    !hasNothing &&
    contract.contractItems
      .filter((c) => c.status !== 'Inactive')
      .every((c) => c.type === ContractItemType.Device) &&
    contract.contractItems.filter((c) => c.status !== 'Inactive');

  const hasNoServiceButIsNotDevice =
    !serviceContractItem && contract.status === ContractStatus.Cancelled;

  const isCustomerUser = serviceContractItem?.serviceInfo.userId == customerId;

  const sendToContractPage =
    (isContractCancelled && isCustomerPayer) ||
    (isCustomerPayer && !isCustomerUser && !isStaff) ||
    hasOnlyDevices;

  if (isContractAlltSaman && isContractEmpty) {
    return null;
  }

  if (hasNothing && !isStaff) {
    return null;
  }

  return (
    <>
      {isListView ? (
        <Box
          width="100%"
          paddingX={3}
          paddingY={4}
          display="flex"
          borderBottomStyle="solid"
          borderColor="grey100"
          borderWidth="1px"
          alignItems="center"
          cursor={{ hover: 'pointer' }}
          background={{ hover: 'grey100' }}
          renderAs="a"
          href={
            sendToContractPage
              ? `/beta/${customerId}/askriftir/${contract?.id}`
              : `/beta/${customerId}/thjonustur/${serviceContractItem?.serviceId}`
          }
        >
          <Box width="5/12">
            <Box marginBottom={1}>
              <Text variant="pLargeBold" color={color}>
                {hasNoServiceButIsNotDevice || serviceContractItem
                  ? serviceContractItem?.serviceInfo.userName
                  : contract.payerName}
              </Text>
            </Box>
            <Box display="flex" flexDirection="row" alignItems="center">
              <Text color="grey500" variant="pSmallRegular">
                {t('contract.payedBy')}
              </Text>
              <Box style={{ marginLeft: '4px' }}>
                <Text variant="pSmallRegular">{contract?.payerName}</Text>
              </Box>
            </Box>
          </Box>
          <Box marginLeft={-2} width="4/12">
            <Box marginBottom={1}>
              <Text variant="pLargeBold" color={color}>
                {contract?.variant?.name} {hasRestriction && <Pill color="warning" text="Lokað" />}
              </Text>
            </Box>
            <Text variant="pSmallRegular" renderAs="div">
              {serviceContractItem
                ? serviceContractItem.serviceInfo?.nickname
                : contract?.status === ContractStatus.Cancelled
                ? t('cancelled')
                : deviceHeaderForStaff}
            </Text>
            {serviceContractItem && contract?.status === ContractStatus.Pending && (
              <Text variant="pSmallRegular" marginTop={1}>
                {t('newPending')}
              </Text>
            )}
          </Box>
          <Box gap={3} display="flex" justifyContent="flex-end" width="3/12">
            <Text variant="pLargeBold" textAlign="right">
              {serviceContractItem
                ? formatPrice(monthlyCharge ?? 0)
                : formatPrice(hasActiveDevice?.variant?.monthlyCharge ?? 0)}
            </Text>
            <Box marginRight={-5}>
              <Menu
                color={color}
                label="Menu"
                items={
                  sendToContractPage
                    ? [
                        {
                          text: t('contract.usage'),
                          href: `/beta/${customerId}/thjonustur/${serviceContractItem?.serviceId}`,
                        },
                        {
                          text: t('contract.breakdown'),
                          href: `/beta/${customerId}/thjonustur/${serviceContractItem?.serviceId}/sundurlidun`,
                        },
                        {
                          text: t('contract.settings'),
                          href: `/beta/${customerId}/thjonustur/${serviceContractItem?.serviceId}/stillingar`,
                        },
                      ]
                    : []
                }
                disclosure={
                  serviceContractItem ? (
                    <IconButton
                      color="black100"
                      icon="dotsVertical"
                      hiddenButtonText="More button"
                      onClick={(event) => {
                        event.stopPropagation();
                      }}
                    />
                  ) : (
                    <Box marginLeft={5}></Box>
                  )
                }
              />
            </Box>
          </Box>
        </Box>
      ) : (
        <Box width={{ sm: '100%', md: '6/12', lg: '4/12' }} paddingX={2} marginBottom={3}>
          <Box
            cursor={{ hover: 'pointer' }}
            renderAs="a"
            href={
              sendToContractPage
                ? `/beta/${customerId}/askriftir/${contract?.id}`
                : `/beta/${customerId}/thjonustur/${serviceContractItem?.serviceId}`
            }
            boxShadow="small"
          >
            <Box
              boxShadow={{
                hover: !hasOnlyDevices
                  ? 'coloredPurple'
                  : !isContractCancelled
                  ? 'coloredGreen'
                  : 'normal',
              }}
              background={isContractCancelled ? 'grey400' : color}
              paddingX={3}
              paddingTop={4}
              paddingBottom={3}
            >
              <Box
                display="flex"
                flexDirection="row"
                justifyContent="space-between"
                marginBottom={1}
              >
                <Text variant="h6" color="white">
                  {getFirstName(
                    serviceContractItem?.serviceInfo.userName ??
                      serviceContractItem?.serviceInfo.type ??
                      '',
                  )}
                </Text>
                <Box marginRight={-2}>
                  <Menu
                    color={color}
                    label="Menu"
                    items={
                      sendToContractPage
                        ? [
                            {
                              text: t('contract.usage'),
                              href: `/beta/${customerId}/thjonustur/${serviceContractItem?.serviceId}`,
                            },
                            {
                              text: t('contract.breakdown'),
                              href: `/beta/${customerId}/thjonustur/${serviceContractItem?.serviceId}/sundurlidun`,
                            },
                            {
                              text: t('contract.settings'),
                              href: `/beta/${customerId}/thjonustur/${serviceContractItem?.serviceId}/stillingar`,
                            },
                          ]
                        : []
                    }
                    disclosure={
                      serviceContractItem ? (
                        <IconButton
                          color="white"
                          icon="dotsVertical"
                          hiddenButtonText="More button"
                          onClick={(event) => {
                            event.stopPropagation();
                          }}
                        />
                      ) : (
                        <></>
                      )
                    }
                  />
                </Box>
              </Box>
              <Box display="flex" justifyContent="space-between">
                <Box display="flex" flexDirection="column" gap={1}>
                  <Text variant="pMediumRegular" color="white">
                    {contract?.variant?.name}
                  </Text>
                  <Text variant="pSmallRegular" color="white">
                    {serviceContractItem?.serviceInfo.nickname}{' '}
                    {hasRestriction && (
                      <Box marginTop={1}>
                        <Pill color="warning" text="Lokað" />
                      </Box>
                    )}
                    {hasOnlyDevices && (
                      <Box marginTop={1}>
                        <Pill color="warning" text="Sagt upp" />
                      </Box>
                    )}
                    {contract?.status === ContractStatus.Pending && (
                      <Box marginTop={1}>
                        <Pill color="success" text="Nýskráning" />
                      </Box>
                    )}
                    {hasNothing && contract?.status === ContractStatus.Active && (
                      <>
                        <Pill color="warning" text="ATH" />
                        <Text>
                          Þessi áskrift er tóm og ætti að hreinsa upp. Ef þið rekist á svona megiði
                          gjarnan senda mál á þróun.
                        </Text>
                      </>
                    )}
                  </Text>
                  {terminated && (
                    <Text color="pink" variant="pSmallBold">{`Varð óvirkt ${formatDate(
                      terminated,
                      'dd.MM.yyyy',
                    )}`}</Text>
                  )}
                </Box>

                {contract?.status !== ContractStatus.Pending && (
                  <Text variant="pSmallRegular" color="white">
                    {formatPrice(isInAlltSaman ? 0 : monthlyCharge ?? 0)}
                  </Text>
                )}
              </Box>
            </Box>
            {!isContractCancelled ? (
              <Box>
                {contract?.contractItems
                  ?.filter(
                    (item) =>
                      item.status === EquipmentRentalStatus.Active && !item.variant?.isHidden,
                  )
                  ?.map((item: DeviceContractItem, index) => {
                    return (
                      <Box
                        dottedShadow="small"
                        key={item.id}
                        background="white"
                        alignItems="center"
                      >
                        <Box
                          borderWidth={{ sm: '1px', hover: '4px' }}
                          borderLeftStyle={{ sm: 'solid', hover: 'solid' }}
                          borderRightStyle={{ sm: 'solid', hover: 'none' }}
                          borderBottomStyle={{ sm: 'solid', hover: 'none' }}
                          borderTopStyle={{ sm: 'solid', hover: 'none' }}
                          borderColor={{ sm: 'grey200', hover: color }}
                          padding={4}
                        >
                          <Box
                            display="flex"
                            flexDirection="row"
                            alignItems={hasRestriction ? 'flex-start' : 'center'}
                            justifyContent="space-between"
                            marginRight={2}
                          >
                            <Box display="flex" flexDirection="column" gap={1}>
                              <Text variant="pLargeBold" color={color} renderAs="div">
                                {item?.variant?.name}
                              </Text>
                            </Box>
                            <Icon icon="arrowRight" color={color} />
                          </Box>
                          {isStaff && item?.rentalInfo?.trackingCode && (
                            <Text color="black100" variant={'pSmallRegular'}>
                              {item?.rentalInfo?.trackingCode}
                            </Text>
                          )}
                          {hasOnlyDevices && <Pill color="yellow" text="Ekki skilað" />}
                          <Box
                            display="flex"
                            justifyContent="flex-end"
                            flexDirection="row"
                            marginRight={3}
                            marginTop={1}
                          >
                            <Text
                              variant="pSmallRegular"
                              color="grey600"
                              renderAs="div"
                            >{`${formatPrice(
                              isInAlltSaman ? 0 : item?.variant?.monthlyCharge ?? 0,
                            )} / mán`}</Text>
                          </Box>
                        </Box>
                      </Box>
                    );
                  })}
              </Box>
            ) : (
              <Box background="white" alignItems="center">
                <Box
                  borderWidth={{ sm: '1px', hover: '4px' }}
                  borderLeftStyle={{ sm: 'solid', hover: 'solid' }}
                  borderRightStyle={{ sm: 'solid', hover: 'none' }}
                  borderBottomStyle={{ sm: 'solid', hover: 'none' }}
                  borderTopStyle={{ sm: 'solid', hover: 'none' }}
                  borderColor={{ sm: 'grey200', hover: 'grey200' }}
                  padding={4}
                >
                  <Box
                    display="flex"
                    flexDirection="row"
                    alignItems="center"
                    justifyContent="space-between"
                    marginRight={2}
                  >
                    <Text
                      variant="pLargeBold"
                      color={isContractCancelled ? 'grey400' : color}
                      renderAs="div"
                    >
                      Áskrift sagt upp
                    </Text>
                    <Icon icon="arrowRight" color={isContractCancelled ? 'grey400' : color} />
                  </Box>
                </Box>
              </Box>
            )}
          </Box>
        </Box>
      )}
    </>
  );
};

ContractProfileListItem.getInitialProps = () => {
  return {
    namespacesRequired: ['subscriptions'],
  };
};

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