import { useContext, useState } from "react";
import api from "../services/api";
import { useNavigate } from "react-router-dom";
import "../styles/Login.css";
import { AuthContext } from "../context/AuthContext";

export default function Login() {
  const { login } = useContext(AuthContext);
  const [form, setForm] = useState({ user: "", password: "" });
  const [isModal, setShowModal] = useState(false);
  const [recoverEmail, setRecoverEmail] = useState("");
  const [error, setError] = useState("");
  const navigate = useNavigate();

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      const response = await api.post("/auth/login", {
        name_mail_user: form.user,
        user_pass: form.password,
      });
      if (response.data.rol != 0) {
        login(response.data.rol, response.data);
        navigate("/app");
      } else {
        throw new Error(response.data.message || "Error al iniciar sesión");
      }
    } catch (error) {
      const errorMsg = error
        ? "Usuario o contraseña incorrecto"
        : "Error al iniciar sesión";
      setError(errorMsg);
    }

    // try {
    //   const response = await api.post("/auth/login", {
    //     name_mail_user: form.user,
    //     user_pass: form.password,
    //   });

    //   console.log("✅ Login exitoso", response.data);
    //   setMensaje(response.data.message);
    //   setError("");
    //   navigate("/app/income");

    // } catch (err) {
    //   const errorMsg = err.response?.data?.error || "Error al iniciar sesión";
    //   console.error("❌ Error:", errorMsg);
    //   setError(errorMsg);
    //   setMensaje("");
    // }
  };

  const handleRecoverPass = async () => {
    try {
      await api.post("/auth/recoverpass", {
        user_mail: recoverEmail,
      });
      alert(`Se envió un enlace de recuperación a: ${recoverEmail}`);
      setShowModal(false);
      setRecoverEmail("");
    } catch (err) {
      const errorMsg = err.response?.data?.error || "Error al iniciar sesión";
      console.error("❌ Error:", errorMsg);
      setError(errorMsg);
    }
  };

  const handleRecover = (e) => {
    e.preventDefault();
    handleRecoverPass();
  };

  return (
    <div className="flex h-screen items-center justify-center">
      <div className="login-page">
        <div className="login-container">
          {/* Logo a la izquierda */}
          <div className="logo-box">
            <img src="/logoHotel.png" alt="Logo" className="logo" />
          </div>
          <div className="login-form">
            <div className="button-group">
              <form onSubmit={handleSubmit} className="login-form">
                <input
                  type="text"
                  name="user"
                  placeholder="Email/User"
                  value={form.user}
                  onChange={(e) => {
                    setForm({ ...form, user: e.target.value });
                    if (error) setError("");
                  }}
                  className="custom-input"
                  required
                />

                <input
                  type="password"
                  name="password"
                  placeholder="Password"
                  value={form.password}
                  onChange={(e) => {
                    setForm({ ...form, password: e.target.value });
                    if (error) setError("");
                  }}
                  className="custom-input"
                  required
                />

                {error && (
                  <div
                    style={{
                      color: "red",
                      fontSize: "14px",
                      fontWeight: "700",
                      textAlign: "center",
                      marginBottom: "5px",
                    }}
                  >
                    {error}
                  </div>
                )}

                <div className="login-buttons">
                  <button type="submit" className="btn btn-primary">
                    Log In
                  </button>
                  <button
                    type="button"
                    className="btn btn-secondary"
                    onClick={() => setShowModal(true)}
                  >
                    Recover Password
                  </button>
                </div>
              </form>
            </div>
          </div>

          {/* Modal */}
          {isModal && (
            <div className="modal-overlay">
              <div className="modal-box">
                <h3 className="modal-title">Recover Password</h3>
                <form onSubmit={handleRecover} className="modal-form">
                  <input
                    type="email"
                    placeholder="Enter your email..."
                    value={recoverEmail}
                    onChange={(e) => setRecoverEmail(e.target.value)}
                    required
                    className="recover-input"
                  />
                  <div className="modal-actions">
                    <button type="submit" className="btn btn-primary">
                      Send email
                    </button>
                    <button
                      type="button"
                      className="btn btn-secondary"
                      onClick={() => setShowModal(false)}
                    >
                      Cancel
                    </button>
                  </div>
                </form>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
