// File Path: monorepo/web/frontend/src/pages/Anonymous/TwoFA/Step1Page.jsx
import React, { useEffect, useCallback } from "react";
import { Link, useNavigate } from "react-router";
import { useAuthManager } from "../../../services/Services";
import {
  UIXThemeProvider,
  useUIXTheme,
  useMobileOptimizations,
} from "../../../components/UIX";
import { BRAND_COLORS, getBrandButtonClasses } from "../../../constants/BrandColors";
import {
  DevicePhoneMobileIcon,
  ComputerDesktopIcon,
  ArrowRightIcon,
  ArrowLeftIcon,
  CheckCircleIcon,
  ShieldCheckIcon,
  QrCodeIcon,
} from "@heroicons/react/24/outline";

function TwoFAStep1Page() {
  return (
    <UIXThemeProvider>
      <TwoFAStep1PageContent />
    </UIXThemeProvider>
  );
}

function TwoFAStep1PageContent() {
  const authManager = useAuthManager();
  const navigate = useNavigate();
  const { getThemeClasses } = useUIXTheme();
  const { isMobile } = useMobileOptimizations();

  useEffect(() => {
    // Start the page at the top
    window.scrollTo({ top: 0, behavior: "smooth" });

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

  const handleCancel = useCallback(() => {
    // Clear auth data and redirect to login
    authManager.clearAuthData();
    navigate("/login");
  }, [authManager, navigate]);

  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 1 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: "33%" }}
                ></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`}>
                  Setup Two-Factor Authentication
                </h1>
                <p className={`text-base sm:text-lg ${getThemeClasses("text-secondary")} max-w-3xl mx-auto`}>
                  To ensure your account stays secure, you need to sign in using{" "}
                  <span className={`font-semibold ${getThemeClasses("text-accent")}`}>
                    two-factor Authentication (2FA)
                  </span>
                  . The following wizard will help you get setup with 2FA.
                </p>
              </div>

              {/* Setup Instructions */}
              <div className={`${getThemeClasses("bg-info-light")} ${getThemeClasses("border-info")} border rounded-xl p-6`}>
                <div className="flex items-start space-x-3">
                  <QrCodeIcon className={`h-6 w-6 ${getThemeClasses("text-info")} mt-0.5 flex-shrink-0`} />
                  <div>
                    <h3 className={`font-semibold ${getThemeClasses("text-info-dark")} mb-2`}>
                      Recommended Setup Process
                    </h3>
                    <p className={`${getThemeClasses("text-info-dark")} mb-4`}>
                      To make initial 2FA setup easier, we encourage you to login
                      on a device BESIDES the mobile device with the camera that
                      you wish to use.
                    </p>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                      <div className="flex items-center space-x-3 bg-white/70 rounded-lg p-3">
                        <ComputerDesktopIcon className={`h-5 w-5 ${getThemeClasses("text-accent")}`} />
                        <span className={`text-sm font-medium ${getThemeClasses("text-info-dark")}`}>
                          Login on a desktop device
                        </span>
                      </div>
                      <div className="flex items-center space-x-3 bg-white/70 rounded-lg p-3">
                        <DevicePhoneMobileIcon className={`h-5 w-5 ${getThemeClasses("text-accent")}`} />
                        <span className={`text-sm font-medium ${getThemeClasses("text-info-dark")}`}>
                          Use mobile to scan QR code
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              {/* Download Apps Section */}
              <div>
                <h2 className={`text-xl sm:text-2xl font-bold ${getThemeClasses("text-primary")} mb-6 text-center`}>
                  Choose Your Authenticator App
                </h2>

                <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                  {/* Apple 2FA Authenticator */}
                  <div className={`${getThemeClasses("bg-card")} ${getThemeClasses("card-border")} rounded-xl p-6 ${getThemeClasses("hover-shadow")} transition-all duration-300`}>
                    <div className="text-center mb-4">
                      <div className={`w-12 h-12 mx-auto bg-gray-900 rounded-xl flex items-center justify-center mb-3`}>
                        <span className="text-white text-lg font-bold">🍎</span>
                      </div>
                      <h3 className={`text-lg font-bold ${getThemeClasses("text-primary")} mb-2`}>
                        Apple 2FA
                      </h3>
                    </div>
                    <p className={`${getThemeClasses("text-secondary")} text-sm mb-4 leading-relaxed`}>
                      All iOS and Mac devices with a <strong>Safari Web Browser</strong>{" "}
                      come with built-in 2FA verification services. Sign in with your{" "}
                      <em>Apple ID</em> in Safari and you can take advantage of this
                      service.
                    </p>
                    <div className="flex items-center justify-center">
                      <CheckCircleIcon className={`h-5 w-5 ${getThemeClasses("text-success")}`} />
                      <span className={`text-sm font-medium ${getThemeClasses("text-success")} ml-2`}>
                        Built-in Solution
                      </span>
                    </div>
                  </div>

                  {/* Google Authenticator */}
                  <div className={`${getThemeClasses("bg-card")} ${getThemeClasses("card-border")} rounded-xl p-6 ${getThemeClasses("hover-shadow")} transition-all duration-300`}>
                    <div className="text-center mb-4">
                      <div className={`w-12 h-12 mx-auto ${getThemeClasses("bg-accent")} rounded-xl flex items-center justify-center mb-3`}>
                        <span className="text-white text-lg font-bold">G</span>
                      </div>
                      <h3 className={`text-lg font-bold ${getThemeClasses("text-primary")} mb-2`}>
                        Google Authenticator
                      </h3>
                    </div>
                    <p className={`${getThemeClasses("text-secondary")} text-sm mb-4 leading-relaxed`}>
                      This 2FA app is created by <strong>Google, Inc.</strong> and
                      works on both iOS and Android devices.
                    </p>
                    <div className="space-y-2">
                      <a
                        href="https://apps.apple.com/ca/app/google-authenticator/id388497605"
                        target="_blank"
                        rel="noreferrer"
                        className={`flex items-center justify-center w-full py-2 px-3 ${getBrandButtonClasses('IOS')} text-white text-xs font-medium rounded-lg transition-colors ${isMobile ? "min-h-[44px]" : ""}`}
                        role="button"
                        aria-label="Download Google Authenticator for iOS"
                      >
                        Download for iOS →
                      </a>
                      <a
                        href="https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2&pli=1"
                        target="_blank"
                        rel="noreferrer"
                        className={`flex items-center justify-center w-full py-2 px-3 ${getBrandButtonClasses('ANDROID')} text-white text-xs font-medium rounded-lg transition-colors ${isMobile ? "min-h-[44px]" : ""}`}
                        role="button"
                        aria-label="Download Google Authenticator for Android"
                      >
                        Download for Android →
                      </a>
                    </div>
                  </div>

                  {/* Authenticator Chrome Extension */}
                  <div className={`${getThemeClasses("bg-card")} ${getThemeClasses("card-border")} rounded-xl p-6 ${getThemeClasses("hover-shadow")} transition-all duration-300`}>
                    <div className="text-center mb-4">
                      <div className={`w-12 h-12 mx-auto ${BRAND_COLORS.AUTHENTICATOR_EXTENSION.ICON_BG} rounded-xl flex items-center justify-center mb-3`}>
                        <span className="text-white text-lg font-bold">A</span>
                      </div>
                      <h3 className={`text-lg font-bold ${getThemeClasses("text-primary")} mb-2`}>
                        Authenticator
                      </h3>
                    </div>
                    <p className={`${getThemeClasses("text-secondary")} text-sm mb-4 leading-relaxed`}>
                      This 2FA app is created by <strong>authenticator.cc</strong> and
                      works as a Chrome browser extension.
                    </p>
                    <a
                      href="https://chromewebstore.google.com/detail/authenticator/bhghoamapcdpbohphigoooaddinpkbai?pli=1"
                      target="_blank"
                      rel="noreferrer"
                      className={`flex items-center justify-center w-full py-2 px-3 ${getThemeClasses("bg-accent")} text-white text-xs font-medium rounded-lg ${getThemeClasses("hover-accent-dark")} transition-colors ${isMobile ? "min-h-[44px]" : ""}`}
                      role="button"
                      aria-label="Add Authenticator extension to Chrome"
                    >
                      Add to Chrome →
                    </a>
                  </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-color")}`}>
                <button
                  onClick={handleCancel}
                  className={`flex items-center justify-center px-6 py-3 ${getThemeClasses("btn-secondary")} rounded-lg transition-all duration-200 ${isMobile ? "min-h-[44px]" : ""}`}
                  type="button"
                  aria-label="Cancel 2FA setup and return to login"
                >
                  <ArrowLeftIcon className="h-4 w-4 mr-2" />
                  Cancel Setup
                </button>

                <Link
                  to="/login/2fa/step-2"
                  className={`flex items-center justify-center px-8 py-3 ${getThemeClasses("btn-primary")} rounded-lg ${getThemeClasses("hover-transform")} transition-all duration-200 font-medium ${isMobile ? "min-h-[44px]" : ""}`}
                  role="button"
                  aria-label="Continue to step 2 of 2FA setup"
                >
                  Continue Setup
                  <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")} 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">
                      1 of 3 (Introduction & App Downloads)
                    </span>
                  </div>
                </div>
                <details className="mt-3">
                  <summary className={`text-xs font-medium ${getThemeClasses("text-primary")} cursor-pointer`}>
                    Auth State (Sanitized)
                  </summary>
                  <pre className={`mt-2 text-xs bg-white p-2 rounded ${getThemeClasses("card-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-muted")}`}>
              © 2025 Flashpoint Training
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}

export default TwoFAStep1Page;
