// File: monorepo/web/maplefile-frontend/src/pages/Anonymous/Register/VerifyEmail.jsx
// UIX version - Email Verification (100% UIX Components)
import { useState, useEffect, useCallback, useMemo, useRef } from "react";
import { useNavigate } from "react-router";
import { useServices } from "../../../services/Services";
import {
  Card,
  Button,
  Input,
  Alert,
  GDPRFooter,
  Navigation,
  PageContainer,
  PageHeader,
  ProgressIndicator,
  InfoBox,
} from "../../../components/UIX";
import { useUIXTheme } from "../../../components/UIX/themes/useUIXTheme";
import {
  ArrowRightIcon,
  ArrowLeftIcon,
  LockClosedIcon,
  CheckIcon,
  InformationCircleIcon,
  EnvelopeIcon,
  ClockIcon,
  ArrowPathIcon,
} from "@heroicons/react/24/outline";

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

  // Refs for cleanup
  const isMountedRef = useRef(true);
  const timerRef = useRef(null);
  const resendTimeoutRef = useRef(null);
  const resendCooldownRef = useRef(null);

  const [email, setEmail] = useState("");
  const [verificationCode, setVerificationCode] = useState("");
  const [loading, setLoading] = useState(false);
  const [generalError, setGeneralError] = useState("");
  const [fieldErrors, setFieldErrors] = useState({});
  const [resendLoading, setResendLoading] = useState(false);
  const [resendSuccess, setResendSuccess] = useState(false);
  const [timeRemaining, setTimeRemaining] = useState(4320); // 72 hours in minutes
  const [canResend, setCanResend] = useState(true);
  const [resendCooldown, setResendCooldown] = useState(0);

  useEffect(() => {
    isMountedRef.current = true;

    // Get email from sessionStorage
    const registeredEmail = sessionStorage.getItem("registeredEmail");

    if (!registeredEmail) {
      // Redirect back to registration if no email found
      if (import.meta.env.DEV) {
        console.log("[VerifyEmail] No email found, redirecting to register");
      }
      navigate("/register");
      return;
    }

    // Validate email format to prevent XSS/tampering
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(registeredEmail)) {
      if (import.meta.env.DEV) {
        console.error("[VerifyEmail] Invalid email format in sessionStorage");
      }
      sessionStorage.removeItem("registeredEmail");
      navigate("/register");
      return;
    }

    if (isMountedRef.current) {
      setEmail(registeredEmail);
    }

    return () => {
      isMountedRef.current = false;
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
      if (resendTimeoutRef.current) {
        clearTimeout(resendTimeoutRef.current);
      }
      if (resendCooldownRef.current) {
        clearInterval(resendCooldownRef.current);
      }
    };
  }, [navigate]);

  // Countdown timer effect (simplified for 72 hours)
  useEffect(() => {
    timerRef.current = setInterval(() => {
      setTimeRemaining((prev) => {
        if (prev <= 0) return 0;
        return prev - 1;
      });
    }, 60000); // Update every minute

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

  // Format time as hours
  const formatTime = useCallback((minutes) => {
    const hours = Math.floor(minutes / 60);
    const remainingMinutes = minutes % 60;
    if (hours > 24) {
      const days = Math.floor(hours / 24);
      const remainingHours = hours % 24;
      return `${days} day${days > 1 ? "s" : ""}, ${remainingHours} hour${remainingHours !== 1 ? "s" : ""}`;
    }
    return `${hours} hour${hours !== 1 ? "s" : ""}, ${remainingMinutes} minute${remainingMinutes !== 1 ? "s" : ""}`;
  }, []);

  const handleInputChange = useCallback((value) => {
    const sanitized = value.replace(/\D/g, ""); // Only allow digits
    if (sanitized.length <= 8) {
      setVerificationCode(sanitized);
      // Clear errors when user types - use functional updates to avoid unnecessary re-renders
      setGeneralError((prev) => prev ? "" : prev);
      setFieldErrors((prev) => {
        if (prev.code) {
          return { ...prev, code: "" };
        }
        return prev;
      });
    }
  }, []);

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

    if (verificationCode.length !== 8) {
      setFieldErrors({ code: "Please enter an 8-digit verification code" });
      return;
    }

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

    try {
      if (import.meta.env.DEV) {
        console.log("[VerifyEmail] Verifying email with code");
      }
      const result = await authManager.verifyEmail(verificationCode);

      if (import.meta.env.DEV) {
        console.log("[VerifyEmail] Email verification successful");
      }

      // Store user role for success page
      sessionStorage.setItem("userRole", result.user_role.toString());

      // Navigate to success page
      navigate("/register/verify-success");
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("[VerifyEmail] Email verification failed:", error);
      }

      // Handle RFC 9457 errors with field-specific validation
      if (error.fieldErrors && Object.keys(error.fieldErrors).length > 0) {
        setFieldErrors(error.fieldErrors);
      }

      if (error.message) {
        setGeneralError(error.message);
      }
    } finally {
      if (isMountedRef.current) {
        setLoading(false);
      }
    }
  }, [verificationCode, authManager, navigate]);

  const handleResendCode = useCallback(async () => {
    if (!canResend) {
      return;
    }

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

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

      // Call the actual backend API endpoint
      const response = await authManager.apiService.makeRequest("/resend-verification", {
        method: "POST",
        body: JSON.stringify({ email }),
      });

      if (import.meta.env.DEV) {
        console.log("[VerifyEmail] Resend verification successful");
      }

      if (isMountedRef.current) {
        setResendSuccess(true);
        setVerificationCode(""); // Clear the current code

        // Clear success message after 5 seconds
        resendTimeoutRef.current = setTimeout(() => {
          if (isMountedRef.current) {
            setResendSuccess(false);
          }
        }, 5000);

        // Start 60-second cooldown timer
        let countdown = 60;
        resendCooldownRef.current = setInterval(() => {
          countdown--;
          if (isMountedRef.current) {
            setResendCooldown(countdown);
            if (countdown <= 0) {
              setCanResend(true);
              if (resendCooldownRef.current) {
                clearInterval(resendCooldownRef.current);
                resendCooldownRef.current = null;
              }
            }
          } else {
            if (resendCooldownRef.current) {
              clearInterval(resendCooldownRef.current);
              resendCooldownRef.current = null;
            }
          }
        }, 1000);
      }
    } catch (err) {
      if (import.meta.env.DEV) {
        console.error("[VerifyEmail] Resend verification failed:", err);
      }

      // On error, allow immediate retry
      if (isMountedRef.current) {
        setCanResend(true);
        setResendCooldown(0);
      }

      // Handle RFC 9457 errors
      if (err.fieldErrors && Object.keys(err.fieldErrors).length > 0) {
        setFieldErrors(err.fieldErrors);
      }

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

  const handleBackToRecovery = useCallback(() => {
    navigate("/register/recovery");
  }, [navigate]);

  const handleBackToRegistration = useCallback(() => {
    // Clear session storage
    sessionStorage.removeItem("registrationResult");
    sessionStorage.removeItem("registeredEmail");
    navigate("/register");
  }, [navigate]);

  // Memoize expiry status message
  const expiryMessage = useMemo(() => {
    if (timeRemaining <= 0) return "Code has expired";
    return `Code expires in ${formatTime(timeRemaining)}`;
  }, [timeRemaining, formatTime]);

  const isExpired = useMemo(() => timeRemaining <= 0, [timeRemaining]);

  // Memoize progress steps
  const progressSteps = useMemo(
    () => [
      { label: "Register", completed: true },
      { label: "Recovery", completed: true },
      { label: "Verify", completed: false },
    ],
    [],
  );

  // Memoize navigation links
  const navLinks = useMemo(
    () => [{ to: "/login", text: "Step 3 of 3", variant: "secondary" }],
    [],
  );

  if (!email) {
    return (
      <PageContainer>
        <Card className="text-center p-8 max-w-md mx-auto mt-20">
          <h2 className={`text-2xl font-bold ${getThemeClasses("text-primary")} mb-4`}>
            Loading...
          </h2>
          <p className={getThemeClasses("text-secondary")}>
            Loading verification page...
          </p>
        </Card>
      </PageContainer>
    );
  }

  return (
    <PageContainer showBlobs>
      {/* Navigation */}
      <Navigation icon={LockClosedIcon} logoText="MapleFile" links={navLinks} />

      {/* Main Content */}
      <div className="flex-1 flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8 relative z-10">
        <div className="max-w-md w-full space-y-8">
          {/* Progress Indicator */}
          <ProgressIndicator steps={progressSteps} currentStep={3} />

          {/* Page Header */}
          <PageHeader
            icon={EnvelopeIcon}
            title="Verify Your Email"
            subtitle="Enter the 8-digit code sent to your email"
            className="text-center"
            iconClassName="animate-pulse"
          />

          {/* Expiry Warning */}
          <div className={`flex items-center justify-center space-x-2 text-sm ${getThemeClasses("text-secondary")}`}>
            <ClockIcon className={`h-4 w-4 ${getThemeClasses("icon-warning")}`} />
            <span className={isExpired ? getThemeClasses("text-error") + " font-semibold" : ""}>
              {expiryMessage}
            </span>
          </div>

          {/* Form Card */}
          <Card className="shadow-2xl animate-fade-in-up-delay">
            {/* Error Message Box - only show after form submission attempt */}
            {generalError && (
              <Alert type="error" className="mb-6">
                <div>
                  <h3 className="text-base font-bold mb-2">
                    Verification Failed
                  </h3>
                  <p className="text-sm">{generalError}</p>
                </div>
              </Alert>
            )}

            {/* Resend Success Message */}
            {resendSuccess && (
              <Alert type="success" className="mb-6">
                <div>
                  <h3 className="text-sm font-semibold">
                    Code Resent Successfully
                  </h3>
                  <p className="text-sm mt-1">
                    A new verification code has been sent to your email.
                  </p>
                </div>
              </Alert>
            )}

            {/* Email Display */}
            <div className="mb-6">
              <InfoBox
                icon={EnvelopeIcon}
                label="Verification email sent to:"
                value={email}
              />
            </div>

            {/* Form */}
            <form onSubmit={handleSubmit} className="space-y-6">
              <Input
                label="Verification Code"
                type="text"
                name="verification_code"
                value={verificationCode}
                onChange={handleInputChange}
                placeholder="00000000"
                maxLength={8}
                required
                disabled={loading}
                error={fieldErrors.code}
                className="text-center text-2xl font-mono tracking-widest"
                helperText="Check your email inbox and spam folder"
              />

              <div className="space-y-3">
                <Button
                  type="submit"
                  disabled={loading || verificationCode.length !== 8 || isExpired}
                  variant="primary"
                  fullWidth
                  loading={loading}
                  loadingText="Verifying..."
                  className="whitespace-nowrap"
                >
                  {isExpired ? (
                    "Code Expired - Resend Required"
                  ) : (
                    <>
                      <CheckIcon className="mr-2 h-4 w-4 inline-block" />
                      <span className="inline-block">Submit</span>
                    </>
                  )}
                </Button>

                <div className="flex space-x-3">
                  <Button
                    type="button"
                    onClick={handleResendCode}
                    disabled={resendLoading || !canResend}
                    variant="secondary"
                    fullWidth
                    loading={resendLoading}
                    loadingText="Sending..."
                    className="whitespace-nowrap"
                  >
                    <ArrowPathIcon className="mr-2 h-4 w-4 inline-block" />
                    <span className="inline-block">{canResend ? "Resend Code" : `Resend (${resendCooldown}s)`}</span>
                  </Button>

                  <Button
                    type="button"
                    onClick={handleBackToRecovery}
                    disabled={loading}
                    variant="secondary"
                    fullWidth
                    className="whitespace-nowrap"
                  >
                    <ArrowLeftIcon className="mr-2 h-4 w-4 inline-block" />
                    <span className="inline-block">Back to Recovery</span>
                  </Button>
                </div>
              </div>
            </form>

            {/* Start Over Link */}
            <div className="mt-6 text-center">
              <Button
                onClick={handleBackToRegistration}
                variant="ghost"
                size="sm"
                className={`${getThemeClasses("link-primary")} hover:underline px-2 py-1`}
              >
                Start registration over
              </Button>
            </div>
          </Card>

          {/* Help Section */}
          <Alert type="info" className="animate-fade-in-up-delay-2">
            <div>
              <h3 className="text-sm font-semibold mb-3">
                Having trouble?
              </h3>
              <ul className="text-sm space-y-2">
                <li className="flex items-start">
                  <span className="mr-2 mt-0.5">•</span>
                  Check your spam/junk folder for the email
                </li>
                <li className="flex items-start">
                  <span className="mr-2 mt-0.5">•</span>
                  Make sure you're checking {email}
                </li>
                <li className="flex items-start">
                  <span className="mr-2 mt-0.5">•</span>
                  The verification code expires after 72 hours
                </li>
                <li className="flex items-start">
                  <span className="mr-2 mt-0.5">•</span>
                  Click "Resend Code" to get a new verification email
                </li>
              </ul>
            </div>
          </Alert>
        </div>
      </div>

      {/* Footer */}
      <GDPRFooter />

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

        .animate-fade-in-up-delay {
          animation: fade-in-up 0.6s ease-out 0.2s both;
        }

        .animate-fade-in-up-delay-2 {
          animation: fade-in-up 0.6s ease-out 0.4s both;
        }
      `}</style>
    </PageContainer>
  );
};

export default VerifyEmail;
