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

function TwoFAStep2Page() {
  return (
    <UIXThemeProvider>
      <TwoFAStep2PageContent />
    </UIXThemeProvider>
  );
}

function TwoFAStep2PageContent() {
  ////
  //// 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 [otpData, setOtpData] = useState(null);
  const [qrCodeBlobUrl, setQrCodeBlobUrl] = useState(null);
  const [copiedField, setCopiedField] = useState(null);
  const [userEmail, setUserEmail] = useState("your-account");

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

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

  const handleCopyToClipboard = useCallback(async (text, fieldName) => {
    try {
      await navigator.clipboard.writeText(text);
      setCopiedField(fieldName);

      // Haptic feedback on mobile
      if (isMobile && window.navigator.vibrate) {
        window.navigator.vibrate(50);
      }

      setTimeout(() => setCopiedField(null), 2000);
    } catch (err) {
      if (import.meta.env.DEV) {
        console.error("Failed to copy text: ", err);
      }
      // Fallback for older browsers
      const textArea = document.createElement("textarea");
      textArea.value = text;
      textArea.style.position = "fixed";
      textArea.style.opacity = "0";
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      try {
        document.execCommand("copy");
        setCopiedField(fieldName);
        setTimeout(() => setCopiedField(null), 2000);
      } catch (fallbackErr) {
        if (import.meta.env.DEV) {
          console.error("Fallback copy failed: ", fallbackErr);
        }
      }
      document.body.removeChild(textArea);
    }
  }, [isMobile]);

  ////
  //// 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(
            "TwoFAStep2Page: User not authenticated, redirecting to login",
          );
        }
        navigate("/login");
        return;
      }

      // Get current user's email for account name display
      const user = authManager.getCurrentUser();
      if (user && user.email) {
        setUserEmail(user.email);
      }

      // Check if we already have setup data
      const setupState = twoFactorAuthManager.getSetupState();
      if (setupState.qrCodeBlobUrl && setupState.base32Secret) {
        if (import.meta.env.DEV) {
          console.log("TwoFAStep2Page: Using existing setup data");
        }
        setOtpData({
          base32: setupState.base32Secret,
          optAuthURL: setupState.optAuthURL,
        });
        setQrCodeBlobUrl(setupState.qrCodeBlobUrl);
      } else {
        // Generate new OTP data
        if (import.meta.env.DEV) {
          console.log("TwoFAStep2Page: Generating new OTP data");
        }
        generateOTPData();
      }
    }

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

  /**
   * Cleanup QR code blob URL to prevent memory leak
   */
  useEffect(() => {
    return () => {
      if (qrCodeBlobUrl) {
        URL.revokeObjectURL(qrCodeBlobUrl);
        if (import.meta.env.DEV) {
          console.log("Step2Page: QR code blob URL cleaned up");
        }
      }
    };
  }, [qrCodeBlobUrl]);

  /**
   * Generate OTP data and QR code
   */
  const generateOTPData = useCallback(async () => {
    setIsLoading(true);
    setErrors({});

    try {
      // Generate OTP secret first
      if (import.meta.env.DEV) {
        console.log("TwoFAStep2Page: Generating OTP secret");
      }
      const otpResponse =
        await twoFactorAuthManager.generateOTP(onUnauthorized);
      setOtpData(otpResponse);

      // Generate QR code
      if (import.meta.env.DEV) {
        console.log("TwoFAStep2Page: Generating QR code");
      }
      const qrBlobUrl =
        await twoFactorAuthManager.generateOTPAndQRCode(onUnauthorized);
      setQrCodeBlobUrl(qrBlobUrl);

      if (import.meta.env.DEV) {
        console.log(
          "TwoFAStep2Page: OTP data and QR code generated successfully",
        );
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("TwoFAStep2Page: Failed to generate OTP data", error);
      }
      setErrors(error);

      // Scroll to top to show errors
      window.scrollTo(0, 0);
    } finally {
      setIsLoading(false);
    }
  }, [twoFactorAuthManager, onUnauthorized]);

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

  if (isLoading) {
    return (
      <div className={`min-h-screen relative overflow-hidden ${getThemeClasses("bg-gradient-primary")}`}>
        <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>

        <div className="relative z-10 min-h-screen flex items-center justify-center p-4 sm:p-6 lg:p-8">
          <div className="text-center">
            <div className="inline-flex items-center justify-center w-16 h-16 sm:w-20 sm:h-20 bg-white rounded-2xl shadow-lg mb-6">
              <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>
            <h1 className={`text-2xl sm:text-3xl font-bold ${getThemeClasses("text-primary")} mb-4`}>
              Generating 2FA Setup...
            </h1>
            <p className={`${getThemeClasses("text-secondary")} text-lg`}>
              Please wait while we prepare your two-factor authentication setup.
            </p>
            <div className="mt-8">
              <div className={`inline-block animate-spin rounded-full h-8 w-8 border-b-2 ${getThemeClasses("border-accent")}`}></div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  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 2 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: "66%" }}
                ></div>
              </div>
            </div>

            {/* Page Content */}
            <div className="space-y-6 sm:space-y-8">
              <div className="text-center">
                <h1 className={`text-2xl sm:text-3xl lg:text-4xl font-bold ${getThemeClasses("text-primary")} mb-4`}>
                  Scan QR Code
                </h1>
                <p className={`text-base sm:text-lg ${getThemeClasses("text-secondary")} max-w-3xl mx-auto`}>
                  With your 2FA application open, please scan the following QR
                  code with your device and click next when ready.
                </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>
              )}

              {/* QR Code Section */}
              <div className={`${getThemeClasses("bg-accent-light")} ${getThemeClasses("border-accent")} rounded-xl p-6 sm:p-8`}>
                <div className="text-center">
                  <div className="flex items-center justify-center mb-6">
                    <QrCodeIcon className={`h-8 w-8 ${getThemeClasses("text-accent")} mr-2`} />
                    <h3 className={`text-xl font-semibold ${getThemeClasses("text-accent-dark")}`}>
                      QR Code Scanner
                    </h3>
                  </div>

                  {qrCodeBlobUrl ? (
                    <div className="inline-block bg-white p-4 rounded-2xl shadow-lg qr-code-container">
                      <img
                        src={qrCodeBlobUrl}
                        alt="2FA QR Code"
                        className="w-48 h-48 sm:w-64 sm:h-64 lg:w-72 lg:h-72 mx-auto rounded-lg"
                        loading="eager"
                        decoding="async"
                      />
                      <p className={`text-sm ${getThemeClasses("text-secondary")} mt-4 font-medium`}>
                        Scan with your authenticator app
                      </p>
                    </div>
                  ) : (
                    <div className="inline-block bg-white p-4 rounded-2xl shadow-lg">
                      <div className={`w-48 h-48 sm:w-64 sm:h-64 lg:w-72 lg:h-72 border-2 dashed ${getThemeClasses("border-muted")} rounded-lg flex items-center justify-center`}>
                        <div className="text-center">
                          <div className={`animate-spin rounded-full h-8 w-8 border-b-2 ${getThemeClasses("border-accent")} mx-auto mb-4`}></div>
                          <p className={`${getThemeClasses("text-secondary")} font-medium`}>
                            QR Code Loading...
                          </p>
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              </div>

              {/* Divider */}
              <div className="relative">
                <div className="absolute inset-0 flex items-center">
                  <div className={`w-full border-t ${getThemeClasses("border-muted")}`}></div>
                </div>
                <div className="relative flex justify-center text-sm">
                  <span className={`px-4 ${getThemeClasses("bg-card")} ${getThemeClasses("text-secondary")} font-medium`}>
                    OR
                  </span>
                </div>
              </div>

              {/* Manual Entry Section */}
              <div className={`${getThemeClasses("bg-muted-light")} ${getThemeClasses("border-muted")} rounded-xl p-6 sm:p-8`}>
                <h3 className={`text-xl font-semibold ${getThemeClasses("text-primary")} mb-4 text-center`}>
                  Manual Entry Method
                </h3>
                <p className={`${getThemeClasses("text-secondary")} mb-6 text-center`}>
                  Copy and paste the following values into your authenticator
                  app:
                </p>

                <div className="space-y-4">
                  {/* Account Name */}
                  <div>
                    <label className={`block text-sm font-semibold ${getThemeClasses("text-primary")} mb-2`}>
                      Account Name:
                    </label>
                    <div className="relative copy-button-container">
                      <textarea
                        readOnly
                        value={`${window.location.hostname}: ${userEmail}`}
                        className={`w-full p-4 ${getThemeClasses("input-border")} rounded-lg ${getThemeClasses("bg-card")} ${getThemeClasses("text-primary")} font-mono text-sm resize-none ${getThemeClasses("input-focus")}`}
                        rows="2"
                      />
                      <button
                        onClick={() =>
                          handleCopyToClipboard(
                            `${window.location.hostname}: ${userEmail}`,
                            "account",
                          )
                        }
                        className={`absolute top-2 right-2 p-2 ${getThemeClasses("text-secondary")} ${getThemeClasses("hover:text-accent")} transition-colors`}
                        title="Copy to clipboard"
                      >
                        {copiedField === "account" ? (
                          <CheckIcon className={`h-4 w-4 ${getThemeClasses("text-success")}`} />
                        ) : (
                          <DocumentDuplicateIcon className="h-4 w-4" />
                        )}
                      </button>
                      {copiedField === "account" && (
                        <div className={`absolute -top-10 right-0 ${getThemeClasses("bg-success")} text-white px-3 py-2 rounded-lg text-sm font-semibold shadow-lg`}>
                          Copied!
                        </div>
                      )}
                    </div>
                  </div>

                  {/* Your Key */}
                  <div>
                    <label className={`block text-sm font-semibold ${getThemeClasses("text-primary")} mb-2`}>
                      Your Key:
                    </label>
                    <div className="relative copy-button-container">
                      <textarea
                        readOnly
                        value={otpData ? otpData.base32 : "Loading..."}
                        className={`w-full p-4 ${getThemeClasses("input-border")} rounded-lg ${getThemeClasses("bg-card")} ${getThemeClasses("text-primary")} font-mono text-sm resize-none ${getThemeClasses("input-focus")}`}
                        rows="3"
                      />
                      <button
                        onClick={() =>
                          handleCopyToClipboard(
                            otpData ? otpData.base32 : "",
                            "key",
                          )
                        }
                        disabled={!otpData}
                        className={`absolute top-2 right-2 p-2 ${getThemeClasses("text-secondary")} ${getThemeClasses("hover:text-accent")} transition-colors disabled:opacity-50 disabled:cursor-not-allowed`}
                        title="Copy to clipboard"
                      >
                        {copiedField === "key" ? (
                          <CheckIcon className={`h-4 w-4 ${getThemeClasses("text-success")}`} />
                        ) : (
                          <DocumentDuplicateIcon className="h-4 w-4" />
                        )}
                      </button>
                      {copiedField === "key" && (
                        <div className={`absolute -top-10 right-0 ${getThemeClasses("bg-success")} text-white px-3 py-2 rounded-lg text-sm font-semibold shadow-lg`}>
                          Copied!
                        </div>
                      )}
                    </div>
                  </div>

                  {/* Type of Key */}
                  <div>
                    <label className={`block text-sm font-semibold ${getThemeClasses("text-primary")} mb-2`}>
                      Type of Key:
                    </label>
                    <div className="relative copy-button-container">
                      <input
                        type="text"
                        readOnly
                        value="Time based"
                        className={`w-full p-4 ${getThemeClasses("input-border")} rounded-lg ${getThemeClasses("bg-card")} ${getThemeClasses("text-primary")} font-mono text-sm ${getThemeClasses("input-focus")}`}
                      />
                      <button
                        onClick={() =>
                          handleCopyToClipboard("Time based", "type")
                        }
                        className={`absolute top-1/2 right-2 transform -translate-y-1/2 p-2 ${getThemeClasses("text-secondary")} ${getThemeClasses("hover:text-accent")} transition-colors`}
                        title="Copy to clipboard"
                      >
                        {copiedField === "type" ? (
                          <CheckIcon className={`h-4 w-4 ${getThemeClasses("text-success")}`} />
                        ) : (
                          <DocumentDuplicateIcon className="h-4 w-4" />
                        )}
                      </button>
                      {copiedField === "type" && (
                        <div className={`absolute -top-10 right-0 ${getThemeClasses("bg-success")} text-white px-3 py-2 rounded-lg text-sm font-semibold shadow-lg`}>
                          Copied!
                        </div>
                      )}
                    </div>
                  </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-1"
                  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 1"
                >
                  <ArrowLeftIcon className="h-4 w-4 mr-2" />
                  Back
                </Link>

                <Link
                  to="/login/2fa/step-3"
                  className={`flex items-center justify-center px-8 py-3 ${getThemeClasses("button-primary")} rounded-lg transition-all duration-200 font-medium`}
                  role="button"
                  aria-label="Continue to step 3"
                >
                  Next
                  <ArrowRightIcon className="h-4 w-4 ml-2" />
                </Link>
              </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>Step:</span>
                    <span className="font-medium">
                      2 of 3 (QR Code Generation)
                    </span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span>Has OTP Data:</span>
                    <span
                      className={`font-medium ${otpData ? getThemeClasses("text-success") : getThemeClasses("text-error")}`}
                    >
                      {otpData ? "Yes" : "No"}
                    </span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span>Has QR Code:</span>
                    <span
                      className={`font-medium ${qrCodeBlobUrl ? getThemeClasses("text-success") : getThemeClasses("text-error")}`}
                    >
                      {qrCodeBlobUrl ? "Yes" : "No"}
                    </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 TwoFAStep2Page;
