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

const AuthForm = () => {
  const [formData, setFormData] = useState({
    username: "",
    password: "",
    first_name: "",
    last_name: "",
    phone: "",
  });
  const [isLogin, setIsLogin] = useState(true);
  const [error, setError] = useState(null);
  const navigate = useNavigate();

  const API_BASE = "/api";

  const handleChange = (field) => (e) =>
    setFormData({ ...formData, [field]: e.target.value });

  const doLogin = async (username, password) => {
    const res = await axios.post(`${API_BASE}/login`, { username, password });
    const data = res.data;
    if (data.token) {
      localStorage.setItem("token", data.token);
      localStorage.setItem("user", JSON.stringify(data.user));
      localStorage.removeItem("error");
      navigate("/");
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError("");

    try {
      if (isLogin) {
        await doLogin(formData.username, formData.password);
      } else {
        await axios.post(`${API_BASE}/register`, formData);
        await doLogin(formData.username, formData.password);
      }
    } catch (err) {
      setError(
        err.response?.data?.error ||
        err.message ||
        (isLogin
          ? "Неверный логин или пароль"
          : "Не удалось зарегистрироваться"),
      );
    }
  };

  const toggleMode = () => {
    setIsLogin(!isLogin);
    setError("");
  };

  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 ? "Вход в FISH FISH" : "Регистрация в FISH FISH"}
        </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:border-blue-500 focus:outline-none sm:text-sm"
              placeholder="Логин"
              value={formData.username}
              onChange={handleChange("username")}
            />
            <input
              type="password"
              required
              className="relative block w-full rounded-b-md border border-gray-300 px-3 py-2 text-gray-900 focus:border-blue-500 focus:outline-none sm:text-sm"
              placeholder="Пароль"
              value={formData.password}
              onChange={handleChange("password")}
            />

            {!isLogin && (
              <>
                <input
                  type="text"
                  required
                  className="relative block w-full rounded-t-md border border-gray-300 px-3 py-2 text-gray-900 focus:border-blue-500 focus:outline-none sm:text-sm"
                  placeholder="Имя"
                  value={formData.first_name}
                  onChange={handleChange("first_name")}
                />
                <input
                  type="text"
                  required
                  className="relative block w-full rounded-t-md border border-gray-300 px-3 py-2 text-gray-900 focus:border-blue-500 focus:outline-none sm:text-sm"
                  placeholder="Фамилия"
                  value={formData.last_name}
                  onChange={handleChange("last_name")}
                />
                <input
                  type="text"
                  required
                  className="relative block w-full rounded-t-md border border-gray-300 px-3 py-2 text-gray-900 focus:border-blue-500 focus:outline-none sm:text-sm"
                  placeholder="Номер телефона"
                  value={formData.phone}
                  onChange={handleChange("phone")}
                />
              </>
            )}
          </div>

          {error && <p className="text-center text-sm text-red-600">{error}</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"
          >
            {isLogin ? "Войти" : "Зарегистрироваться"}
          </button>

          <p className="text-center text-sm text-gray-600">
            {isLogin ? "Нет аккаунта?" : "Уже есть аккаунт?"}{" "}
            <span
              className="cursor-pointer text-blue-600 hover:underline"
              onClick={toggleMode}
            >
              {isLogin ? "Зарегистрироваться" : "Войти"}
            </span>
          </p>
        </form>
      </div>
    </div>
  );
};

export default AuthForm;
