import { useState } from "react";
import axios from "axios";
import bgFish from "../assets/Исходники/background.jpg";
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("");
  };

  // общий класс для всех полей ввода — фирменный стиль
  const inputClass =
    "block w-full rounded-md bg-white/5 border border-white/10 px-4 py-3 text-white placeholder-white/40 focus:border-gold focus:outline-none transition-colors";

  return (
    <div className="relative flex min-h-screen items-center justify-center px-4 overflow-hidden">
      <div
        className="absolute inset-0 bg-cover bg-center"
        style={{ backgroundImage: `url(${bgFish})` }}
      />
      <div className="absolute inset-0 bg-slate-900/75" />
      <div className="relative w-full max-w-md space-y-6 rounded-lg bg-slate-800/60 border border-slate-700/50 p-8 md:p-10">
        <h2 className="text-center text-2xl md:text-3xl font-medium uppercase text-white">
          {isLogin ? "Вход" : "Регистрация"}
        </h2>

        <form className="space-y-4" onSubmit={handleSubmit}>
          <input
            type="text"
            required
            className={inputClass}
            placeholder="Логин"
            value={formData.username}
            onChange={handleChange("username")}
          />
          <input
            type="password"
            required
            className={inputClass}
            placeholder="Пароль"
            value={formData.password}
            onChange={handleChange("password")}
          />

          {!isLogin && (
            <>
              <input
                type="text"
                required
                className={inputClass}
                placeholder="Имя"
                value={formData.first_name}
                onChange={handleChange("first_name")}
              />
              <input
                type="text"
                required
                className={inputClass}
                placeholder="Фамилия"
                value={formData.last_name}
                onChange={handleChange("last_name")}
              />
              <input
                type="text"
                required
                className={inputClass}
                placeholder="Номер телефона"
                value={formData.phone}
                onChange={handleChange("phone")}
              />
            </>
          )}

          {error && <p className="text-center text-sm text-red-400">{error}</p>}

          <button
            type="submit"
            className="w-full rounded-md bg-gold text-black px-4 py-3 text-sm font-medium uppercase tracking-wide hover:opacity-90 transition-opacity"
          >
            {isLogin ? "Войти" : "Зарегистрироваться"}
          </button>

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

export default AuthForm;
