// 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, NavBar, AuthPageHeader } from "../../../components/UIX";
import { useUIXTheme } from "../../../components/UIX/themes/useUIXTheme";
import {
  ArrowRightIcon,
  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">
        <NavBar
          links={[
            { to: "/register", label: "Need an account?" },
            { to: "/recovery", label: "Forgot password?" }
          ]}
          transparent
        />
      </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 */}
          <AuthPageHeader
            title="Secure Sign In"
            icon={ShieldCheckIcon}
          />

          {/* 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;
