import styled from '@emotion/styled';
import { useQuery } from '@tanstack/react-query';
import { useRouter } from 'next/router';
import Script from 'next/script';
import { useEffect, useState } from 'react';

const Wrapper = styled.div`
  padding: 20px;
  max-width: 800px;
  margin: 20px auto;
  box-shadow: 2px 4px 10px 0 rgba(0, 0, 0, 0.1);
`;

declare global {
  interface Window {
    // Tolt-generated unique referral IDs can be received from the Tolt script on the landing page or app's frontend
    tolt_referral: string;
  }
}

export async function getServerSideProps() {
  const serverUri = process.env.SERVER_URI || 'http://localhost:3001';
  const appUri = process.env.APP_URI || 'http://localhost:3002';
  const clientsidePaddleToken = process.env.PADDLE_CLIENTSIDE_TOKEN || '';
  const environment = process.env.ENVIRONMENT || 'development';
  return { props: { serverUri, appUri, clientsidePaddleToken, environment } };
}

const Checkout = ({
  serverUri,
  appUri,
  clientsidePaddleToken,
  environment,
}: {
  serverUri: string;
  appUri: string;
  clientsidePaddleToken: string;
  environment: string;
}) => {
  const router = useRouter();
  const { priceId, discountCode, plan } = router.query;
  const [paddleLoaded, setPaddleLoaded] = useState(false);

  const { data: account } = useQuery(['account'], async () => {
    const res = await (await fetch(`${serverUri}/auth/whoami`, { credentials: 'include' })).json();
    return res;
  });

  const openPaddleCheckout = () => {
    (window as any).Paddle.Checkout.open({
      items: [{ priceId, quantity: 1 }],
      customer: {
        email: account.email,
      },
      settings: {
        allowLogout: false,
        displayMode: 'overlay',
        theme: 'light',
        locale: 'en',
        successUrl: `${appUri}/upgrade-return?plan=${plan}`,
      },
      customData: {
        user_id: account.id,
        user_email: account.email,
        tolt_referral: window.tolt_referral,
      },
      discountCode,
    });
  };

  useEffect(() => {
    if (!!account?.email && !account.plan && paddleLoaded) {
      openPaddleCheckout();
    }
  }, [account, paddleLoaded]);

  if (!account) return null;

  return (
    <>
      <Script
        src="https://cdn.paddle.com/paddle/v2/paddle.js"
        onLoad={() => {
          (window as any).Paddle.Environment.set(environment === 'production' ? 'production' : 'sandbox');
          (window as any).Paddle.Initialize({
            token: clientsidePaddleToken,
            eventCallback: (data) => {
              if (data.name === 'checkout.closed') window.close();
            },
          });
          setPaddleLoaded(true);
        }}
      />
      <script async src="https://cdn.tolt.io/tolt.js" data-tolt="11a42c01-b5f6-4961-858b-8a37dac631f2"></script>
      {!!account.plan && (
        <Wrapper>
          <div>
            <h1>Hi there, {account.username}!</h1>
            <p>
              You are already on the <strong>{account.plan}</strong> plan.
            </p>
            <p>
              If you would like to update your subscription status, please{' '}
              <a href={`${appUri}/subscription`}>click here</a> to go to the subscription management panel.
            </p>
            <p>
              Or, you can <a href={`${appUri}`}>click here</a> to return to WavTool.
            </p>
          </div>
        </Wrapper>
      )}
    </>
  );
};

export default Checkout;
