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

function TwoFABackupCodeRecoveryPage() {
  return (
    <UIXThemeProvider>
      <TwoFABackupCodeRecoveryPageContent />
    </UIXThemeProvider>
  );
}

function TwoFABackupCodeRecoveryPageContent() {
  ////
  //// 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 [backupCode, setBackupCode] = 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 backup code
    const validationError =
      twoFactorAuthManager.validateRecoveryCode(backupCode);
    if (validationError) {
      setErrors(validationError);
      window.scrollTo(0, 0);
      return;
    }

    setIsLoading(true);

    try {
      if (import.meta.env.DEV) {
        console.log(
          "TwoFABackupCodeRecoveryPage: Using backup code for recovery",
        );
      }

      // Clean backup code (remove whitespace)
      const cleanedBackupCode = backupCode.replace(/\s/g, "");

      // Use recovery code
      const recoveryResponse = await twoFactorAuthManager.recoveryOTP(
        { backup_code: cleanedBackupCode },
        onUnauthorized,
      );

      if (import.meta.env.DEV) {
        console.log(
          "TwoFABackupCodeRecoveryPage: Backup code recovery successful",
        );
      }

      // Handle successful recovery - redirect based on user role
      if (recoveryResponse.user && recoveryResponse.user.role) {
        const redirectPath = getRoleRedirectPath(recoveryResponse.user.role);
        if (import.meta.env.DEV) {
          console.log(
            `TwoFABackupCodeRecoveryPage: Redirecting to ${redirectPath}`,
          );
        }
        navigate(redirectPath);
      } else {
        // Fallback redirect
        if (import.meta.env.DEV) {
          console.log(
            "TwoFABackupCodeRecoveryPage: No user role in response, redirecting to dashboard",
          );
        }
        navigate("/dashboard");
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error(
          "TwoFABackupCodeRecoveryPage: Backup code recovery failed",
          error,
        );
      }
      setErrors(error);
      window.scrollTo(0, 0);
    } finally {
      setIsLoading(false);
    }
  }, [backupCode, 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 backup code recovery)
      if (!authManager.isAuthenticated()) {
        if (import.meta.env.DEV) {
          console.log(
            "TwoFABackupCodeRecoveryPage: 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-error-light")} rounded-full mb-4`}>
                <ShieldExclamationIcon className={`h-8 w-8 ${getThemeClasses("text-error")}`} />
              </div>
              <h1 className={`text-2xl sm:text-3xl lg:text-4xl font-bold ${getThemeClasses("text-primary")} mb-4`}>
                Two-Factor Authentication
              </h1>
              <h2 className={`text-lg sm:text-xl font-semibold ${getThemeClasses("text-secondary")} mb-4`}>
                Backup Code Recovery
              </h2>
              <p className={`text-base ${getThemeClasses("text-secondary")} max-w-2xl mx-auto`}>
                Copy and paste your <strong>2FA backup code</strong> into the
                following field and submit to disable 2FA and log into your
                dashboard.
              </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">
                <label
                  htmlFor="backupCode"
                  className={`block text-lg font-semibold ${getThemeClasses("text-primary")}`}
                >
                  <KeyIcon className="h-5 w-5 inline-block mr-2" />
                  Enter your 2FA Backup Code:
                </label>
                <div className="relative">
                  <input
                    id="backupCode"
                    type="text"
                    placeholder="Please enter here..."
                    value={backupCode}
                    onChange={(e) => setBackupCode(e.target.value)}
                    disabled={isLoading}
                    className={`w-full p-4 sm:p-6 border-2 rounded-xl font-mono text-base sm:text-lg transition-all duration-200 ${
                      errors.backupCode ||
                      errors.backup_code ||
                      errors.recoveryCode
                        ? `${getThemeClasses("border-error")} ${getThemeClasses("bg-error-light")}`
                        : `${getThemeClasses("input-border")} ${getThemeClasses("bg-card")} ${getThemeClasses("input-focus")}`
                    } ${isLoading ? "opacity-50 cursor-not-allowed" : ""}`}
                  />
                  {(errors.backupCode ||
                    errors.backup_code ||
                    errors.recoveryCode) && (
                    <div className={`text-sm mt-2 ${getThemeClasses("text-error")}`}>
                      {errors.backupCode ||
                        errors.backup_code ||
                        errors.recoveryCode}
                    </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"
                  className={`flex items-center justify-center px-6 py-3 ${getThemeClasses("button-secondary")} rounded-lg transition-all duration-200 font-medium`}
                >
                  <ArrowLeftIcon className="h-4 w-4 mr-2" />
                  Back to 2FA
                </Link>

                <button
                  type="submit"
                  disabled={isLoading || !backupCode.trim()}
                  className={`flex items-center justify-center px-8 py-3 rounded-lg font-medium transition-all duration-200 ${
                    isLoading || !backupCode.trim()
                      ? `${getThemeClasses("bg-muted")} ${getThemeClasses("text-muted-foreground")} cursor-not-allowed`
                      : getThemeClasses("button-primary")
                  }`}
                >
                  {isLoading ? (
                    <>
                      <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-current mr-2"></div>
                      Submitting...
                    </>
                  ) : (
                    <>
                      <CheckIcon className="h-4 w-4 mr-2" />
                      Submit
                    </>
                  )}
                </button>
              </div>
            </form>

            {/* Help Text */}
            <div className={`mt-8 ${getThemeClasses("bg-muted-light")} ${getThemeClasses("border-muted")} rounded-xl p-6`}>
              <h3 className={`font-semibold ${getThemeClasses("text-primary")} mb-3`}>
                Need Help?
              </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>
                    Backup codes are typically 8-16 characters long
                  </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>
                    They may contain letters, numbers, or dashes
                  </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>
                    Each backup code can only be used once
                  </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>
                    If you don't have your backup code, contact your
                    administrator
                  </span>
                </li>
              </ul>
            </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>Backup Code Length:</span>
                    <span className="font-medium">{backupCode.length}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span>Loading:</span>
                    <span className="font-medium">
                      {isLoading ? "Yes" : "No"}
                    </span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span>Has Errors:</span>
                    <span className="font-medium">
                      {Object.keys(errors).length > 0 ? "Yes" : "No"}
                    </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>
              </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 TwoFABackupCodeRecoveryPage;
