import { useState } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";

const AuthForm = () => {
  const [isLogin, setIsLogin] = useState(true);
  const [formData, setFormData] = useState({ username: "", password: "" });
  const [message, setMessage] = useState({ text: "", isError: false });
  const navigate = useNavigate();

  const API_BASE = "";

  const handleSubmit = async (e) => {
    e.preventDefault();
    setMessage({ text: "", isError: false });

    const endpoint = isLogin ? "/login" : "/register";

    try {
      const { data } = await axios.post(`${API_BASE}${endpoint}`, formData);

      if (isLogin) {
        localStorage.setItem("token", data.token);
        navigate("/");
      } else {
        setMessage({
          text: "Регистрация успешна! Теперь войдите",
          isError: false,
        });
        setIsLogin(true);
      }
    } catch (err) {
      setMessage({
        text: err.response?.data?.error || "Ошибка сервера",
        isError: true,
      });
    }
  };

  return (
    <div className="flex min-h-screen items-center justify-center bg-gray-100 px-4">
      <div className="w-full max-w-md space-y-8 rounded-lg bg-white p-10 shadow-md">
        <h2 className="text-center text-3xl font-bold text-gray-900">
          {isLogin ? "Вход в MRP" : "Регистрация"}
        </h2>

        <form className="mt-8 space-y-6" onSubmit={handleSubmit}>
          <div className="rounded-md shadow-sm -space-y-px">
            <input
              type="text"
              required
              className="relative block w-full rounded-t-md border border-gray-300 px-3 py-2 text-gray-900 focus:z-10 focus:border-blue-500 focus:outline-none sm:text-sm"
              placeholder="Логин"
              onChange={(e) =>
                setFormData({ ...formData, username: e.target.value })
              }
            />
            <input
              type="password"
              required
              className="relative block w-full rounded-b-md border border-gray-300 px-3 py-2 text-gray-900 focus:z-10 focus:border-blue-500 focus:outline-none sm:text-sm"
              placeholder="Пароль"
              onChange={(e) =>
                setFormData({ ...formData, password: e.target.value })
              }
            />
          </div>

          {message.text && (
            <p
              className={`text-sm ${message.isError ? "text-red-500" : "text-green-500"}`}
            >
              {message.text}
            </p>
          )}

          <button
            type="submit"
            className="group relative flex w-full justify-center rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 focus:outline-none"
          >
            {isLogin ? "Войти" : "Зарегистрироваться"}
          </button>
        </form>

        <div className="text-center">
          <button
            onClick={() => setIsLogin(!isLogin)}
            className="text-sm text-blue-600 hover:text-blue-500"
          >
            {isLogin ? "Нет аккаунта? Создать" : "Уже есть аккаунт? Войти"}
          </button>
        </div>
      </div>
    </div>
  );
};

export default AuthForm;
