import React, { useState } from 'react';
import { Box, Datepicker, Icon, Input, MainButton, Select, Text } from '@nova-hf/ui';
import { 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 { useCancelSubscriptionMutation, useSubscriptionsQuery } from 'typings/graphql';
import { useTranslation } from 'utils/i18n';

const COLOR = 'pink';

type UppsognProps = {
  hradleid: Hradleid;
  authentication: Authentication;
  ui: UI;
};

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

const Uppsogn = ({ hradleid, authentication, ui }: UppsognProps) => {
  const { t } = useTranslation(['multi', 'cancel']);
  const { enqueueSnackbar } = useSnackbar();
  const [checkedSubIds, setCheckedSubIds] = useState<string[]>();
  const [cancelAt, setCancelAt] = useState(new Date());
  const [description, setDescription] = useState('');
  const [reason, setReason] = useState('');
  const router = useRouter();
  const ssn = router?.query?.ssn;
  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 mobileReasons = [
    {
      id: 'ServiceArea',
      text: t('cancel:steps.reason.mobileReasons.serviceArea'),
      showOption: true,
    },
    {
      id: 'WontGiveReason',
      text: t('cancel:steps.reason.mobileReasons.wontGiveReason'),
      showOption: true,
    },
    {
      id: 'PhoneDontWork',
      text: t('cancel:steps.reason.mobileReasons.phoneDontWork'),
      showOption: true,
    },
    {
      id: 'WorkPays',
      text: t('cancel:steps.reason.mobileReasons.workPays'),
      showOption: true,
    },
    {
      id: 'EverythingInSamePlace',
      text: t('cancel:steps.reason.mobileReasons.everythingInSamePlace'),
      showOption: true,
    },
    {
      id: 'ToExpensive',
      text: t('cancel:steps.reason.mobileReasons.toExpensive'),
      showOption: true,
    },
    {
      id: 'LoadingCard',
      text: t('cancel:steps.reason.mobileReasons.loadingCard'),
      showOption: true,
    },
    {
      id: 'BadService',
      text: t('cancel:steps.reason.mobileReasons.badService'),
      showOption: true,
    },
    {
      id: 'AnotherOffer',
      text: t('cancel:steps.reason.mobileReasons.anotherOffer'),
      showOption: true,
    },
    {
      id: 'GoingAbroad',
      text: t('cancel:steps.reason.mobileReasons.goingAbroad'),
      showOption: true,
    },
    {
      id: 'CancelNova',
      text: t('cancel:steps.reason.mobileReasons.cancelNova'),
      showOption: true,
    },
    {
      id: 'AnotherNovaNumber',
      text: t('cancel:steps.reason.mobileReasons.anotherNovaNumber'),
      showOption: true,
    },
    {
      id: 'StoppedUsingNumber',
      text: t('cancel:steps.reason.mobileReasons.stoppedUsingNumber'),
      showOption: true,
    },
    {
      id: 'Other',
      text: t('cancel:steps.reason.mobileReasons.other'),
      showOption: true,
    },
  ];

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

      return {
        name: truncatedName as string,
        info: subId,
        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 cancelInput = (subscription: mappedSubscription) => {
    const isChecked = checkedSubIds?.some((checkedSub) => checkedSub === subscription?.id);
    if (isChecked) {
      return {
        subscriptionId: subscription?.id,
        cancelAt: cancelAt,
        description: description,
        reason: reason,
      };
    }
    return null;
  };

  const [cancelSubscription, { loading }] = useCancelSubscriptionMutation({
    onCompleted: (data) => {
      enqueueSnackbar('Uppsögn tókst', {
        variant: 'success',
      });

      if (data) {
        router.push(`/${router.query.ssn}/fjoldaskraning`);
        hradleid?.incrementTrigger();
        ui.setHasMultiMenu(false);
      }
    },
    onError(error) {
      enqueueSnackbar('Uppsögn tókst ekki' + error.message, {
        variant: 'error',
      });
    },
  });

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

      if (reason && useInput) {
        await cancelSubscription({
          variables: {
            input: {
              subscriptionId: useInput.subscriptionId,
              cancelAt: cancelAt,
              description: description,
              reason: reason,
            },
          },
        });
      }
    }
  };

  return (
    <MultiStepWrapper
      hradleid={hradleid}
      color={COLOR}
      getMappedSubs={mappedSubs}
      disabledSubIds={filteredSubIds ?? []}
      sendCheckedToChild={getCheckedSubs}
      title="Uppsögn"
      firstRowTitle={t('multi:headers.user')}
      secondRowTitle={t('multi:multi.phoneNumber')}
      icon="power"
      customerName={customerName ?? ''}
    >
      <Box display="flex" flexDirection="column" gap={3}>
        <Text color="black100" variant="h4">
          Uppsögn
        </Text>
        <Text color="black100">
          Vinsamlegast segðu okkur frá hér fyrir neðan hver ástæða uppsagna er og gefðu okkur nánari
          lýsingu og dagsetningu sem uppsagnir á að fara fram.{' '}
        </Text>

        <Box marginTop={5} display="flex" flexDirection="column" gap={4}>
          <Datepicker
            onSelect={(value: Date) => setCancelAt(value)}
            selected={cancelAt}
            minDate={new Date()}
            color="black100"
            inputId={'date'}
            inputName={t('steps.date.title')}
            isRequired
          />
          <Select
            id="reason"
            label="Ástæða"
            isBold={!!reason}
            onChange={(e) => {
              const selectedReason = e.target.value;
              setReason(selectedReason);
            }}
            required
          >
            <option value="" hidden>
              {'Veldu ástæðu'}
            </option>
            {mobileReasons?.map((reason, index) => {
              return (
                <option key={index} value={reason?.id}>
                  {reason?.text}
                </option>
              );
            })}
          </Select>
          <Input
            id="descriptionInput"
            name="descriptionInput"
            label="Nánari lýsing"
            color="grey900"
            defaultValue={description}
            onChange={(e) => setDescription(e.target.value)}
          />
        </Box>
        <Box
          display="flex"
          flexDirection="row-reverse"
          alignItems="center"
          justifyContent="space-between"
          marginTop={10}
        >
          <Box width="4/12">
            <MainButton
              text="Staðfesta"
              onClick={() => (mappedSubs ? handleButtonClick(mappedSubs) : undefined)}
              dottedShadow="none"
              color="pink"
              isLoading={loading}
              isDisabled={!reason || !cancelAt}
            />
          </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>
  );
};

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

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