'use client';

import { useStatsigClient } from '@statsig/react-bindings';
import { useSearchParams } from 'next/navigation';
import { useEffect, useState } from 'react';

import { CLOUDFLARE_TURNSTILE_SITE_KEY_AUTH } from '@/utils/constants';

// Extend window interface for Turnstile
declare global {
  interface Window {
    turnstile?: {
      render: (container: string, options: any) => void;
      remove: (element: Element) => void;
    };
  }
}

export default function VerifyTurnstilePage() {
  const searchParams = useSearchParams();
  const partialToken = searchParams.get('partial_token');
  const completeUrl = searchParams.get('url');
  const [progress, setProgress] = useState(0);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [turnstileLoaded, setTurnstileLoaded] = useState(false);
  const [statsigReady, setStatsigReady] = useState(false);
  const [isTurnstileEnabled, setIsTurnstileEnabled] = useState(false);
  const statsigClient = useStatsigClient();

  const getMessage = () => {
    if (progress < 30) return 'Tuning the instruments';
    return 'Warming up the synthesizers';
  };

  // Progress animation effect
  useEffect(() => {
    const interval = setInterval(() => {
      setProgress((prev) => {
        if (isSubmitting) return 100; // Move to 100% when submitting
        if (prev >= 95) return 95; // Stop at 95% until token is submitted
        return prev + 1;
      });
    }, 50); // Update every 50ms for smooth animation

    return () => clearInterval(interval);
  }, [isSubmitting]);

  // Statsig readiness polling
  useEffect(() => {
    let pollCount = 0;
    const maxPolls = 20; // 20 * 50ms = 1000ms = 1 second
    const pollInterval = 50; // 50ms
    let timeoutId: NodeJS.Timeout | null = null;
    let isCleanedUp = false;

    const pollStatsig = () => {
      if (isCleanedUp) return;

      const currentStatus = statsigClient?.client?.loadingStatus || 'Unknown';

      if (currentStatus === 'Ready') {
        setStatsigReady(true);
        // Evaluate the gate only after Statsig is ready
        const gateValue = statsigClient.checkGate('auth-turnstile-enabled');
        setIsTurnstileEnabled(gateValue);
        return;
      }

      pollCount++;
      if (pollCount < maxPolls) {
        timeoutId = setTimeout(pollStatsig, pollInterval);
      } else {
        // After 1 second, proceed anyway
        setStatsigReady(true);
        // Evaluate the gate even if Statsig isn't ready
        const gateValue = statsigClient.checkGate('auth-turnstile-enabled');
        setIsTurnstileEnabled(gateValue);
      }
    };

    // Start polling immediately
    pollStatsig();

    // Cleanup function
    return () => {
      isCleanedUp = true;
      if (timeoutId) {
        clearTimeout(timeoutId);
      }
    };
  }, [statsigClient]);

  // Handle case when Turnstile is disabled
  useEffect(() => {
    if (!statsigReady || !completeUrl) return;

    if (!isTurnstileEnabled) {
      // If Turnstile is disabled, immediately redirect with "disabled" token
      const redirectUrl = `${completeUrl}&turnstile_token=disabled`;
      window.location.href = redirectUrl;
    }
  }, [isTurnstileEnabled, completeUrl, statsigReady]);

  useEffect(() => {
    // Only load Turnstile if Statsig is ready and the gate is enabled
    if (!statsigReady || !isTurnstileEnabled) return;

    let script: HTMLScriptElement | null = null;

    // Load Turnstile script
    const loadTurnstile = () => {
      if (typeof window === 'undefined') return;

      // Load script if not already loaded
      if (!window.turnstile) {
        script = document.createElement('script');
        script.src =
          'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';
        script.async = true;
        script.onload = () => {
          setTurnstileLoaded(true);
        };
        script.onerror = () => {
          console.error('Failed to load Turnstile');
        };
        document.head.appendChild(script);
      } else {
        setTurnstileLoaded(true);
      }
    };

    loadTurnstile();

    // Cleanup function
    return () => {
      script?.remove();
    };
  }, [partialToken, completeUrl, isTurnstileEnabled, statsigReady]);

  // Render Turnstile when loaded and container is ready
  useEffect(() => {
    if (
      !statsigReady ||
      !isTurnstileEnabled ||
      !turnstileLoaded ||
      !window.turnstile ||
      !completeUrl
    )
      return;

    const container = document.getElementById('turnstile-container');
    if (!container) return;

    // Remove any existing turnstile widget
    const existingWidget = container.querySelector('.cf-turnstile');
    if (existingWidget) {
      existingWidget.remove();
    }

    window.turnstile.render('#turnstile-container', {
      sitekey: CLOUDFLARE_TURNSTILE_SITE_KEY_AUTH,
      callback: (token: string) => {
        // Complete progress and redirect
        setIsSubmitting(true);
        setProgress(100);

        setTimeout(() => {
          const redirectUrl = `${completeUrl}&turnstile_token=${token}`;
          window.location.href = redirectUrl;
        }, 200); // Small delay to show 100% completion
      },
      'error-callback': (error: any) => {
        // TODO: handle this
        console.error('Turnstile verification failed', error);
        const redirectUrl = `${completeUrl}&turnstile_error=${error}`;
        window.location.href = redirectUrl;
      },
      theme: 'light',
      size: 'normal',
    });
  }, [turnstileLoaded, completeUrl, isTurnstileEnabled, statsigReady]);

  return (
    <div className='flex min-h-screen w-full flex-col items-center justify-center'>
      <div className='max-w-md text-center'>
        <h1 className='mb-6 text-3xl font-bold whitespace-nowrap text-foreground-primary transition-all duration-500'>
          {getMessage()}
        </h1>
        <p className='mb-6 text-foreground-secondary'>
          Just a moment while we prepare everything for you...
        </p>

        {/* Pink progress bar */}
        <div className='mb-6 h-2 w-full rounded-full bg-background-secondary'>
          <div
            className='h-2 rounded-full transition-all duration-300 ease-out'
            style={{
              backgroundColor: 'var(--color-accent-pink)',
              width: `${progress}%`,
            }}
          ></div>
        </div>

        {/* Turnstile container - only show if Statsig is ready and Turnstile is enabled */}
        {statsigReady && isTurnstileEnabled && (
          <div
            id='turnstile-container'
            className='mb-6 flex justify-center'
          ></div>
        )}

        {isSubmitting && (
          <p className='text-sm text-foreground-secondary'>
            Completing setup...
          </p>
        )}
      </div>
    </div>
  );
}
