// File Path: monorepo/web/frontend/src/pages/Anonymous/TwoFA/BackupCodeGeneratePage.jsx
import React, { useState, useEffect, useCallback } from "react";
import { useNavigate, useLocation } from "react-router";
import {
  useAuthManager,
  useTwoFactorAuthManager,
} from "../../../services/Services";
import { getRoleRedirectPath } from "../../../constants/Roles";
import { AUTH_TIMEOUTS } from "../../../constants/Timeouts";
import {
  UIXThemeProvider,
  useUIXTheme,
  useMobileOptimizations,
  BackupCodeDisplay,
} from "../../../components/UIX";
import {
  CheckCircleIcon,
  ShieldCheckIcon,
  ExclamationTriangleIcon,
  ArrowRightIcon,
} from "@heroicons/react/24/outline";

function TwoFABackupCodeGeneratePage() {
  return (
    <UIXThemeProvider>
      <TwoFABackupCodeGeneratePageContent />
    </UIXThemeProvider>
  );
}

function TwoFABackupCodeGeneratePageContent() {
  ////
  //// Backup Code from React Router location state (secure, memory-only).
  ////

  const location = useLocation();

  // Retrieve backup code from navigation state (more secure than sessionStorage)
  // This prevents XSS attacks from accessing storage APIs
  const backupCode = location.state?.backupCode;
  const timestamp = location.state?.timestamp;

  // Validate timeout: backup code expires after 5 minutes for security
  const isExpired = !timestamp || Date.now() - timestamp > AUTH_TIMEOUTS.BACKUP_CODE_EXPIRATION_MS;

  ////
  //// Services.
  ////

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

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

  const [errors, setErrors] = useState({});
  const [currentUser, setCurrentUser] = useState(null);

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

  /**
   * Handle confirmation and redirect to dashboard
   */
  const handleConfirm = useCallback(() => {
    // Clear 2FA setup state since we're done
    twoFactorAuthManager.clearSetupState();

    // Determine redirect path based on user role
    if (currentUser && currentUser.role) {
      const redirectPath = getRoleRedirectPath(currentUser.role);
      if (import.meta.env.DEV) {
        console.log(`TwoFABackupCodeGeneratePage: Redirecting to ${redirectPath}`);
      }
      navigate(redirectPath);
    } else {
      // Fallback redirect
      if (import.meta.env.DEV) {
        console.log(
          "TwoFABackupCodeGeneratePage: No user role found, redirecting to dashboard",
        );
      }
      navigate("/dashboard");
    }
  }, [currentUser, twoFactorAuthManager, 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(
            "TwoFABackupCodeGeneratePage: User not authenticated, redirecting to login",
          );
        }
        navigate("/login");
        return;
      }

      // Check if backup code is provided and not expired
      if (!backupCode || isExpired) {
        if (import.meta.env.DEV) {
          console.log(
            isExpired
              ? "TwoFABackupCodeGeneratePage: Backup code expired (>5 min), redirecting to 2FA setup"
              : "TwoFABackupCodeGeneratePage: No backup code provided, redirecting to 2FA setup",
          );
        }
        navigate("/login/2fa/step-1");
        return;
      }

      // Get current user from auth state for role-based redirect
      const user = authManager.getCurrentUser();
      if (user && user.role) {
        setCurrentUser({ role: user.role });
      } else {
        // If no user data available, redirect to login
        if (import.meta.env.DEV) {
          console.log(
            "TwoFABackupCodeGeneratePage: No user data available, redirecting to login",
          );
        }
        navigate("/login");
        return;
      }

      if (import.meta.env.DEV) {
        console.log(
          "TwoFABackupCodeGeneratePage: Backup code displayed successfully",
        );
      }
    }

    return () => (mounted = false);
  }, [authManager, navigate, backupCode, 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`}>
            {/* Header */}
            <div className="text-center mb-8 sm:mb-10">
              <div className={`inline-flex items-center justify-center w-16 h-16 ${getThemeClasses("bg-success-light")} rounded-full mb-4`}>
                <CheckCircleIcon className={`h-8 w-8 ${getThemeClasses("text-success")}`} />
              </div>
              <h1 className={`text-2xl sm:text-3xl lg:text-4xl font-bold ${getThemeClasses("text-primary")} mb-4`}>
                2FA Setup Complete!
              </h1>
              <p className={`text-base sm:text-lg ${getThemeClasses("text-secondary")} max-w-2xl mx-auto`}>
                Your two-factor authentication has been successfully activated.
                Please save your backup code in a secure location.
              </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>
            )}

            {/* Backup Code Section */}
            <div className="space-y-6 sm:space-y-8">
              <BackupCodeDisplay
                code={backupCode || ""}
                label="Your 2FA Backup Code"
                showWarnings={true}
                onCopy={() => {
                  if (import.meta.env.DEV) {
                    console.log("Backup code copied");
                  }
                }}
              />

              {/* Instructions */}
              <div className={`${getThemeClasses("bg-accent-light")} ${getThemeClasses("border-accent")} rounded-xl p-6`}>
                <div className="flex items-start space-x-3">
                  <ShieldCheckIcon 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 account is now protected with two-factor
                          authentication
                        </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>
                          Every login will require your password AND a code from
                          your authenticator app
                        </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>
                          Use your backup code if you lose access to your
                          authenticator app
                        </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>
                          Contact your administrator if you lose both your
                          authenticator app and backup code
                        </span>
                      </li>
                    </ul>
                  </div>
                </div>
              </div>

              {/* Continue Button */}
              <div className={`flex justify-center pt-6 border-t ${getThemeClasses("border-muted")}`}>
                <button
                  onClick={handleConfirm}
                  className={`flex items-center justify-center px-8 py-3 ${getThemeClasses("button-primary")} rounded-lg transition-all duration-200 font-medium`}
                >
                  Continue to Dashboard
                  <ArrowRightIcon className="h-4 w-4 ml-2" />
                </button>
              </div>
            </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>Has Backup Code:</span>
                    <span
                      className={`font-medium ${backupCode ? getThemeClasses("text-success") : getThemeClasses("text-error")}`}
                    >
                      {backupCode ? "Yes" : "No"}
                    </span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span>Backup Code Length:</span>
                    <span className="font-medium">
                      {backupCode ? backupCode.length : 0}
                    </span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span>Current User Role:</span>
                    <span className="font-medium">
                      {currentUser ? currentUser.role : "Unknown"}
                    </span>
                  </div>
                </div>

                <details className="mt-3">
                  <summary className="text-xs font-medium text-gray-700 cursor-pointer">
                    Auth State (Sanitized)
                  </summary>
                  <pre className="mt-2 text-xs bg-white p-2 rounded border overflow-auto">
                    {JSON.stringify({
                      isAuthenticated: authManager.isAuthenticated(),
                      user: authManager.getCurrentUser() ? {
                        role: authManager.getCurrentUser().role,
                        email: authManager.getCurrentUser().email ? '***@***.***' : null,
                      } : null,
                      // Tokens redacted for security
                      accessToken: authManager.getAuthState().accessToken ? '***REDACTED***' : null,
                      refreshToken: authManager.getAuthState().refreshToken ? '***REDACTED***' : null,
                    }, null, 2)}
                  </pre>
                </details>

                {backupCode && (
                  <details className="mt-3">
                    <summary className="text-xs font-medium text-gray-700 cursor-pointer">
                      Backup Code Status
                    </summary>
                    <pre className="mt-2 text-xs bg-white p-2 rounded border overflow-auto">
                      {JSON.stringify({
                        hasBackupCode: !!backupCode,
                        codeLength: backupCode.length,
                        // Code redacted for security
                        code: '***REDACTED***',
                      }, null, 2)}
                    </pre>
                  </details>
                )}
              </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 TwoFABackupCodeGeneratePage;
