import React, { useEffect, useState } from 'react';
import { Box, Checkbox, Icon, MainButton, NumberInput, Text } from '@nova-hf/ui';
import { formatPrice, getMaxLengthOfName } from 'beta/utils/helpers';
import MultiStepWrapper from 'containers/multiStepWrapper/MultiStepWrapper';
import { inject, observer } from 'mobx-react';
import { useRouter } from 'next/router';
import { useSnackbar } from 'notistack';
import Authentication from 'store/authentication';
import Hradleid from 'store/hradleid';
import UI from 'store/ui';
import { IContext } from 'typings/context';
import { useSplitBillMutation, useSubscriptionsQuery } from 'typings/graphql';
import { useTranslation } from 'utils/i18n';

const COLOR = 'pink';

type ThakProps = {
  hradleid: Hradleid;
  authentication: Authentication;
  ui: UI;
  ssn: string;
};

type mappedSubscription = {
  name: string;
  info: string;
  id: string;
  payer?: string;
};

const Thak = ({ hradleid, authentication, ui, ssn }: ThakProps) => {
  const { t } = useTranslation(['multi']);
  const { enqueueSnackbar } = useSnackbar();
  const [checkedSubIds, setCheckedSubIds] = useState<string[]>();
  const [ceiling, setCeiling] = useState('');
  const [highError, setHighError] = useState(false);
  const [isChecked, setIsChecked] = useState(true);
  const router = useRouter();
  const { accountInput } = authentication;
  const { data } = useSubscriptionsQuery({
    variables: {
      subscriptionsInput: {
        onlyActive: true,
        forBulkMethods: true,
        perPage: 1000,
      },
      accountInput,
    },
    ssr: false,
  });

  const subscriptions = data?.me?.subscriptions?.subscriptions;
  const customerName = data?.me?.name;

  const mapSubsToUsernamesAndInfo = () => {
    return hradleid?.subscriptionIds?.map((subId) => {
      const subscription = subscriptions?.find((sub) => sub?.subscriptionId === subId);
      const username = subscription?.name;
      const ceiling = subscription?.roofAmount;
      const MAX = getMaxLengthOfName();
      const truncatedName =
        username && username.length > MAX ? `${username.slice(0, MAX)}...` : username;

      return {
        name: truncatedName as string,
        info: formatPrice(ceiling),
        id: subId,
        payer: subscription?.accountSsn,
      };
    });
  };

  const mappedSubs = mapSubsToUsernamesAndInfo();
  const subsWhereCustomerIsNotPayer = mappedSubs?.filter((sub) => sub.payer !== ssn);
  const filteredSubIds = subsWhereCustomerIsNotPayer?.map((sub) => sub.id);
  const getCheckedSubs = (subIds: Array<string>) => {
    setCheckedSubIds(subIds);
  };
  const splitBillInput = (subscription: mappedSubscription) => {
    const isChecked = checkedSubIds?.some((checkedSub) => checkedSub === subscription?.id);
    if (isChecked) {
      return {
        subscriptionId: subscription?.id,
        splitBillLimit: parseInt(ceiling, 10),
        splitBill: isChecked,
      };
    }
    return null;
  };

  const [splitBill, { loading }] = useSplitBillMutation({
    onCompleted: (data) => {
      enqueueSnackbar(t('ceiling.singleSuccess'), {
        variant: 'success',
      });

      if (data) {
        hradleid?.incrementTrigger();
        ui.setHasMultiMenu(false);
      }
    },
    onError(error) {
      enqueueSnackbar(t('ceiling.singleFail') + error.message, {
        variant: 'error',
      });
    },
  });

  const handleButtonClick = async (subscriptions: mappedSubscription[]) => {
    for (const subscription of subscriptions) {
      const useInput = splitBillInput(subscription);

      if (ceiling && useInput) {
        await splitBill({
          variables: {
            input: {
              subscriptionId: useInput.subscriptionId,
              splitBillLimit: useInput.splitBillLimit,
              splitBill: useInput.splitBill,
            },
          },
        });
      }
    }
    await router.push({
      pathname: `/${ssn}/fjoldaskraning`,
      query: { ssn: ssn },
    });
  };

  useEffect(() => {
    if (ceiling) {
      const high = 1000000;
      const numberValue = parseInt(ceiling, 10);
      if (numberValue > high) setHighError(true);
      if (numberValue < high) setHighError(false);
    }
  }, [ceiling]);

  return (
    <MultiStepWrapper
      hradleid={hradleid}
      color={COLOR}
      getMappedSubs={mappedSubs}
      disabledSubIds={filteredSubIds ?? []}
      sendCheckedToChild={getCheckedSubs}
      title={t('ceiling.ceiling')}
      firstRowTitle={t('headers.user')}
      secondRowTitle={t('ceiling.ceiling')}
      icon="wallet"
      customerName={customerName ?? ''}
    >
      <Box display="flex" flexDirection="column" gap={3}>
        <Text color="black100" variant="h4">
          {t('ceiling.choose')}
        </Text>
        <Text color="black100">{t('ceiling.subtitle')}</Text>

        <Box marginTop={15} display="flex" flexDirection="column" gap={4}>
          <NumberInput
            id="CreditCardInput"
            label={t('ceiling.newCeiling')}
            name="New ceiling Input"
            numberType="number"
            value={ceiling}
            required
            disabled={false}
            onChange={(value) => setCeiling(value)}
          />
          <Checkbox
            label={'Hafa þak virkt'}
            isChecked={isChecked}
            type="checked"
            color="pink"
            onChange={() => {
              setIsChecked(!isChecked);
            }}
          />
        </Box>
        {highError && (
          <Box
            gap={1}
            display="flex"
            flexDirection="row"
            alignItems="center"
            marginRight="auto"
            width="4/12"
          >
            {highError && (
              <>
                <Icon icon="info" color="warning" />
                <Text marginRight="auto" color="warning" variant="pSmallRegular">
                  {t('ceiling.valueError')}
                </Text>
              </>
            )}
          </Box>
        )}
        <Box
          display="flex"
          flexDirection="row-reverse"
          alignItems="center"
          justifyContent="space-between"
          marginTop={10}
        >
          <Box width="4/12">
            <MainButton
              text={t('ceiling.confirm')}
              onClick={() => (mappedSubs ? handleButtonClick(mappedSubs) : undefined)}
              dottedShadow="none"
              color="pink"
              isLoading={loading}
              isDisabled={!ceiling || highError}
            />
          </Box>
        </Box>
        {filteredSubIds && filteredSubIds.length > 0 && (
          <Box display="flex" flexDirection="row" alignItems="center" gap={1}>
            <Icon icon="info" color="warning" />
            <Text>{t('multi:multi.payerError')}</Text>
          </Box>
        )}
      </Box>
    </MultiStepWrapper>
  );
};

Thak.getInitialProps = ({ pathname, query }: IContext) => {
  return {
    pathname,
    ssn: query.ssn,
    namespacesRequired: ['multi'],
  };
};

export default inject('hradleid', 'authentication', 'ui')(observer(Thak));
