'use client';

import { useEffect, useRef, useState } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import Image from 'next/image';
import { CheckCircle2, XCircle } from 'lucide-react';
import { useAppDispatch } from '@/hooks/useRedux';
import { activateAccount } from '@/store/slices/authSlice';
import { Button } from '@/components/ui/button';
import { Loader } from '@/components/shared/Loader';
import { ROUTES } from '@/constants';

type ActivateState = 'loading' | 'success' | 'error';

export default function ActivatePage() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const dispatch = useAppDispatch();
  const hasActivated = useRef(false);

  const [state, setState] = useState<ActivateState>('loading');
  const [errorMsg, setErrorMsg] = useState('');

  useEffect(() => {
    if (hasActivated.current) return;

    const token = searchParams.get('token');
    if (!token) {
      setState('error');
      setErrorMsg('No activation token found. Please check your email for the correct link.');
      return;
    }

    hasActivated.current = true;

    let redirectTimer: ReturnType<typeof setTimeout>;

    const activate = async () => {
      const result = await dispatch(activateAccount(token));
      if (activateAccount.fulfilled.match(result)) {
        setState('success');
        redirectTimer = setTimeout(() => {
          router.push(ROUTES.PRICING);
        }, 2000);
      } else {
        setState('error');
        setErrorMsg(
          (result.payload as string) ||
            'Activation failed. The link may have expired or already been used.',
        );
      }
    };

    activate();

    return () => clearTimeout(redirectTimer);
  }, [searchParams, dispatch, router]);

  return (
    <div className="relative min-h-[calc(100vh-4rem)] flex items-center justify-center px-4">
      <div className="pointer-events-none absolute inset-0 -z-10">
        <div className="absolute top-1/3 left-1/2 -translate-x-1/2 w-[400px] h-[400px] rounded-full bg-brand-500/[0.04] dark:bg-brand-400/[0.06] blur-[100px]" />
      </div>

      <div className="w-full max-w-md text-center space-y-6 animate-fade-in">
        <div className="inline-flex h-12 w-12 items-center justify-center rounded-2xl overflow-hidden mx-auto">
          <Image src="/logo.png" alt="Activate Abundanate" width={48} height={48} className="object-contain" />
        </div>

        {state === 'loading' && (
          <div className="rounded-2xl border border-border bg-card shadow-card p-10 space-y-6">
            <Loader size="lg" />
            <div className="space-y-2">
              <h1 className="text-2xl font-bold">Activating your account…</h1>
              <p className="text-muted-foreground">Please wait while we verify your token.</p>
            </div>
          </div>
        )}

        {state === 'success' && (
          <div className="rounded-2xl border border-emerald-500/20 bg-emerald-50 dark:bg-emerald-500/5 p-10 space-y-6">
            <CheckCircle2 className="h-14 w-14 text-emerald-500 mx-auto" />
            <div className="space-y-2">
              <h1 className="text-2xl font-bold">Account activated!</h1>
              <p className="text-muted-foreground">
                Welcome to Activate Abundanate! Redirecting you to choose a plan…
              </p>
            </div>
            <div className="h-1 w-full rounded-full bg-muted overflow-hidden">
              <div className="h-full bg-emerald-500 rounded-full animate-[progress_2s_linear_forwards]" />
            </div>
          </div>
        )}

        {state === 'error' && (
          <div className="rounded-2xl border border-destructive/20 bg-destructive/5 p-10 space-y-6">
            <XCircle className="h-14 w-14 text-destructive mx-auto" />
            <div className="space-y-2">
              <h1 className="text-2xl font-bold">Activation failed</h1>
              <p className="text-muted-foreground">{errorMsg}</p>
            </div>
            <div className="flex flex-col gap-3">
              <Button variant="gold" asChild>
                <a href={ROUTES.LOGIN}>Go to Login</a>
              </Button>
              <Button variant="ghost" size="sm" onClick={() => window.location.reload()}>
                Try Again
              </Button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
