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

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

const AuthModal: React.FC<AuthModalProps> = ({
  show,
  onHide,
  initialMode = "login",
}) => {
  const [mode, setMode] = useState<"login" | "signup">(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(false);

  const { login, register } = useAuth();

  // Update mode when modal is opened with different initialMode
  useEffect(() => {
    if (show && initialMode) {
      setMode(initialMode);
    }
  }, [show, initialMode]);

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

  const handleGoogleLogin = () => {
    const clientId = process.env.REACT_APP_GOOGLE_CLIENT_ID;
    const redirectUri = `${window.location.origin}/auth/google/callback`;
    const scope = '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();
    setLoading(true);
    setError("");

    try {
      if (mode === "login") {
        await login(email, password);
        onHide();
      } else {
        await register({
          email,
          password,
          firstName,
          lastName,
          username: email.split("@")[0], // Generate username from email
        });
        onHide();
      }
    } catch (err: any) {
      setError(err.response?.data?.message || "An error occurred");
    } finally {
      setLoading(false);
    }
  };


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

  return (
    <>
      {!showForgotPassword && (
        <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">
            <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 CommunityRentals.App
              </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)}
                          required
                        />
                      </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)}
                          required
                        />
                      </div>
                    </div>
                  </>
                )}

                <div className="mb-3">
                  <label className="form-label">Email</label>
                  <input
                    type="email"
                    className="form-control"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    required
                  />
                </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();
                      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 CommunityRentals.App'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;
