// File Path: monorepo/web/frontend/src/pages/Anonymous/TwoFA/ValidationPage.jsx
import React, { useState, useEffect, useCallback, useRef } from "react";
import { Link, useNavigate } from "react-router";
import {
  useAuthManager,
  useTwoFactorAuthManager,
} from "../../../services/Services";
import { getRoleRedirectPath } from "../../../constants/Roles";
import {
  UIXThemeProvider,
  useUIXTheme,
  useMobileOptimizations,
  OTPInput,
  Button,
} from "../../../components/UIX";
import {
  ShieldCheckIcon,
  ExclamationTriangleIcon,
  ArrowRightIcon,
  ArrowLeftIcon,
  KeyIcon,
  DevicePhoneMobileIcon,
} from "@heroicons/react/24/outline";

function TwoFAValidationPage() {
  return (
    <UIXThemeProvider>
      <TwoFAValidationPageContent />
    </UIXThemeProvider>
  );
}

function TwoFAValidationPageContent() {
  ////
  //// Services.
  ////

  const authManager = useAuthManager();
  const twoFactorAuthManager = useTwoFactorAuthManager();
  const navigate = useNavigate();
  const { getThemeClasses } = useUIXTheme();
  const { isMobile } = useMobileOptimizations();

  ////
  //// Component states.
  ////

  const [errors, setErrors] = useState({});
  const [isLoading, setIsLoading] = useState(false);
  const [token, setToken] = useState("");
  const isMountedRef = useRef(true);

  // Cleanup on unmount - prevents state updates after unmount
  useEffect(() => {
    isMountedRef.current = true;
    return () => {
      isMountedRef.current = false;
    };
  }, []);

  ////
  //// Event handling.
  ////

  const onUnauthorized = useCallback(() => {
    navigate("/login?unauthorized=true");
  }, [navigate]);

  /**
   * Handle form submission
   */
  const handleSubmit = useCallback(async (e) => {
    e.preventDefault();

    // Prevent state updates if component is unmounted
    if (!isMountedRef.current) return;

    // Clear previous errors
    setErrors({});

    // Validate token
    const validationError = twoFactorAuthManager.validateOTPCode(token);
    if (validationError) {
      setErrors(validationError);
      window.scrollTo(0, 0);
      return;
    }

    setIsLoading(true);

    try {
      if (import.meta.env.DEV) {
        console.log("TwoFAValidationPage: Validating OTP token for login");
      }

      // Clean token (remove whitespace)
      const cleanedToken = token.replace(/\s/g, "");

      // Validate OTP for login
      const validateResponse = await twoFactorAuthManager.validateOTP(
        { token: cleanedToken },
        onUnauthorized,
      );

      if (!isMountedRef.current) return;

      if (import.meta.env.DEV) {
        console.log("TwoFAValidationPage: OTP validation successful");
      }

      // Handle successful validation - redirect based on user role
      if (validateResponse.user && validateResponse.user.role) {
        const redirectPath = getRoleRedirectPath(validateResponse.user.role);
        if (import.meta.env.DEV) {
          console.log(`TwoFAValidationPage: Redirecting to ${redirectPath}`);
        }
        navigate(redirectPath);
      } else {
        // Fallback redirect
        if (import.meta.env.DEV) {
          console.log(
            "TwoFAValidationPage: No user role in response, redirecting to dashboard",
          );
        }
        navigate("/dashboard");
      }
    } catch (error) {
      if (!isMountedRef.current) return;

      if (import.meta.env.DEV) {
        console.error("TwoFAValidationPage: OTP validation failed", error);
      }
      setErrors(error);
      window.scrollTo(0, 0);
    } finally {
      if (isMountedRef.current) {
        setIsLoading(false);
      }
    }
  }, [token, twoFactorAuthManager, onUnauthorized, navigate]);

  ////
  //// Misc.
  ////

  useEffect(() => {
    let mounted = true;

    if (mounted) {
      // Start the page at the top
      window.scrollTo({ top: 0, behavior: isMobile ? "instant" : "smooth" });

      // Check if user is authenticated (they should be to access 2FA validation)
      if (!authManager.isAuthenticated()) {
        if (import.meta.env.DEV) {
          console.log(
            "TwoFAValidationPage: User not authenticated, redirecting to login",
          );
        }
        navigate("/login");
        return;
      }
    }

    return () => (mounted = false);
  }, [authManager, navigate, isMobile]);

  ////
  //// Component rendering.
  ////

  return (
    <div className={`min-h-screen relative overflow-hidden ${getThemeClasses("bg-gradient-primary")}`}>
      {/* Animated background blobs */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        <div className={`absolute -top-20 -right-20 sm:-top-32 sm:-right-32 lg:-top-40 lg:-right-40 w-40 h-40 sm:w-60 sm:h-60 lg:w-80 lg:h-80 ${getThemeClasses("decorative-blob-1")} rounded-full filter blur-xl opacity-30 animate-blob`}></div>
        <div className={`absolute -bottom-20 -left-20 sm:-bottom-32 sm:-left-32 lg:-bottom-40 lg:-left-40 w-40 h-40 sm:w-60 sm:h-60 lg:w-80 lg:h-80 ${getThemeClasses("decorative-blob-2")} rounded-full filter blur-xl opacity-30 animate-blob animation-delay-2000`}></div>
        <div className={`absolute top-20 left-20 sm:top-32 sm:left-32 lg:top-40 lg:left-40 w-40 h-40 sm:w-60 sm:h-60 lg:w-80 lg:h-80 ${getThemeClasses("decorative-blob-3")} rounded-full filter blur-xl opacity-30 animate-blob animation-delay-4000`}></div>
      </div>

      <div className="relative z-10 min-h-screen flex items-center justify-center p-4 sm:p-6 lg:p-8">
        <div className="w-full max-w-2xl lg:max-w-3xl xl:max-w-4xl">
          {/* Logo */}
          <div className="text-center mb-6 sm:mb-8 animate-fade-in">
            <Link
              to="/"
              className="inline-flex items-center justify-center w-16 h-16 sm:w-20 sm:h-20 bg-white rounded-2xl shadow-lg"
            >
              <img
                src="/img/flashpointraining-logo.jpeg"
                alt="Flashpoint Training"
                className="w-12 h-12 sm:w-16 sm:h-16 object-contain"
                loading="eager"
                decoding="async"
              />
            </Link>
          </div>

          {/* Main Card */}
          <div className={`backdrop-blur-sm ${getThemeClasses("bg-card")} shadow-2xl rounded-2xl animate-slide-up p-6 sm:p-8 lg:p-10`}>
            {/* Header */}
            <div className="text-center mb-8 sm:mb-10">
              <div className={`inline-flex items-center justify-center w-16 h-16 ${getThemeClasses("bg-accent-light")} rounded-full mb-4`}>
                <ShieldCheckIcon className={`h-8 w-8 ${getThemeClasses("text-accent")}`} />
              </div>
              <h1 className={`text-2xl sm:text-3xl lg:text-4xl font-bold ${getThemeClasses("text-primary")} mb-4`}>
                Two-Factor Authentication
              </h1>
              <p className={`text-base sm:text-lg ${getThemeClasses("text-secondary")} max-w-2xl mx-auto`}>
                Enter the 6-digit verification code from your authenticator app
                to complete your login.
              </p>
            </div>

            {/* Error Display */}
            {Object.keys(errors).length > 0 && (
              <div className={`mb-6 ${getThemeClasses("bg-error-light")} ${getThemeClasses("border-error")} rounded-xl p-6`}>
                <div className="flex items-start space-x-3">
                  <ExclamationTriangleIcon className={`h-6 w-6 ${getThemeClasses("text-error")} mt-0.5 flex-shrink-0`} />
                  <div>
                    <h3 className={`font-semibold ${getThemeClasses("text-error-dark")} mb-2`}>
                      Error occurred:
                    </h3>
                    <div className="space-y-1">
                      {Object.entries(errors).map(([key, value]) => (
                        <div key={key} className={getThemeClasses("text-error-dark")}>
                          <strong>{key}:</strong>{" "}
                          {typeof value === "string"
                            ? value
                            : JSON.stringify(value)}
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              </div>
            )}

            {/* Form */}
            <form onSubmit={handleSubmit} className="space-y-6 sm:space-y-8">
              <div className="space-y-4">
                <OTPInput
                  label="Enter Verification Code"
                  value={token}
                  onChange={setToken}
                  error={errors.token}
                  disabled={isLoading}
                  helperText="Enter the 6-digit code from your authenticator app"
                  autoFocus
                />
              </div>

              {/* Info Box */}
              <div className={`${getThemeClasses("bg-muted-light")} ${getThemeClasses("border-muted")} rounded-xl p-6`}>
                <div className="flex items-start space-x-3">
                  <DevicePhoneMobileIcon className={`h-6 w-6 ${getThemeClasses("text-accent")} mt-0.5 flex-shrink-0`} />
                  <div>
                    <h3 className={`font-semibold ${getThemeClasses("text-primary")} mb-2`}>
                      Using an authenticator app?
                    </h3>
                    <p className={`text-sm ${getThemeClasses("text-secondary")}`}>
                      Open your authenticator app (like Google Authenticator,
                      Authy, or Microsoft Authenticator) and enter the 6-digit
                      code shown for your account.
                    </p>
                  </div>
                </div>
              </div>

              {/* Navigation */}
              <div className={`flex flex-col sm:flex-row justify-between items-center gap-4 pt-6 border-t ${getThemeClasses("border-muted")}`}>
                <Link
                  to="/login/2fa/backup-code-recovery"
                  className={`flex items-center justify-center px-6 py-3 ${getThemeClasses("button-secondary")} rounded-lg transition-all duration-200`}
                >
                  <KeyIcon className="h-4 w-4 mr-2" />
                  Use Backup Code
                </Link>

                <Button
                  type="submit"
                  variant="primary"
                  disabled={isLoading || token.length !== 6}
                  loading={isLoading}
                  className="px-8"
                >
                  {!isLoading && (
                    <span className="inline-flex items-center gap-2">
                      <span>Continue</span>
                      <ArrowRightIcon className="h-4 w-4" />
                    </span>
                  )}
                  {isLoading && "Verifying..."}
                </Button>
              </div>

              {/* Back to Login */}
              <div className="text-center">
                <Link
                  to="/login"
                  className={`text-sm ${getThemeClasses("text-secondary")} ${getThemeClasses("hover:text-accent")} transition-colors`}
                >
                  <ArrowLeftIcon className="h-3 w-3 inline mr-1" />
                  Back to Login
                </Link>
              </div>
            </form>

            {/* Debug info in development */}
            {import.meta.env.DEV && (
              <div className={`mt-8 p-4 ${getThemeClasses("bg-muted-light")} rounded-lg ${getThemeClasses("card-border")}`}>
                <h4 className={`text-sm font-semibold ${getThemeClasses("text-primary")} mb-3`}>
                  Debug Info (Development Only):
                </h4>
                <div className={`space-y-2 text-xs ${getThemeClasses("text-secondary")}`}>
                  <div className="flex items-center justify-between">
                    <span>Authenticated:</span>
                    <span
                      className={`font-medium ${authManager.isAuthenticated() ? getThemeClasses("text-success") : getThemeClasses("text-error")}`}
                    >
                      {authManager.isAuthenticated() ? "Yes" : "No"}
                    </span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span>Token Length:</span>
                    <span className="font-medium">{token.length}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span>Loading:</span>
                    <span
                      className={`font-medium ${isLoading ? getThemeClasses("text-accent") : getThemeClasses("text-success")}`}
                    >
                      {isLoading ? "Yes" : "No"}
                    </span>
                  </div>
                </div>
              </div>
            )}
          </div>

          {/* Copyright */}
          <div className="text-center mt-6 sm:mt-8">
            <p className={`text-sm ${getThemeClasses("text-secondary")}`}>
              © 2025 Flashpoint Training
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}

export default TwoFAValidationPage;
