// File: monorepo/web/maplefile-frontend/src/pages/Anonymous/Login/VerifyOTT.jsx
// UIX version - Step 2: Verify One-Time Token
import { useState, useEffect, useRef, useCallback, useMemo } from "react";
import { useNavigate, useLocation, Link } from "react-router";
import { useServices } from "../../../services/Services";
import { Card, OTPInput, Button, Alert, GDPRFooter } from "../../../components/UIX";
import { useUIXTheme } from "../../../components/UIX/themes/useUIXTheme";
import {
  ArrowRightIcon,
  LockClosedIcon,
  CheckIcon,
  ClockIcon,
  EnvelopeIcon,
  KeyIcon,
} from "@heroicons/react/24/outline";

const VerifyOTT = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { authManager, localStorageService } = useServices();
  const { getThemeClasses } = useUIXTheme();

  // Check if we came from CompleteLogin with an auto-resent code
  const codeWasAutoResent = location.state?.codeResent === true;

  // Refs for cleanup and preventing state updates after unmount
  const isMountedRef = useRef(true);
  const timerRef = useRef(null);
  const resendTimeoutRef = useRef(null);

  const [ott, setOtt] = useState("");
  const [email, setEmail] = useState("");
  const [loading, setLoading] = useState(false);
  const [generalError, setGeneralError] = useState("");
  const [fieldErrors, setFieldErrors] = useState({});
  const [resendLoading, setResendLoading] = useState(false);
  const [resendSuccess, setResendSuccess] = useState(codeWasAutoResent); // Show success if auto-resent
  const [timeRemaining, setTimeRemaining] = useState(600); // 10 minutes in seconds

  // Cleanup effect - prevents memory leaks
  useEffect(() => {
    isMountedRef.current = true;

    return () => {
      isMountedRef.current = false;
      // Clear all timers
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
      if (resendTimeoutRef.current) {
        clearTimeout(resendTimeoutRef.current);
      }
    };
  }, []);

  // Handle auto-resent code from CompleteLogin - clear navigation state and auto-hide message
  useEffect(() => {
    if (codeWasAutoResent) {
      // Clear the navigation state to prevent showing message on refresh
      window.history.replaceState({}, document.title);

      // Auto-hide the success message after 5 seconds
      const timeout = setTimeout(() => {
        if (isMountedRef.current) {
          setResendSuccess(false);
        }
      }, 5000);

      return () => clearTimeout(timeout);
    }
  }, [codeWasAutoResent]);

  // Initialize email from storage
  useEffect(() => {
    // Try multiple sources for email
    let storedEmail = null;

    // Try 1: Get from authManager
    if (authManager && typeof authManager.getCurrentUserEmail === "function") {
      try {
        storedEmail = authManager.getCurrentUserEmail();
        if (storedEmail && import.meta.env.DEV) {
          console.log("[VerifyOTT] Using email from authManager");
        }
      } catch (err) {
        if (import.meta.env.DEV) {
          console.warn("[VerifyOTT] Could not get email from authManager:", err);
        }
      }
    }

    // Try 2: Get from localStorageService
    if (!storedEmail && localStorageService) {
      try {
        storedEmail = localStorageService.getUserEmail();
        if (storedEmail && import.meta.env.DEV) {
          console.log("[VerifyOTT] Using email from localStorageService");
        }
      } catch (err) {
        if (import.meta.env.DEV) {
          console.warn("[VerifyOTT] Could not get email from localStorageService:", err);
        }
      }
    }

    // Try 3: Get from sessionStorage (fallback)
    if (!storedEmail) {
      storedEmail = sessionStorage.getItem("loginEmail");
      if (storedEmail && import.meta.env.DEV) {
        console.log("[VerifyOTT] Using email from sessionStorage");
      }
    }

    if (storedEmail) {
      setEmail(storedEmail);
    } else {
      // If no email found anywhere, redirect to first step
      if (import.meta.env.DEV) {
        console.log("[VerifyOTT] No stored email found, redirecting to start");
      }
      navigate("/login/request-ott");
    }
  }, [navigate, authManager, localStorageService]);

  // Countdown timer effect
  useEffect(() => {
    if (timeRemaining <= 0) return;

    timerRef.current = setInterval(() => {
      setTimeRemaining((prev) => {
        if (prev <= 1) {
          return 0;
        }
        return prev - 1;
      });
    }, 1000);

    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
    };
  }, [timeRemaining]);

  // Memoize time formatting function
  const formatTime = useCallback((seconds) => {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`;
  }, []);

  const handleSubmit = useCallback(
    async (e) => {
      e.preventDefault();

      // Prevent state updates if component is unmounted
      if (!isMountedRef.current) return;

      setLoading(true);
      setGeneralError("");
      setFieldErrors({});

      try {
        // Validate services are available
        if (!authManager) {
          throw new Error(
            "Authentication service not available. Please refresh the page.",
          );
        }

        if (import.meta.env.DEV) {
          console.log("[VerifyOTT] Verifying OTT via AuthManager");
        }

        const trimmedEmail = email.trim().toLowerCase();

        // Try different possible method names
        let response;

        if (typeof authManager.verifyOTP === "function") {
          response = await authManager.verifyOTP({
            email: trimmedEmail,
            otp_code: ott,
          });
        } else if (typeof authManager.verifyOTT === "function") {
          response = await authManager.verifyOTT(trimmedEmail, ott);
        } else if (typeof authManager.verify === "function") {
          response = await authManager.verify({
            email: trimmedEmail,
            code: ott,
          });
        } else {
          // Generic error - don't expose implementation details
          throw new Error("Authentication service is temporarily unavailable.");
        }

        // Check if component is still mounted before updating state
        if (!isMountedRef.current) return;

        // Validate that we got a proper response
        if (!response) {
          throw new Error("Verification failed. Please try again.");
        }

        // Check if response indicates error
        if (response.error) {
          throw new Error(response.error);
        }

        if (import.meta.env.DEV) {
          console.log("[VerifyOTT] Verification successful");
        }

        // Store the verification response data for CompleteLogin to use
        try {
          // Store in sessionStorage as primary method
          sessionStorage.setItem(
            "otpVerificationResult",
            JSON.stringify(response),
          );

          // Also try to store via localStorageService if available
          if (
            localStorageService &&
            typeof localStorageService.setLoginSessionData === "function"
          ) {
            try {
              localStorageService.setLoginSessionData(
                "verify_response",
                response,
              );
            } catch (storageError) {
              if (import.meta.env.DEV) {
                console.warn(
                  "[VerifyOTT] Could not store via localStorageService:",
                  storageError,
                );
              }
            }
          }

          // Store email as well to ensure it's available
          sessionStorage.setItem("loginEmail", trimmedEmail);

          // Also try to store email via authManager if available
          if (
            authManager &&
            typeof authManager.setCurrentUserEmail === "function"
          ) {
            try {
              authManager.setCurrentUserEmail(trimmedEmail);
            } catch (emailError) {
              if (import.meta.env.DEV) {
                console.warn(
                  "[VerifyOTT] Could not store email via authManager:",
                  emailError,
                );
              }
            }
          }
        } catch (storageError) {
          if (import.meta.env.DEV) {
            console.error(
              "[VerifyOTT] Failed to store verification data:",
              storageError,
            );
          }
          throw new Error(
            "Verification successful but failed to store data. Please try again.",
          );
        }

        // Navigate to complete login step
        navigate("/login/complete");
      } catch (error) {
        if (!isMountedRef.current) return;

        // Log only in development
        if (import.meta.env.DEV) {
          console.error("[VerifyOTT] Verification failed:", error);
        }

        // Parse RFC 9457 error response
        if (error.fieldErrors && Object.keys(error.fieldErrors).length > 0) {
          setFieldErrors(error.fieldErrors);
          setGeneralError("Please fix the following issues:");
        } else if (error.message) {
          // Sanitize error messages - remove technical details
          let userMessage = error.message;

          // Remove technical prefixes
          userMessage = userMessage.replace(/^Failed to verify OTT:\s*/i, "");
          userMessage = userMessage.replace(/^Request failed:\s*/i, "");
          userMessage = userMessage.replace(/^Error:\s*/i, "");
          userMessage = userMessage.replace(
            /^Authentication service.*$/i,
            "Service temporarily unavailable.",
          );

          // Replace generic validation message with friendlier one
          if (userMessage.includes("One or more fields failed validation")) {
            userMessage = "Please check your verification code and try again.";
          }

          // Prevent information disclosure - sanitize technical errors
          if (
            userMessage.includes("method not found") ||
            userMessage.includes("not defined") ||
            userMessage.includes("undefined") ||
            userMessage.includes("Available methods")
          ) {
            userMessage =
              "Service temporarily unavailable. Please try again later.";
          }

          setGeneralError(userMessage);
        } else {
          setGeneralError("Could not verify code. Please try again.");
        }
      } finally {
        if (isMountedRef.current) {
          setLoading(false);
        }
      }
    },
    [ott, email, authManager, localStorageService, navigate],
  );

  const handleResendCode = useCallback(async () => {
    if (!authManager) {
      setGeneralError(
        "Authentication service not available. Please refresh the page.",
      );
      return;
    }

    setResendLoading(true);
    setGeneralError("");
    setFieldErrors({});
    setResendSuccess(false);

    try {
      if (import.meta.env.DEV) {
        console.log("[VerifyOTT] Resending OTT code...");
      }

      const trimmedEmail = email.trim().toLowerCase();

      // Try different possible method names for requesting OTT
      if (typeof authManager.requestOTT === "function") {
        await authManager.requestOTT(trimmedEmail);
      } else if (typeof authManager.requestOTP === "function") {
        await authManager.requestOTP({ email: trimmedEmail });
      } else {
        throw new Error("Service temporarily unavailable.");
      }

      if (!isMountedRef.current) return;

      if (import.meta.env.DEV) {
        console.log("[VerifyOTT] Code resent successfully");
      }

      setResendSuccess(true);
      setOtt(""); // Clear the current code
      setTimeRemaining(600); // Reset timer to 10 minutes

      // Clear success message after 3 seconds
      resendTimeoutRef.current = setTimeout(() => {
        if (isMountedRef.current) {
          setResendSuccess(false);
        }
      }, 3000);
    } catch (err) {
      if (!isMountedRef.current) return;

      if (import.meta.env.DEV) {
        console.error("[VerifyOTT] Failed to resend code:", err);
      }

      // Sanitize error message
      let errorMessage = err.message || "Failed to resend code. Please try again.";
      if (
        errorMessage.includes("method not found") ||
        errorMessage.includes("not defined")
      ) {
        errorMessage = "Service temporarily unavailable. Please try again later.";
      }

      setGeneralError(errorMessage);
    } finally {
      if (isMountedRef.current) {
        setResendLoading(false);
      }
    }
  }, [email, authManager]);

  const handleBackToEmail = useCallback(() => {
    navigate("/login/request-ott");
  }, [navigate]);

  const handleOttChange = useCallback((value) => {
    setOtt(value);
    // Clear errors only once when user starts typing - uses functional updates
    // to avoid dependencies on error state values
    setGeneralError((prev) => prev ? "" : prev);
    setFieldErrors((prev) => Object.keys(prev).length > 0 ? {} : prev);
  }, []);

  // Memoize display email
  const displayEmail = useMemo(() => email || "", [email]);

  // Memoize timer display
  const timerDisplay = useMemo(() => formatTime(timeRemaining), [formatTime, timeRemaining]);

  return (
    <div className={`min-h-screen relative overflow-hidden ${getThemeClasses("bg-gradient-primary")} flex flex-col`}>
      {/* Decorative background blobs */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        <div className={`absolute -top-40 -right-40 w-80 h-80 ${getThemeClasses("decorative-blob-1")} rounded-full filter blur-xl opacity-30 animate-blob`}></div>
        <div className={`absolute -bottom-40 -left-40 w-80 h-80 ${getThemeClasses("decorative-blob-2")} rounded-full filter blur-xl opacity-30 animate-blob animation-delay-2000`}></div>
        <div className={`absolute top-40 left-40 w-80 h-80 ${getThemeClasses("decorative-blob-3")} rounded-full filter blur-xl opacity-30 animate-blob animation-delay-4000`}></div>
      </div>

      {/* Header */}
      <div className="relative z-10 flex-shrink-0">
        <nav className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 flex justify-between items-center">
          <Link to="/" className="inline-flex items-center space-x-3 group">
            <div className="relative">
              <div className={`absolute inset-0 ${getThemeClasses("bg-gradient-secondary")} rounded-xl opacity-0 group-hover:opacity-100 blur-xl transition-opacity duration-300`}></div>
              <div className={`relative flex items-center justify-center h-10 w-10 ${getThemeClasses("bg-gradient-secondary")} rounded-xl shadow-md group-hover:shadow-lg transform group-hover:scale-105 transition-all duration-200`}>
                <LockClosedIcon className="h-5 w-5 text-white" />
              </div>
            </div>
            <span className={`text-xl font-bold ${getThemeClasses("text-primary")} transition-colors duration-200`}>
              MapleFile
            </span>
          </Link>
        </nav>
      </div>

      {/* Main Content */}
      <div className="relative z-10 flex-1 flex items-center justify-center px-4 sm:px-6 lg:px-8 py-12">
        <div className="w-full max-w-md space-y-8 animate-fade-in-up">
          {/* Progress Indicator */}
          <div className="flex items-center justify-center">
            <div className="flex items-center space-x-4">
              <div className="flex items-center">
                <div className="flex items-center justify-center w-8 h-8 bg-green-500 rounded-full text-white text-sm font-bold">
                  <CheckIcon className="h-4 w-4" />
                </div>
                <span className="ml-2 text-sm font-semibold text-green-600">Email</span>
              </div>
              <div className="w-12 h-0.5 bg-green-500"></div>
              <div className="flex items-center">
                <div className={`flex items-center justify-center w-8 h-8 ${getThemeClasses("bg-gradient-secondary")} rounded-full text-white text-sm font-bold shadow-md`}>
                  2
                </div>
                <span className={`ml-2 text-sm font-semibold ${getThemeClasses("text-primary")}`}>
                  Verify
                </span>
              </div>
              <div className="w-12 h-0.5 bg-gray-300"></div>
              <div className="flex items-center">
                <div className="flex items-center justify-center w-8 h-8 bg-gray-200 rounded-full text-gray-500 text-sm font-bold">
                  3
                </div>
                <span className="ml-2 text-sm text-gray-500">Access</span>
              </div>
            </div>
          </div>

          {/* Header */}
          <div className="text-center">
            <div className="flex justify-center mb-6">
              <div className="relative">
                <div className={`absolute inset-0 ${getThemeClasses("bg-gradient-secondary")} rounded-2xl blur-2xl opacity-20`}></div>
                <div className={`relative h-16 w-16 ${getThemeClasses("bg-gradient-secondary")} rounded-2xl flex items-center justify-center shadow-xl`}>
                  <KeyIcon className="h-8 w-8 text-white" />
                </div>
              </div>
            </div>
            <h1 className={`text-3xl font-bold ${getThemeClasses("text-primary")}`}>
              Check your email
            </h1>
            <p className={`mt-2 ${getThemeClasses("text-secondary")}`}>
              Enter the code we sent to your inbox
            </p>
            <div className="flex items-center justify-center space-x-2 text-sm mt-4">
              <ClockIcon className="h-4 w-4 text-amber-600" />
              <span
                className={
                  timeRemaining <= 60
                    ? "text-red-600 font-semibold"
                    : getThemeClasses("text-secondary")
                }
              >
                {timeRemaining > 0
                  ? `Code expires in ${timerDisplay}`
                  : "Code has expired"}
              </span>
            </div>
          </div>

          {/* Form Card */}
          <Card
            className="backdrop-blur-sm bg-white/95 shadow-2xl animate-fade-in-up"
            style={{ animationDelay: "100ms" }}
          >
            {/* Error Alert */}
            {(generalError || Object.keys(fieldErrors).length > 0) && (
              <Alert
                type="error"
                dismissible
                onDismiss={() => {
                  setGeneralError("");
                  setFieldErrors({});
                }}
              >
                <div>
                  {generalError && <p className="text-sm font-medium mb-2">{generalError}</p>}
                  {Object.keys(fieldErrors).length > 0 && (
                    <div className="mt-2">
                      <p className="text-sm font-semibold mb-1">
                        Please fix the following errors:
                      </p>
                      <ul className="list-disc list-inside text-sm space-y-1">
                        {Object.entries(fieldErrors).map(([field, message]) => (
                          <li key={field}>
                            <span className="font-medium capitalize">{field}:</span> {message}
                          </li>
                        ))}
                      </ul>
                    </div>
                  )}
                </div>
              </Alert>
            )}

            {/* Success Alert */}
            {resendSuccess && (
              <Alert type="success">
                <p className="text-sm">A new code has been sent to your email.</p>
              </Alert>
            )}

            {/* Help Info */}
            <Alert type="info">
              <div>
                <h3 className="text-sm font-semibold mb-2">Didn't get a code?</h3>
                <p className="text-xs">
                  Check your spam folder or click "Resend Code". Codes expire after 10 minutes for
                  security.
                </p>
              </div>
            </Alert>

            {/* Email Display */}
            <div className="p-4 bg-gray-100 rounded-lg border border-gray-200">
              <div className="flex items-center">
                <EnvelopeIcon className="h-5 w-5 text-gray-400 mr-3" />
                <p className="text-sm text-gray-800 font-medium truncate">{displayEmail}</p>
                <Button
                  onClick={handleBackToEmail}
                  disabled={loading}
                  variant="ghost"
                  size="sm"
                  className={`ml-auto ${getThemeClasses("link-primary")} hover:underline flex-shrink-0 px-2 py-1`}
                >
                  Change
                </Button>
              </div>
            </div>

            <form onSubmit={handleSubmit} className="space-y-6">
              {/* OTP Input - UIX Component */}
              <OTPInput
                value={ott}
                onChange={handleOttChange}
                maxLength={8}
                placeholder="00000000"
                disabled={loading}
                error={fieldErrors.ott}
              />

              {/* Submit Button */}
              <Button
                type="submit"
                variant="primary"
                fullWidth
                disabled={loading || !authManager || timeRemaining <= 0 || ott.length !== 8}
                loading={loading}
                loadingText="Verifying..."
              >
                <span className="inline-flex items-center justify-center gap-2">
                  <span>
                    {timeRemaining <= 0 ? "Code Expired" : "Verify & Continue"}
                  </span>
                  {timeRemaining > 0 && <ArrowRightIcon className="h-5 w-5" />}
                </span>
              </Button>

              {/* Resend Button */}
              <Button
                type="button"
                variant="outline"
                fullWidth
                onClick={handleResendCode}
                disabled={resendLoading || !authManager}
                loading={resendLoading}
                loadingText="Sending..."
              >
                Resend Code
              </Button>
            </form>
          </Card>
        </div>
      </div>

      {/* Footer */}
      <GDPRFooter containerClassName="bg-white/75" />

      {/* Animation Styles */}
      <style>{`
        @keyframes fade-in-up {
          from {
            opacity: 0;
            transform: translateY(30px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }
        .animate-fade-in-up {
          animation: fade-in-up 0.6s ease-out forwards;
        }
        @keyframes blob {
          0% {
            transform: translate(0px, 0px) scale(1);
          }
          33% {
            transform: translate(30px, -50px) scale(1.1);
          }
          66% {
            transform: translate(-20px, 20px) scale(0.9);
          }
          100% {
            transform: translate(0px, 0px) scale(1);
          }
        }
        .animate-blob {
          animation: blob 7s infinite;
        }
        .animation-delay-2000 {
          animation-delay: 2s;
        }
        .animation-delay-4000 {
          animation-delay: 4s;
        }
      `}</style>
    </div>
  );
};

export default VerifyOTT;
