// File: monorepo/web/maplefile-frontend/src/pages/Anonymous/Login/RequestOTT.jsx
// UIX version - Step 1: Request One-Time Token
import { useState, useEffect, useRef, useCallback } from "react";
import { useNavigate, Link } from "react-router";
import { useServices } from "../../../services/Services";
import { Card, Input, Button, Alert, GDPRFooter, ProgressIndicator, Divider } from "../../../components/UIX";
import { useUIXTheme } from "../../../components/UIX/themes/useUIXTheme";
import {
  ArrowRightIcon,
  LockClosedIcon,
  ShieldCheckIcon,
  SparklesIcon,
} from "@heroicons/react/24/outline";

const RequestOTT = () => {
  const navigate = useNavigate();
  const { authManager } = useServices();
  const { getThemeClasses } = useUIXTheme();

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

  const [email, setEmail] = useState("");
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState("");
  const [generalError, setGeneralError] = useState("");
  const [fieldErrors, setFieldErrors] = useState({});

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

    return () => {
      isMountedRef.current = false;
      // Clear any pending timeouts
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
        timeoutRef.current = null;
      }
    };
  }, []);

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

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

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

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

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

      // Log only in development
      if (import.meta.env.DEV) {
        console.log("[RequestOTT] Requesting OTT via AuthManager");
      }

      // Store email BEFORE making the request
      sessionStorage.setItem("loginEmail", trimmedEmail);

      // Make the OTT request
      let response;
      if (typeof authManager.requestOTT === "function") {
        response = await authManager.requestOTT(trimmedEmail);
      } else if (typeof authManager.requestOTP === "function") {
        response = await authManager.requestOTP({ email: trimmedEmail });
      } else {
        // Generic error message - 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;

      setMessage(response.message || "Verification code sent successfully!");

      // Store email in localStorage via authManager if available
      try {
        if (
          authManager.setCurrentUserEmail &&
          typeof authManager.setCurrentUserEmail === "function"
        ) {
          authManager.setCurrentUserEmail(trimmedEmail);
        }
      } catch (storageError) {
        // Silently handle storage errors - non-critical
        if (import.meta.env.DEV) {
          console.warn("[RequestOTT] Could not store email via authManager:", storageError);
        }
      }

      // Wait a moment to show the success message, then navigate
      // Store timeout ID for cleanup
      timeoutRef.current = setTimeout(() => {
        if (isMountedRef.current) {
          navigate("/login/verify-ott");
        }
      }, 2000);
    } catch (err) {
      // Check if component is still mounted before updating state
      if (!isMountedRef.current) return;

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

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

        // Remove technical prefixes
        userMessage = userMessage.replace(/^Failed to request 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 email address and try again.';
        }

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

        setGeneralError(userMessage);
      } else {
        setGeneralError("Could not send login code. Please try again.");
      }
    } finally {
      // Check if component is still mounted before updating state
      if (isMountedRef.current) {
        setLoading(false);
      }
    }
  }, [email, authManager, navigate]); // Include all dependencies

  const handleKeyPress = useCallback((e) => {
    if (e.key === "Enter" && email && !loading) {
      handleSubmit(e);
    }
  }, [email, loading, handleSubmit]); // Include all dependencies

  return (
    <div className={`min-h-screen relative overflow-hidden ${getThemeClasses("bg-gradient-primary")}`}>
      {/* 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>
          <div className="flex items-center space-x-6">
            <Link
              to="/register"
              className={`text-base font-medium ${getThemeClasses("link-secondary")} transition-colors duration-200`}
            >
              Need an account?
            </Link>
            <Link
              to="/recovery"
              className={`text-base font-medium ${getThemeClasses("link-secondary")} transition-colors duration-200`}
            >
              Forgot password?
            </Link>
          </div>
        </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 */}
          <ProgressIndicator
            steps={[
              { label: "Email" },
              { label: "Verify" },
              { label: "Access" }
            ]}
            currentStep={1}
            className="mb-0"
          />

          {/* Welcome Message */}
          <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`}>
                  <ShieldCheckIcon className="h-8 w-8 text-white" />
                </div>
              </div>
            </div>
            <h1 className={`text-3xl font-bold ${getThemeClasses("text-primary")}`}>Secure Sign In</h1>
          </div>

          {/* Login Form */}
          <Card
            className={`backdrop-blur-sm ${getThemeClasses("bg-card")}/95 shadow-2xl animate-fade-in-up`}
            style={{ animationDelay: "100ms" }}
          >
            <form onSubmit={handleSubmit} className="space-y-6">
              {/* 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 && (
                      <ul className="list-disc list-inside text-sm space-y-1">
                        {Object.entries(fieldErrors).map(([field, error]) => (
                          <li key={field}>
                            <span className="font-medium capitalize">{field}:</span> {error}
                          </li>
                        ))}
                      </ul>
                    )}
                  </div>
                </Alert>
              )}

              {/* Success Message */}
              {message && (
                <Alert type="success">
                  <div>
                    <p className="text-sm">{message}</p>
                    <p className="text-sm mt-1">
                      Redirecting to verification...
                    </p>
                  </div>
                </Alert>
              )}

              {/* GDPR Notice */}
              <Alert type="info">
                <div className="text-xs">
                  <p className="font-semibold mb-1">Data Processing Notice</p>
                  <p>
                    Your email is temporarily stored in your browser to send you a login code—see our{" "}
                    <Link to="/privacy" className={`${getThemeClasses("link-primary")} underline`}>
                      Privacy Policy
                    </Link>{" "}
                    for full details.
                  </p>
                </div>
              </Alert>

              {/* Email Input - UIX Component */}
              <Input
                label="Email Address"
                type="email"
                name="email"
                placeholder="you@example.com"
                value={email}
                onChange={(value) => setEmail(value)}
                onKeyPress={handleKeyPress}
                disabled={loading}
                required
                error={fieldErrors.email}
                autoComplete="email"
                icon={ShieldCheckIcon}
                helperText="We'll send a verification code to this email address"
              />

              {/* Submit Button - UIX Component */}
              <Button
                type="submit"
                variant="primary"
                fullWidth
                disabled={loading || !authManager}
                loading={loading}
                loadingText="Sending login code..."
                className="button-swipe-effect overflow-hidden relative"
              >
                <span className="inline-flex items-center justify-center gap-2 relative z-10">
                  <span>Continue with Email</span>
                  <ArrowRightIcon className="h-5 w-5" />
                </span>
              </Button>

              <Divider text="New to MapleFile?" className="pt-2" />

              {/* Register Link */}
              <Link to="/register">
                <Button
                  type="button"
                  variant="outline"
                  fullWidth
                >
                  <span className="inline-flex items-center justify-center gap-2">
                    <span>Create an Account</span>
                    <SparklesIcon className="h-5 w-5" />
                  </span>
                </Button>
              </Link>

              {/* Help Link */}
              <div className="text-center pt-2">
                <Link
                  to="/recovery"
                  className={`text-sm ${getThemeClasses("link-primary")} font-medium hover:underline`}
                >
                  Forgot your password?
                </Link>
              </div>
            </form>
          </Card>
        </div>
      </div>

      {/* Footer */}
      <GDPRFooter containerClassName={`${getThemeClasses("bg-card")}/75`} />
    </div>
  );
};

export default RequestOTT;
