import * as React from 'react';
import { useEffect, useState } from 'react';
import { Button } from '@nova-hf/ui';
import { ConnectionDetails } from 'components/connection/ConnectionDetails';
import { inject, observer } from 'mobx-react';
import { NextRouter, withRouter } from 'next/router';
import Authentication from 'store/authentication';
import Connection from 'store/models/Connection';
import Profile from 'store/models/Profile';
import { formatFirstName, profileColor } from 'utils/helpers';
import { WithTranslation, withTranslation } from 'utils/i18n';

import {
  useCustomerIdByNationalIdQuery,
  useServiceLazyQuery,
  useSubscriptionQuery,
} from '../../typings/graphql';

interface IDetailProps extends WithTranslation {
  authentication: Authentication;
  profile: Profile;
  packId: string;
  onCancel({ profile, connection }: { profile: Profile; connection: Connection }): void;
  router: NextRouter;
}

const Detail = ({ profile, t, packId, router, onCancel, authentication }: IDetailProps) => {
  const [fiberDescription, setFiberDescription] = useState('');
  const { rateplan } = profile;
  const color = profileColor(rateplan);
  const { accountInput } = authentication;
  const connection = profile.connections[parseInt(packId, 10)];
  const [serviceId, setServiceId] = useState(connection?.subscriptionId);
  const [isBeta, setIsBeta] = useState(false);
  const { subscriptionId, type } = connection || { subscriptionId: undefined, type: undefined };
  const isGuid = (input: string): boolean => {
    const guidPattern =
      /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
    if (guidPattern.test(input)) {
      setServiceId(input);
    }
    return guidPattern.test(input);
  };

  const { data, loading, error } = useSubscriptionQuery({
    variables: { subscriptionId, accountInput },
  });

  const connectionProfile = data?.me?.profiles ? data.me.profiles[0] : undefined;

  const isFiber = type === 'Internet';
  const user = connectionProfile ? formatFirstName(connectionProfile?.name) : '';

  const detailTitle = connectionProfile
    ? isFiber
      ? connectionProfile.title
      : user
    : subscriptionId;

  const detailSubtitle = isFiber ? '' : user && subscriptionId;

  const subscriptionTitle = connectionProfile?.rateplan?.shortTitle;

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

  const customerId = contractCustomerData?.customerByNationalId?.id;

  const [getService] = useServiceLazyQuery({
    onCompleted(data) {
      if (data?.service?.name) {
        setFiberDescription(data.service.name);
      } else {
        return;
      }
    },
  });

  useEffect(() => {
    if (isGuid(serviceId)) {
      getService({
        variables: {
          serviceId: serviceId,
        },
      });
    }
  }, [serviceId]);

  useEffect(() => {
    if (connection && isGuid(connection?.subscriptionId)) {
      setServiceId(connection.subscriptionId);
      setIsBeta(true);
    } else {
      setIsBeta(false);
    }
  }, [router.query.pack]);

  if (error) {
    return <div>error</div>;
  }
  if (loading) {
    return <div>...</div>;
  }

  if (!data || !data.me || !authentication || !connection) {
    return null;
  }

  return (
    <>
      {connectionProfile || isBeta ? (
        <ConnectionDetails
          color={color}
          title={fiberDescription ? fiberDescription : detailTitle ? detailTitle : ''}
          subtitle={detailSubtitle}
          headerLink={
            isBeta
              ? undefined
              : `/${router.query.ssn}/thjonusta/${subscriptionId}?parentId=${profile?.subscriptionId}`
          }
          betaLink={isBeta ? `/beta/${customerId}/thjonustur/${serviceId}` : undefined}
          connectionType={connection.type}
          description={t('detail.cancel.connection.description', { subscriptionTitle })}
          buttonText={t('detail.cancel.connection.heading')}
          onClick={() => onCancel({ profile, connection })}
          className="tourConnectionDetail"
        />
      ) : (
        <Button
          background="white"
          text="dark"
          big
          fill
          noShadow
          onClick={() => onCancel({ profile, connection })}
        >
          {t('detail.cancel.connection.heading')}
        </Button>
      )}
    </>
  );
};

export default withTranslation('subscription')(
  withRouter(inject('authentication')(observer(Detail))),
);
