import * as React from 'react';
import { useLazyQuery } from '@apollo/client';
import { AttentionBox, Box, Button, Col, DataHeading, Row, Text } from '@nova-hf/ui';
import { ThemeColorType } from '@nova-hf/ui/umd/ts/src/styles/vars.css';
import { parseMainColor } from 'beta/utils/typeGuards';
import EditMenu from 'components/edit-menu/EditMenu';
import PaymentStatusBar from 'components/payment-status-bar/PaymentStatusBar';
import { ProfileDetails } from 'components/profile-detail/ProfileDetails';
import Detail from 'containers/detail/Detail';
import ProfileItem from 'containers/profileItem/ProfileItem';
import Signup from 'containers/signup/Signup';
import { REFILL_CATEGORIES } from 'graphql/queries/refills';
import { inject, observer } from 'mobx-react';
import { useRouter } from 'next/router';
import { useSnackbar } from 'notistack';
import Authentication from 'store/authentication';
import Change from 'store/change';
import AutoRefill from 'store/models/AutoRefill';
import Profile from 'store/models/Profile';
import UsagePack from 'store/models/UsageInfo';
import UI from 'store/ui';
import { IAutoRefill, IConnection, IRefillCategory } from 'typings';
import {
  ServiceStatus,
  UsageType,
  useFiberInfoQuery,
  useHasUnpaidClaimQuery,
  useMobileServiceOrderQuery,
  useMobileServicesQuery,
  useUsageItemsQuery,
} from 'typings/graphql';
import { getIcon } from 'utils/getIcon';
import { formatDate, formatPrice, profileColor, scrollToElement } from 'utils/helpers';
import { useTranslation } from 'utils/i18n';
import { replaceQuery } from 'utils/routing';

import TransferNumberStatus from '../../../farsimi/components/TransferNumberStatus';

import { Bundle } from './components/Bundle';
import { FiberStatus } from './components/FiberStatus';
import { MonthlySummary } from './components/MonthlySummary';
import { SubscriptionStatus } from './components/SubscriptionStatus';
import { UsageSummary } from './components/UsageSummary';
interface IProps {
  profile: Profile;
  authentication?: Authentication;
  packId: string;
}

interface IProfileProps extends IProps {
  subscriptionId: string;
  color?: ThemeColorType;
  change?: Change;
  ui?: UI;
}

interface IUnregisteredProps {
  color?: string;
  subscriptionId: string;
}

interface IMsisdnPayload {
  msisdn: string;
}

const Unregistered = ({ color, subscriptionId }: IUnregisteredProps) => {
  const { t } = useTranslation('subscription');

  return (
    <Col col={4} marginBottom={0}>
      <Row>
        <Col marginBottom={0}>
          <DataHeading headingIcon={getIcon('ath')}>
            <span>Athugið</span>
          </DataHeading>
        </Col>
        <Col>
          <AttentionBox
            title={t('notification.registerUnregistered.text')}
            subtitle={t('notification.registerUnregistered.description')}
          >
            <Button
              fill
              noShadow
              arrowRight
              background={color}
              to={`/skra?subscriptionId=${subscriptionId}`}
            >
              {t('notification.registerUnregistered.linkText')}
            </Button>
          </AttentionBox>
        </Col>
      </Row>
    </Col>
  );
};

const SubscriptionProfile: React.FunctionComponent<IProfileProps> = (props) => {
  const { profile, packId, authentication, subscriptionId, ui, change } = props;
  const { signup, rateplan, autoRefills } = profile;
  const color = profileColor(rateplan);
  const { t } = useTranslation(['subscription', 'subscriptions']);
  const { enqueueSnackbar } = useSnackbar();
  const router = useRouter();
  const payload: IMsisdnPayload = { msisdn: subscriptionId };
  const ssn = authentication?.accountInput.ssn ?? '';
  const [getAvailableRefills, { error, loading, data }] = useLazyQuery(REFILL_CATEGORIES, {
    variables: { input: payload },
  });
  const { data: fiberInfo } = useFiberInfoQuery({
    skip: profile.type !== 'fiber',
    variables: {
      input: {
        subscriptionId: subscriptionId,
      },
    },
  });

  const { data: claimData } = useHasUnpaidClaimQuery({
    variables: {
      input: {
        subscriptionId: subscriptionId,
      },
    },
  });

  const { data: mobileServiceData } = useMobileServicesQuery({
    variables: {
      input: {
        phoneNumber: subscriptionId ?? '',
      },
    },
    skip: !subscriptionId,
  });

  const serviceId =
    mobileServiceData?.mobileServices?.services?.find(
      (service) => service?.status === ServiceStatus.Pending,
    )?.id ?? undefined;

  const { data: orderData } = useMobileServiceOrderQuery({
    variables: {
      id: serviceId ?? '',
    },
    skip: !serviceId,
  });

  const fetchStatusCodes = ['active', 'b1w', 'b2w', 'porting_out'];

  const { data: usageData } = useUsageItemsQuery({
    variables: { accountInput: { ssn }, subscriptionId },
    skip: !authentication || !fetchStatusCodes.includes(profile.statusCode),
  });

  const hasUnpaidClaim = claimData?.hasUnpaidClaim;

  if (rateplan.isPrepaid && !data && !loading) {
    getAvailableRefills();
  }

  const goTo = (subpage: string) => {
    router.push(
      `/${router.query.ssn}/thjonusta/${subscriptionId}/${subpage}?pack=${router.query.pack}`,
    );
  };

  const onSelect = (packIndex: number) => {
    scrollToElement('#detail', ui?.isMobile);

    replaceQuery({
      router,
      params: { pack: packIndex.toString() },
    });
  };

  const onSelectPack = (pack: UsagePack) => {
    if (pack && profile && !loading) {
      change?.initChangePack(profile, pack, data?.availableRefills as IRefillCategory[]);

      goTo('velja');
    }
  };

  const onSelectAutoRefillPack = (autoRefill: IAutoRefill) => {
    if (error) {
      enqueueSnackbar(t('detail.errorAvailableRefills'), {
        variant: 'error',
      });
      return;
    }

    if (autoRefill && profile && data) {
      change?.initChangeAutoRefillPack(
        profile,
        autoRefill,
        data?.availableRefills as IRefillCategory[],
      );
    }

    goTo('velja');
  };

  const onCancel = ({
    autoRefill,
    pack,
    connection,
  }: {
    autoRefill?: IAutoRefill;
    pack?: UsagePack;
    connection?: IConnection;
  }) => {
    if (profile && pack?.servicepackId !== 'S2113') {
      if (autoRefill) {
        change?.initChangeAutoRefill(profile, autoRefill);
      } else if (pack) {
        change?.initChangePack(profile, pack);
      } else if (connection) {
        change?.initChangeConnection(profile, connection);
      }
      goTo('afskra');
    }
    if (pack?.servicepackId === 'S2113') {
      router.push(`/${router.query.ssn}/thjonusta/${subscriptionId}/stillingar/simkort`);
    }
  };

  const onChange = (autoRefill: AutoRefill, type: string) => {
    if (profile) {
      if (autoRefill) change?.initChangeAutoRefill(profile, autoRefill, type);

      goTo('breyta');
    }
  };

  if (profile.isBundle) {
    return <Bundle profile={profile} packId={packId} onSelect={onSelect} onCancel={onCancel} />;
  }

  // only render signup info when status is 'signup'.
  // this is done to prevent errors, may need some rethinking later.
  const isRegistered = !profile.isRegistered;

  if (profile.type === 'fiber' && profile.statusCode === 'signup') {
    return <Signup color={profileColor(rateplan)} profile={profile} />;
  }

  const statusCode = profile.statusCode;

  const isFlutningur = !!orderData?.mobileServiceOrder?.mobilePortInOrder;

  const usageDataForSubscription = usageData?.me?.subscriptions?.subscriptions?.find(
    (item) => item.subscriptionId === subscriptionId,
  );
  const usageItem = usageDataForSubscription?.usageItems?.find(
    (item) => item.type === UsageType.Data,
  );
  const hasDataUsage = usageItem?.usage?.amount && usageItem?.usage?.amount > 0;
  if (orderData?.mobileServiceOrder && !hasDataUsage) {
    return (
      <Box width="100%">
        <TransferNumberStatus
          color={parseMainColor(color, 'ocean')}
          phoneNumber={subscriptionId}
          isFlutningur={isFlutningur}
        />
      </Box>
    );
  }

  return (
    <>
      {profile.type === 'fiber' && authentication?.isStaff ? (
        <Col col={12}>
          <Box marginBottom={5}>
            {fiberInfo?.subscription?.fiberInfo && (
              <SubscriptionStatus
                subscriptionStatusDetails={
                  fiberInfo.subscription.fiberInfo.subscriptionStatusDetails
                }
                dotColor={
                  fiberInfo.subscription.fiberInfo.subscriptionStatusDetails === 'Í viðskiptum'
                    ? 'success'
                    : 'warning'
                }
              />
            )}
          </Box>
        </Col>
      ) : (
        <Box width="100%" marginBottom={2}>
          <SubscriptionStatus
            subscriptionStatusDetails={
              statusCode === 'b1w'
                ? `${t(
                    `subscriptions:statusCode.${statusCode}.${
                      profile.isPrepaid
                        ? 'prepaid'
                        : hasUnpaidClaim
                        ? 'postpaid'
                        : 'postpaidNoUnpaid'
                    }`,
                  )} (${statusCode})`
                : `${t(`subscriptions:statusCode.${statusCode}`)} (${statusCode})`
            }
            dotColor={statusCode === 'active' ? 'success' : 'warning'}
            rateplan={rateplan}
            isStaff={authentication?.isStaff}
          />
        </Box>
      )}

      {signup && (
        <Col col={12}>
          <Signup color={profileColor(rateplan)} profile={profile} />
        </Col>
      )}

      {profile.type === 'fiber' && authentication?.isStaff && (
        <Col col={12}>
          <DataHeading>Ljósleiðarinn þinn</DataHeading>
          <FiberStatus subscriptionId={subscriptionId} color={color} profile={profile} />
        </Col>
      )}

      {!profile.b1w && authentication?.accountInput?.ssn && subscriptionId && (
        <>
          <Box width={'100%'}>
            <Text variant="h6" marginBottom={4}>
              {profile.rateplan.title}
            </Text>
            <UsageSummary
              authentication={authentication}
              subscriptionId={subscriptionId}
              color={color}
              statusCode={statusCode}
            />
          </Box>
          <>{isRegistered && <Unregistered color={color} subscriptionId={subscriptionId} />}</>
        </>
      )}
      {rateplan.isPrepaid && (
        <>
          <Col>
            <DataHeading headingIcon={getIcon('recurring')}>
              {t('subscription.autoRefill.title')}
            </DataHeading>
          </Col>
          <Col>
            {autoRefills?.length > 0 ? (
              autoRefills?.map((autorefill, index) => (
                <PaymentStatusBar
                  key={index}
                  dueDate={
                    autorefill?.nextRefill ? formatDate(autorefill.nextRefill, 'dd.MM.yyyy') : ''
                  }
                  amount={formatPrice(autorefill.info?.price, { monthly: true })}
                  dateText={`${autorefill.info?.shortTitle} ${t(
                    'subscription.autoRefill.nextRefill',
                  )}: `}
                  amountText={t('paymentStatusBar.amount')}
                  status="Recurring"
                  menu={
                    <EditMenu
                      title={t('subscription.autoRefill.menuTitle')}
                      color={color}
                      iconColor="grey400"
                      menuList={[
                        {
                          title: t('subscription.autoRefill.changePack'),
                          onClick: () => onSelectAutoRefillPack(autorefill),
                        },
                        {
                          title: t('subscription.autoRefill.changeDate'),
                          onClick: () => onChange(autorefill, 'date'),
                        },
                        {
                          title: t('subscription.autoRefill.topupNow'),
                          onClick: () => onSelectAutoRefillPack(autorefill),
                        },
                        {
                          title: t('subscription.autoRefill.updatePaymentMethod'),
                          onClick: () => onChange(autorefill, 'payment'),
                        },
                        {
                          title: t('subscription.autoRefill.cancel'),
                          onClick: () => onCancel({ autoRefill: autorefill }),
                        },
                      ]}
                    />
                  }
                />
              ))
            ) : (
              <Text>{t('subscription.autoRefill.emptyMessage')}</Text>
            )}
          </Col>
        </>
      )}
      <Col>
        <DataHeading headingIcon={getIcon(profile.rateplan.typeId)}>Allir pakkar</DataHeading>
      </Col>
      <ProfileDetails
        detail={
          packId && (
            <Detail
              profile={profile}
              packId={packId}
              onSelect={onSelectPack}
              onCancel={onCancel}
              onChange={onChange}
            />
          )
        }
      >
        <ProfileItem profile={profile} onSelect={onSelect} selectedPack={packId} />
      </ProfileDetails>
      <MonthlySummary
        authentication={authentication}
        subscriptionId={subscriptionId}
        color={color}
      />
    </>
  );
};

export default inject('change', 'ui', 'authentication')(observer(SubscriptionProfile));
