import { useNavigate } from 'react-router';
import { useQuery } from '@apollo/client';

import { useModal } from 'components/layers';

import { Box, Button, Text, Heading } from 'components/common';
import { ExternalLink } from 'components/router/ExternalLink';
import {
  PackageInformation,
  PackageInformationProps,
} from './PackageInformation';
import { CancelChangeModal } from './CancelSubscriptionModal';
import { CURRENT_PACKAGE } from './schema/queries';
import { CurrentPackageQuery } from 'types/graphql';

import { PATHS as HOMEPAGE } from 'pages/root/HomePage';
import { PATHS as SETTINGS } from 'pages/settings';

export const CheckoutSuccess = () => {
  const { data } = useQuery<CurrentPackageQuery>(CURRENT_PACKAGE);
  const navigate = useNavigate();

  const cancelChangeModal = useModal(CancelChangeModal);

  const renderLastSubscription = (
    currentPackages: PackageInformationProps['data'][]
  ) => {
    const length = currentPackages.length;
    const pkg = currentPackages[length - 1];
    const isNext = length > 1;
    return (
      <Box width="100%" paddingX={4} spacingY={4}>
        <Text size="s" align="center">
          {isNext
            ? 'Your next subscription starts automatically when your current active plan ends.'
            : 'Your upgrade was successful'}
        </Text>
        <PackageInformation
          data={pkg}
          scheduled={isNext}
          hasScheduledChange={isNext}
          onCancel={() => cancelChangeModal.show({ name: pkg.name })}
        />
      </Box>
    );
  };

  return (
    <Box
      width={600}
      height="100%"
      display="flex"
      column
      align="center"
      justify="center"
      spacingY={4}
    >
      <Heading size="l" align="center">
        Congratulations!
      </Heading>

      {data?.currentPackage
        ? renderLastSubscription(data.currentPackage)
        : null}

      <ExternalLink className="link fz14" href="https://fansifter.com/pricing">
        Learn more about plans on the pricing page
      </ExternalLink>
      <Button
        onClick={() => navigate(`/${HOMEPAGE.settings}/${SETTINGS.billing}`)}
        size="l"
      >
        Billing settings
      </Button>
    </Box>
  );
};
