import React, { useState, useEffect, useRef, useCallback } from "react";
import { useAuth } from "../contexts/AuthContext";
import PasswordStrengthMeter from "./PasswordStrengthMeter";
import PasswordInput from "./PasswordInput";
import ForgotPasswordModal from "./ForgotPasswordModal";
import VerificationCodeModal from "./VerificationCodeModal";

interface AuthModalProps {
  show: boolean;
  onHide: () => void;
  initialMode?: "login" | "signup" | "forgot-password";
}

const AuthModal: React.FC<AuthModalProps> = ({
  show,
  onHide,
  initialMode = "login",
}) => {
  const [mode, setMode] = useState<"login" | "signup">(initialMode === "forgot-password" ? "login" : initialMode);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [showForgotPassword, setShowForgotPassword] = useState(initialMode === "forgot-password");
  const [showVerificationModal, setShowVerificationModal] = useState(false);

  const { login, register } = useAuth();
  const modalRef = useRef<HTMLDivElement>(null);

  // Update mode when modal is opened with different initialMode
  useEffect(() => {
    if (show && initialMode) {
      if (initialMode === "forgot-password") {
        setShowForgotPassword(true);
        setMode("login"); // Default to login when returning from forgot password
      } else {
        setMode(initialMode);
        setShowForgotPassword(false);
      }
    }
  }, [show, initialMode]);

  // Focus trapping for accessibility
  const handleKeyDown = useCallback((e: KeyboardEvent) => {
    if (e.key !== "Tab" || !modalRef.current) return;

    const focusableElements = modalRef.current.querySelectorAll<HTMLElement>(
      'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
    );
    const focusableArray = Array.from(focusableElements).filter(
      (el) => !el.hasAttribute("disabled") && el.offsetParent !== null
    );

    if (focusableArray.length === 0) return;

    const firstElement = focusableArray[0];
    const lastElement = focusableArray[focusableArray.length - 1];

    if (e.shiftKey) {
      // Shift + Tab: if on first element, go to last
      if (document.activeElement === firstElement) {
        e.preventDefault();
        lastElement.focus();
      }
    } else {
      // Tab: if on last element, go to first
      if (document.activeElement === lastElement) {
        e.preventDefault();
        firstElement.focus();
      }
    }
  }, []);

  // Set up focus trap and initial focus when modal is shown
  useEffect(() => {
    if (show && !showForgotPassword && !showVerificationModal) {
      document.addEventListener("keydown", handleKeyDown);

      // Focus the first input element when modal opens
      if (modalRef.current) {
        const firstInput = modalRef.current.querySelector<HTMLElement>("input");
        firstInput?.focus();
      }

      return () => {
        document.removeEventListener("keydown", handleKeyDown);
      };
    }
  }, [show, showForgotPassword, showVerificationModal, handleKeyDown]);

  const resetModal = () => {
    setError("");
    setEmail("");
    setPassword("");
    setFirstName("");
    setLastName("");
    setShowVerificationModal(false);
  };

  const handleGoogleLogin = () => {
    const clientId = process.env.REACT_APP_GOOGLE_CLIENT_ID;
    const redirectUri = `${window.location.origin}/auth/google/callback`;
    const scope = "openid email profile";
    const responseType = "code";

    const googleAuthUrl =
      `https://accounts.google.com/o/oauth2/v2/auth?` +
      `client_id=${encodeURIComponent(clientId || "")}` +
      `&redirect_uri=${encodeURIComponent(redirectUri)}` +
      `&response_type=${responseType}` +
      `&scope=${encodeURIComponent(scope)}` +
      `&access_type=offline` +
      `&prompt=consent`;

    window.location.href = googleAuthUrl;
  };

  const handleEmailSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");

    // Custom validation to match app's error styling
    if (mode === "signup") {
      if (!firstName.trim()) {
        setError("Please enter your first name");
        return;
      }
      if (!lastName.trim()) {
        setError("Please enter your last name");
        return;
      }
    }

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!email.trim()) {
      setError("Please enter your email address");
      return;
    }
    if (!emailRegex.test(email)) {
      setError("Please enter a valid email address");
      return;
    }

    setLoading(true);

    try {
      if (mode === "login") {
        await login(email, password);
        onHide();
      } else {
        const response = await register({
          email,
          password,
          firstName,
          lastName,
          username: email.split("@")[0], // Generate username from email
        });
        // Show verification modal after successful registration
        setShowVerificationModal(true);
        // Don't call onHide() - keep modal context for verification
      }
    } catch (err: any) {
      // Show first specific validation error if available, otherwise generic error
      const details = err.response?.data?.details;
      const specificError = details?.[0]?.message;
      setError(
        specificError || err.response?.data?.error || "An error occurred"
      );
    } finally {
      setLoading(false);
    }
  };

  if (!show && !showForgotPassword && !showVerificationModal) return null;

  return (
    <>
      {/* Verification Code Modal - shown after signup */}
      {showVerificationModal && (
        <VerificationCodeModal
          show={showVerificationModal}
          onHide={() => {
            setShowVerificationModal(false);
            resetModal();
            onHide();
          }}
          email={email}
          onVerified={() => {
            setShowVerificationModal(false);
            resetModal();
            onHide();
          }}
        />
      )}

      {!showForgotPassword && !showVerificationModal && (
        <div
          className="modal show d-block"
          tabIndex={-1}
          style={{ backgroundColor: "rgba(0,0,0,0.5)" }}
        >
          <div className="modal-dialog modal-dialog-centered">
            <div className="modal-content" ref={modalRef}>
              <div className="modal-header border-0 pb-0">
                <button
                  type="button"
                  className="btn-close"
                  onClick={() => {
                    resetModal();
                    onHide();
                  }}
                ></button>
              </div>
              <div className="modal-body px-4 pb-4">
                <h4 className="text-center mb-2">Welcome to Village Share</h4>

                {error && (
                  <div className="alert alert-danger" role="alert">
                    {error}
                  </div>
                )}

                {/* Email Form */}
                <form onSubmit={handleEmailSubmit}>
                  {mode === "signup" && (
                    <>
                      <div className="row mb-3">
                        <div className="col">
                          <label className="form-label">First Name</label>
                          <input
                            type="text"
                            className="form-control"
                            value={firstName}
                            onChange={(e) => setFirstName(e.target.value)}
                          />
                        </div>
                        <div className="col">
                          <label className="form-label">Last Name</label>
                          <input
                            type="text"
                            className="form-control"
                            value={lastName}
                            onChange={(e) => setLastName(e.target.value)}
                          />
                        </div>
                      </div>
                    </>
                  )}

                  <div className="mb-3">
                    <label className="form-label">Email</label>
                    <input
                      type="text"
                      className="form-control"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      autoComplete="email"
                    />
                  </div>

                  <PasswordInput
                    id="password"
                    label="Password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    required
                  />
                  {mode === "signup" && (
                    <div
                      style={{ marginTop: "-0.75rem", marginBottom: "1rem" }}
                    >
                      <PasswordStrengthMeter password={password} />
                    </div>
                  )}

                  {mode === "login" && (
                    <div
                      className="text-end mb-3"
                      style={{ marginTop: "-0.5rem" }}
                    >
                      <a
                        href="#"
                        className="text-primary text-decoration-none small"
                        onClick={(e) => {
                          e.preventDefault();
                          setShowForgotPassword(true);
                        }}
                      >
                        Forgot password?
                      </a>
                    </div>
                  )}

                  <button
                    type="submit"
                    className="btn btn-primary w-100 py-3 mb-1"
                    disabled={loading}
                  >
                    {loading
                      ? "Loading..."
                      : mode === "login"
                      ? "Log in"
                      : "Sign up"}
                  </button>
                </form>

                <div className="d-flex align-items-center my-3">
                  <hr className="flex-grow-1" />
                  <span className="px-3 text-muted">or</span>
                  <hr className="flex-grow-1" />
                </div>

                {/* Social Login Options */}
                <button
                  className="btn btn-outline-dark w-100 mb-2 py-3 d-flex align-items-center justify-content-center"
                  onClick={handleGoogleLogin}
                  disabled={loading}
                  type="button"
                >
                  <i className="bi bi-google me-2"></i>
                  Continue with Google
                </button>

                <div className="text-center mt-3">
                  <small className="text-muted">
                    {mode === "login"
                      ? "Don't have an account? "
                      : "Already have an account? "}
                    <a
                      href="#"
                      className="text-primary text-decoration-none"
                      onClick={(e) => {
                        e.preventDefault();
                        setError("");
                        setMode(mode === "login" ? "signup" : "login");
                      }}
                    >
                      {mode === "login" ? "Sign up" : "Log in"}
                    </a>
                  </small>
                </div>

                <p className="text-center text-muted small mt-4 mb-0">
                  By continuing, you agree to Village Share's{" "}
                  <a href="/terms" className="text-decoration-none">
                    Terms of Service
                  </a>{" "}
                  and{" "}
                  <a href="/privacy" className="text-decoration-none">
                    Privacy Policy
                  </a>
                  .
                </p>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Forgot Password Modal */}
      <ForgotPasswordModal
        show={showForgotPassword}
        onHide={() => setShowForgotPassword(false)}
        onBackToLogin={() => setShowForgotPassword(false)}
      />
    </>
  );
};

export default AuthModal;
