import { useRef, useState } from 'react';
import {
  Routes,
  Route,
  Link,
  NavLink,
  useNavigate,
  useLocation,
} from 'react-router-dom';
import { useQuery } from '@apollo/client';
import { SUBSCRIPTION_PAGE_PROPS } from 'components/billing/schema/queries';
import {
  SubscriptionPagePropsQuery,
  SubscriptionPagePropsQueryVariables,
} from 'types/graphql';

import { Header } from 'components/Header';
import { Spinner } from 'components/common';
import { Redirect } from 'components/router/Redirect';
import { withErrorBoundary } from 'components/ErrorBoundary';

import { SelectPlanScreen } from './SelectPlanScreen';
import { CheckoutScreen } from './CheckoutScreen';
import { RedirectState } from 'components/billing/modals/UpgradeSubscriptionModal';

export const PATHS = {
  checkout: 'checkout',
};

export const SubscriptionPage = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const stateRef = useRef(location.state as RedirectState | null);

  const [selectedPlan, setSelectedPlan] = useState<
    SubscriptionPagePropsQuery['packages'][0] | null
  >(null);
  const [billingCycle, setBillingCycle] = useState('annual');

  const { loading, data } = useQuery<
    SubscriptionPagePropsQuery,
    SubscriptionPagePropsQueryVariables
  >(SUBSCRIPTION_PAGE_PROPS);

  const handleConfirm = (selected: string, billingCycle: string) => {
    const plan = data?.packages.find((plan) => plan.name === selected);

    setSelectedPlan(plan!);
    setBillingCycle(billingCycle);
    navigate(PATHS.checkout);
  };

  return (
    <div className="h100 flex flexColumn">
      <Header
        left={
          stateRef.current?.path && (
            <Link to={stateRef.current?.path} className="header-link">
              {stateRef.current?.name
                ? `Back to ${stateRef.current?.name}`
                : 'Back'}
            </Link>
          )
        }
        title={
          <div className="flex spacing4">
            <NavLink to="." className="header-link" end>
              Select a plan
            </NavLink>
            <NavLink
              to={PATHS.checkout}
              className="header-link c-gray"
              style={{ pointerEvents: 'none' }}
            >
              Finalize and confirm
            </NavLink>
          </div>
        }
      />
      <div className="flexGrow marginXA padding4" style={{ width: 600 }}>
        {data && (
          <Routes>
            <Route
              index
              element={withErrorBoundary(
                <SelectPlanScreen
                  plans={data.packages}
                  currentPlan={data.currentPackage[0]?.name}
                  currentBillingCycle={data.currentPackage[0]?.billingCycle}
                  defaultPlan={selectedPlan?.name}
                  defaultbillingCycle={billingCycle}
                  status={data.currentPackage[0]?.status}
                  onConfirm={handleConfirm}
                />
              )}
              key="SelectPlanScreen"
            />
            <Route
              path={PATHS.checkout}
              element={withErrorBoundary(
                selectedPlan ? (
                  <CheckoutScreen
                    plan={selectedPlan}
                    billingCycle={billingCycle}
                    onCancel={() => navigate('.', { replace: true })}
                  />
                ) : (
                  <Redirect to=".." />
                )
              )}
              key="CheckoutScreen"
            />
          </Routes>
        )}
        <Spinner show={loading} />
      </div>
    </div>
  );
};
