import { useState, useEffect } from "react";
import styles from "./Auth.module.css";
import { ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

export const Auth = ({
  LoginComponent,
  SignUpComponent,
  onLoginSubmit,
  onSignUpSubmit,
  loginLabel = "Login Form",
  signupLabel = "SignUp Form",
  loginTabLabel = "Login",
  signupTabLabel = "Signup",
  initialMode = "login",
  showForgotPassword = true,
  showSwitchPrompt = true,
}) => {
  const [isLoginMode, setIsLoginMode] = useState(initialMode === "login");

  useEffect(() => {
    setIsLoginMode(initialMode === "login");
  }, [initialMode]);

  return (
    <div className={styles.container}>
      <div className={styles.formCard}>
        <h2 className={styles.header}>
          {isLoginMode ? loginLabel : signupLabel}
        </h2>

        <div className={styles.tabContainer}>
          <button
            className={`${styles.tabButton} ${isLoginMode ? styles.activeTab : ""}`}
            onClick={() => setIsLoginMode(true)}
          >
            {loginTabLabel}
          </button>
          <button
            className={`${styles.tabButton} ${!isLoginMode ? styles.activeTab : ""}`}
            onClick={() => setIsLoginMode(false)}
          >
            {signupTabLabel}
          </button>
        </div>

        {isLoginMode ? (
          <div className={styles.login}>
            <LoginComponent onLogin={onLoginSubmit} />
            {showForgotPassword && (
              <a href="#" className={styles.forgotLink}>Forgot password?</a>
            )}
          </div>
        ) : (
          <div className={styles.signup}>
            <SignUpComponent
              onSignUpSubmit={async (formData) => {
                if (onSignUpSubmit) {
                  await onSignUpSubmit(formData);
                  setIsLoginMode(true);
                }
              }}
            />
          </div>
        )}

        {showSwitchPrompt && (
          <div className={styles.signupPrompt}>
            {isLoginMode ? "Not a member?" : "Already a member?"}{" "}
            <a href="#" onClick={() => setIsLoginMode(!isLoginMode)}>
              {isLoginMode ? "Signup now" : "Login"}
            </a>
          </div>
        )}
      </div>

      <ToastContainer position="top-right" autoClose={3000} />
    </div>
  );
};
