import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';

import { LaunchDiscountPlanCard } from '../components/launch-discount/plan-card';
import { LAUNCH_PLANS, LaunchPlan } from '../components/launch-discount/plans';
import { GRADIENT, MONO, SANS } from '../components/signup-mirror/theme';
import { Spinner } from '../components/ui/Spinner';
import { useAppStateContext } from '../context/user.data.context';
import { recomaze_ai_personalization_env } from '../env';
import {
  createSignupCheckout,
  skipLaunchDiscount,
} from '../service/payment/payment.service';
import { getBaseUrl } from '../utils/domain';
import { PlanType } from '../utils/plan';

const PageLoading = (): JSX.Element => (
  <div className="flex min-h-[60vh] items-center justify-center">
    <Spinner className="h-6 w-6 text-gray-400" />
  </div>
);

const LaunchDiscount = (): JSX.Element => {
  const navigate = useNavigate();
  const { token, clientId, user } = useAppStateContext();

  const [lockingKey, setLockingKey] = useState<PlanType | null>(null);
  const [skipping, setSkipping] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!user) return;
    // Only a confirmed non-mirror account is bounced; a stale /me that omits
    // the flag must not eject a merchant who just arrived from the Mirror.
    if (user.signup_mirror === false) {
      navigate('/dashboard', { replace: true });

      return;
    }
    if (user.signup_mirror_completed_at) {
      navigate('/dashboard', { replace: true });
    }
  }, [user, navigate]);

  const adminBase = (): string => {
    const url = getBaseUrl(recomaze_ai_personalization_env?.wp_api_url);

    return `${url}/wp-admin/admin.php?page=recomaze`;
  };

  const lock = async (plan: LaunchPlan): Promise<void> => {
    if (!token || lockingKey || skipping) return;
    setError(null);
    setLockingKey(plan.key);
    try {
      const base = adminBase();
      const response = await createSignupCheckout({
        price_id: plan.priceId,
        success_url: `${base}#/dashboard`,
        cancel_url: `${base}#/launch-discount`,
      });
      if (response?.success && response.session?.url) {
        window.location.replace(response.session.url);

        return;
      }
      throw new Error(response?.message || 'Failed to start checkout');
    } catch (checkoutError) {
      console.error(checkoutError);
      setError('Something went wrong opening checkout. Please try again.');
      setLockingKey(null);
    }
  };

  const skip = async (): Promise<void> => {
    if (!token || lockingKey || skipping) return;
    setSkipping(true);
    try {
      await skipLaunchDiscount();
    } catch (skipError) {
      console.error(skipError);
    } finally {
      navigate('/onboarding-chain');
    }
  };

  if (!token || !clientId) return <PageLoading />;

  return (
    <div
      className={`min-h-screen bg-[#f6f6f7] text-[#202223] ${SANS} text-[14px] leading-[1.55] antialiased flex flex-col justify-center px-6 py-16 selection:bg-[rgba(200,23,93,0.2)]`}
    >
      <div className="w-full max-w-[1200px] mx-auto text-center">
        <div
          className={`${MONO} text-[11px] tracking-[0.16em] uppercase text-[#8c9196]`}
        >
          Launch offer
        </div>
        <h1 className="mt-3 m-0 text-[clamp(30px,4.2vw,46px)] font-semibold tracking-[-0.03em] leading-[1.05]">
          <span className={`${GRADIENT} bg-clip-text text-transparent`}>
            50% off
          </span>{' '}
          your first month
        </h1>
        <p className="mt-3 text-[15px] text-[#6d7175] max-w-[560px] mx-auto">
          Your Company ID is saved. Pick a plan and Recomaze goes to work. Free
          for 7 days, then 50% off your first month.
        </p>
      </div>

      <div className="w-full max-w-[1200px] mx-auto mt-9">
        {error && (
          <div className="mb-4 text-center text-sm text-red-600" role="alert">
            {error}
          </div>
        )}

        <div className="grid grid-cols-1 md:grid-cols-3 gap-5 items-stretch">
          {LAUNCH_PLANS.map(plan => (
            <LaunchDiscountPlanCard
              key={plan.key}
              plan={plan}
              isLocking={lockingKey === plan.key}
              disabled={!!lockingKey || skipping}
              onLock={lock}
            />
          ))}
        </div>

        <div className="mt-6 text-center text-[12.5px] text-[#8c9196] max-w-[640px] mx-auto">
          Full access starts today - you won&apos;t be charged now. Your 7-day
          free trial runs first; cancel anytime before it ends and you pay
          nothing. When the trial ends, we bill your first month at 50% off,
          then the full plan price every month after.
        </div>

        <div className="mt-7 flex flex-col items-center gap-2.5">
          <button
            type="button"
            onClick={skip}
            disabled={!!lockingKey || skipping}
            className={`bg-none border-none p-1.5 text-[#8c9196] ${SANS} text-[13px] cursor-pointer underline underline-offset-[3px] decoration-[#c9cccf] hover:text-[#6d7175] disabled:opacity-50`}
          >
            {skipping ? 'Continuing...' : 'Continue without the welcome offer'}
          </button>
        </div>
      </div>
    </div>
  );
};

export default LaunchDiscount;
