'use client';

import { Suspense, useEffect, useMemo } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import Image from 'next/image';
import { CheckCircle2, ArrowRight, ArrowRightLeft } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useSubscription } from '@/hooks/useSubscription';
import { cn, formatDate } from '@/utils';
import { ROUTES } from '@/constants';
import { PageLoader } from '@/components/shared/Loader';
import {
  clearMobileCheckoutReturn,
  isSessionFlow,
  shouldReturnToMobileAccount,
} from '@/utils/sessionFlow';

function SuccessContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { fetchSub, subscription, hasScheduledPlanChange } = useSubscription();

  const returnToMobile = useMemo(
    () => searchParams.get('returnTo') === 'mobile' || shouldReturnToMobileAccount(),
    [searchParams],
  );

  const redirectTarget = returnToMobile ? ROUTES.MOBILE_ACCOUNT : ROUTES.DASHBOARD;

  useEffect(() => {
    fetchSub();
    clearMobileCheckoutReturn();

    const timer = setTimeout(() => {
      router.replace(redirectTarget);
    }, returnToMobile ? 2500 : 6000);

    return () => clearTimeout(timer);
  }, [fetchSub, router, redirectTarget, returnToMobile]);

  const isPlanSwitch = hasScheduledPlanChange;

  return (
    <div
      className={cn(
        'relative flex items-center justify-center px-4',
        isSessionFlow() ? 'min-h-[100dvh]' : 'min-h-[calc(100vh-4rem)]',
      )}
    >
      <div className="pointer-events-none absolute inset-0 -z-10">
        <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[500px] h-[500px] rounded-full bg-emerald-500/[0.04] blur-[100px]" />
        <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[300px] h-[300px] rounded-full bg-brand-500/[0.04] blur-[80px]" />
      </div>

      <div className="max-w-md w-full text-center space-y-8 animate-fade-in">
        <div className="relative mx-auto w-fit">
          <div className="flex h-24 w-24 items-center justify-center rounded-full bg-emerald-500/10 border border-emerald-500/20 mx-auto">
            <CheckCircle2 className="h-12 w-12 text-emerald-500" />
          </div>
          <div className="absolute -top-1 -right-1 flex h-8 w-8 items-center justify-center rounded-full bg-brand-500 border-2 border-background">
            {isPlanSwitch ? (
              <ArrowRightLeft className="h-4 w-4 text-white" />
            ) : (
              <Image src="/logo.png" alt="Activate Abundanate" width={16} height={16} className="object-contain" />
            )}
          </div>
        </div>

        <div className="space-y-3">
          <h1 className="text-4xl font-bold">
            {isPlanSwitch ? 'Plan change scheduled!' : "You're all set!"}
          </h1>
          <p className="text-lg text-muted-foreground">
            {isPlanSwitch ? (
              <>
                Your new <strong>{subscription?.next_plan_name}</strong> plan will start on{' '}
                <strong>{formatDate(subscription?.next_plan_start_date!)}</strong>, after your
                current plan ends.
              </>
            ) : (
              'Your subscription is now active. Welcome to Activate Abundanate Premium!'
            )}
          </p>
        </div>

        {isPlanSwitch ? (
          <div className="rounded-2xl border border-blue-500/20 bg-blue-50 dark:bg-blue-500/5 p-6 text-left space-y-3">
            {[
              `Current plan: ${subscription?.plan_name || 'Active plan'} (continues until end of period)`,
              `Next plan: ${subscription?.next_plan_name} (starts ${formatDate(subscription?.next_plan_start_date!)})`,
              'No interruption to your current access',
              'You can view plan details on your Account page',
            ].map((info) => (
              <div key={info} className="flex items-center gap-3 text-sm">
                <CheckCircle2 className="h-4 w-4 text-blue-500 shrink-0" />
                <span>{info}</span>
              </div>
            ))}
          </div>
        ) : (
          <div className="rounded-2xl border border-emerald-500/20 bg-emerald-50 dark:bg-emerald-500/5 p-6 text-left space-y-3">
            {[
              'Full unlimited access to all features',
              'Create and edit unlimited records',
              'Priority customer support',
              'Available across all your devices',
            ].map((perk) => (
              <div key={perk} className="flex items-center gap-3 text-sm">
                <CheckCircle2 className="h-4 w-4 text-emerald-500 shrink-0" />
                <span>{perk}</span>
              </div>
            ))}
          </div>
        )}

        <div className="flex flex-col gap-3">
          <Button variant="gold" size="lg" asChild>
            <Link href={redirectTarget}>
              {returnToMobile ? 'Back to Account' : 'Go to Dashboard'}
              <ArrowRight className="h-5 w-5" />
            </Link>
          </Button>
          <p className="text-xs text-muted-foreground">
            Redirecting automatically in a few seconds…
          </p>
        </div>
      </div>
    </div>
  );
}

export default function SuccessPage() {
  return (
    <Suspense fallback={<PageLoader text="Confirming your subscription…" />}>
      <SuccessContent />
    </Suspense>
  );
}
