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

function TwoFAStep3Page() {
  return (
    <UIXThemeProvider>
      <TwoFAStep3PageContent />
    </UIXThemeProvider>
  );
}

function TwoFAStep3PageContent() {
  ////
  //// 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 [verificationToken, setVerificationToken] = useState("");

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

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

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

    // Clear previous errors
    setErrors({});

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

    setIsLoading(true);

    try {
      if (import.meta.env.DEV) {
        console.log("TwoFAStep3Page: Verifying OTP token");
      }

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

      // Verify OTP during setup
      const verifyResponse = await twoFactorAuthManager.verifyOTP(
        { verification_token: cleanedToken },
        onUnauthorized,
      );

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

      // Check if we have a backup code in the response
      if (verifyResponse.otp_backup_code || verifyResponse.otpBackupCode) {
        const backupCode =
          verifyResponse.otp_backup_code || verifyResponse.otpBackupCode;
        // Pass backup code via React Router state (more secure than sessionStorage)
        // State is memory-only and not accessible via XSS attacks on storage APIs
        navigate("/login/2fa/backup-code", {
          state: { backupCode, timestamp: Date.now() },
        });
      } else {
        // No backup code provided, redirect based on role
        // This shouldn't happen in normal flow, but handle gracefully
        if (import.meta.env.DEV) {
          console.log(
            "TwoFAStep3Page: No backup code in response, redirecting to dashboard",
          );
        }
        navigate("/dashboard");
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("TwoFAStep3Page: OTP verification failed", error);
      }
      setErrors(error);
      window.scrollTo(0, 0);
    } finally {
      setIsLoading(false);
    }
  }, [verificationToken, 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
      if (!authManager.isAuthenticated()) {
        if (import.meta.env.DEV) {
          console.log(
            "TwoFAStep3Page: 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">
            <div 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"
              />
            </div>
          </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`}>
            {/* Progress Wizard */}
            <div className="mb-8 sm:mb-10">
              <div className="flex items-center justify-between mb-4">
                <div className="flex items-center space-x-2">
                  <ShieldCheckIcon className={`h-6 w-6 ${getThemeClasses("text-accent")}`} />
                  <h2 className={`text-lg sm:text-xl font-semibold ${getThemeClasses("text-primary")}`}>
                    Two-Factor Authentication Setup
                  </h2>
                </div>
                <span className={`text-sm font-medium ${getThemeClasses("text-secondary")} ${getThemeClasses("bg-muted")} px-3 py-1 rounded-full`}>
                  Step 3 of 3
                </span>
              </div>

              {/* Progress Bar */}
              <div className={`w-full ${getThemeClasses("bg-muted")} rounded-full h-2 overflow-hidden`}>
                <div
                  className={`h-2 ${getThemeClasses("bg-gradient-accent")} rounded-full transition-all duration-700 ease-out`}
                  style={{ width: "100%" }}
                ></div>
              </div>
            </div>

            {/* Page Content */}
            <div className="space-y-6 sm:space-y-8">
              <div className="text-center">
                <div className="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-br from-red-100 to-orange-100 rounded-full mb-4">
                  <DevicePhoneMobileIcon 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`}>
                  Verify Setup
                </h1>
                <p className={`text-base sm:text-lg ${getThemeClasses("text-secondary")} max-w-3xl mx-auto`}>
                  Enter the 6-digit verification code from your authenticator
                  app to complete the two-factor authentication setup.
                </p>
              </div>

              {/* Error Display */}
              {Object.keys(errors).length > 0 && (
                <div className={`${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={verificationToken}
                    onChange={setVerificationToken}
                    error={errors.verificationToken || errors.verification_token}
                    disabled={isLoading}
                    helperText="Enter the 6-digit code from your authenticator app"
                    autoFocus
                  />
                </div>

                {/* Info Box */}
                <div className={`${getThemeClasses("bg-accent-light")} ${getThemeClasses("border-accent")} rounded-xl p-6`}>
                  <div className="flex items-start space-x-3">
                    <CheckCircleIcon className={`h-6 w-6 ${getThemeClasses("text-accent")} mt-0.5 flex-shrink-0`} />
                    <div>
                      <h3 className={`font-semibold ${getThemeClasses("text-accent-dark")} mb-2`}>
                        What happens next?
                      </h3>
                      <ul className={`space-y-2 text-sm ${getThemeClasses("text-secondary")}`}>
                        <li className="flex items-start space-x-2">
                          <span className={`w-1.5 h-1.5 ${getThemeClasses("bg-accent")} rounded-full mt-2 flex-shrink-0`}></span>
                          <span>
                            Your authenticator app is now linked to your account
                          </span>
                        </li>
                        <li className="flex items-start space-x-2">
                          <span className={`w-1.5 h-1.5 ${getThemeClasses("bg-accent")} rounded-full mt-2 flex-shrink-0`}></span>
                          <span>
                            You'll receive a one-time backup code for emergency
                            access
                          </span>
                        </li>
                        <li className="flex items-start space-x-2">
                          <span className={`w-1.5 h-1.5 ${getThemeClasses("bg-accent")} rounded-full mt-2 flex-shrink-0`}></span>
                          <span>
                            Future logins will require both your password and a
                            code from your app
                          </span>
                        </li>
                      </ul>
                    </div>
                  </div>
                </div>

                {/* Navigation */}
                <div className={`flex flex-col sm:flex-row sm:justify-between sm:items-center gap-4 pt-6 border-t ${getThemeClasses("border-muted")}`}>
                  <Link
                    to="/login/2fa/step-2"
                    className={`flex items-center justify-center px-6 py-3 ${getThemeClasses("button-secondary")} rounded-lg transition-all duration-200`}
                    role="button"
                    aria-label="Go back to step 2"
                  >
                    <ArrowLeftIcon className="h-4 w-4 mr-2" />
                    Back
                  </Link>

                  <button
                    type="submit"
                    disabled={isLoading || verificationToken.length !== 6}
                    className={`flex items-center justify-center px-8 py-3 rounded-lg transition-all duration-200 font-medium ${
                      isLoading || verificationToken.length !== 6
                        ? `${getThemeClasses("bg-muted")} ${getThemeClasses("text-muted-foreground")} cursor-not-allowed`
                        : getThemeClasses("button-primary")
                    }`}
                    aria-label="Complete 2FA setup"
                  >
                    {isLoading ? (
                      <>
                        <div className={`animate-spin rounded-full h-4 w-4 border-b-2 border-current mr-2`}></div>
                        Verifying...
                      </>
                    ) : (
                      <>
                        Complete Setup
                        <ArrowRightIcon className="h-4 w-4 ml-2" />
                      </>
                    )}
                  </button>
                </div>
              </form>
            </div>

            {/* 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>Step:</span>
                    <span className="font-medium">
                      3 of 3 (Verification)
                    </span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span>Token Length:</span>
                    <span className="font-medium">
                      {verificationToken.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")}`}>
              © 2024 Flashpoint Training
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}

export default TwoFAStep3Page;
