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

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 googleButtonRef = useRef<HTMLDivElement>(null);

  const { login, register, googleLogin, updateUser } = useAuth();

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

  // Initialize Google Sign-In
  useEffect(() => {
    if (show && window.google && process.env.REACT_APP_GOOGLE_CLIENT_ID) {
      try {
        window.google.accounts.id.initialize({
          client_id: process.env.REACT_APP_GOOGLE_CLIENT_ID,
          callback: handleGoogleResponse,
          auto_select: false,
          cancel_on_tap_outside: false,
        });
      } catch (error) {
        console.error("Error initializing Google Sign-In:", error);
      }
    }
  }, [show]);

  const handleGoogleResponse = async (response: any) => {
    try {
      setLoading(true);
      setError("");

      if (!response?.credential) {
        throw new Error("No credential received from Google");
      }

      await googleLogin(response.credential);
      onHide();
      resetModal();
    } catch (err: any) {
      setError(
        err.response?.data?.error ||
          err.message ||
          "Failed to sign in with Google"
      );
    } finally {
      setLoading(false);
    }
  };

  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);
    }
  };

  const handleSocialLogin = (provider: string) => {
    if (provider === "google") {
      if (window.google) {
        try {
          window.google.accounts.id.prompt();
        } catch (error) {
          setError("Failed to open Google Sign-In. Please try again.");
        }
      } else {
        setError("Google Sign-In is not available. Please try again later.");
      }
    }
  };

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

  if (!show) return null;

  return (
    <>
      <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>

                <div className="mb-3">
                  <label className="form-label">Password</label>
                  <input
                    type="password"
                    className="form-control"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    required
                  />
                  {mode === "signup" && (
                    <PasswordStrengthMeter password={password} />
                  )}
                </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={() => handleSocialLogin("google")}
                disabled={loading}
              >
                <i className="bi bi-google me-2"></i>
                Sign in 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>
    </>
  );
};

export default AuthModal;
