import { useState } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import { toast } from "sonner";
import { Loader2 } from "lucide-react";

const API = `${process.env.REACT_APP_BACKEND_URL}/api`;

export default function UserAuth() {
  const navigate = useNavigate();
  const [mode, setMode] = useState("login");
  const [loading, setLoading] = useState(false);
  const [form, setForm] = useState({ name: "", email: "", password: "", phone: "" });
  const update = (f) => (e) => setForm({ ...form, [f]: e.target.value });
  const inputCls = "w-full h-11 px-4 bg-[#1E1E1E] border border-[#2A2A2A] rounded-sm text-[14px] text-white placeholder:text-[#666] focus:outline-none focus:border-[#3B82F6] transition-colors";

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    try {
      if (mode === "register") {
        if (!form.name || !form.email || !form.password) { toast.error("All fields required"); setLoading(false); return; }
        const { data } = await axios.post(`${API}/user/register`, form);
        localStorage.setItem("user_token", data.token);
        localStorage.setItem("user_name", data.user?.name || form.name);
        localStorage.setItem("user_email", data.user?.email || form.email);
        localStorage.setItem("user_id", data.user?.id || "");
        toast.success("Account created!");
        navigate("/dashboard");
      } else {
        const { data } = await axios.post(`${API}/user/login`, { email: form.email, password: form.password });
        localStorage.setItem("user_token", data.token);
        localStorage.setItem("user_name", data.user?.name || "");
        localStorage.setItem("user_email", data.user?.email || form.email);
        localStorage.setItem("user_id", data.user?.id || "");
        toast.success("Welcome back!");
        navigate("/dashboard");
      }
    } catch (err) {
      toast.error(err.response?.data?.detail || "Authentication failed");
    }
    setLoading(false);
  };

  return (
    <div className="min-h-screen bg-[#0B0B0B] pt-24 pb-16 flex items-center justify-center">
      <div className="w-full max-w-sm mx-auto px-4">
        <div className="text-center mb-8">
          <p className="text-[15px] font-extrabold tracking-[-0.03em] text-white uppercase mb-2">
            QUEEN CITY<span className="text-[#3B82F6] ml-1">AUTO</span>
          </p>
          <h1 className="text-2xl font-bold tracking-[-0.03em] text-white">{mode === "login" ? "Sign In" : "Create Account"}</h1>
        </div>

        {/* Tabs */}
        <div className="flex mb-6 border-b border-[#2A2A2A]">
          {["login", "register"].map(m => (
            <button
              key={m}
              data-testid={`auth-tab-${m}`}
              onClick={() => setMode(m)}
              className={`flex-1 py-2.5 text-[13px] font-semibold uppercase tracking-wide transition-colors ${mode === m ? "text-[#3B82F6] border-b-2 border-[#3B82F6]" : "text-[#666] hover:text-white"}`}
            >
              {m === "login" ? "Sign In" : "Register"}
            </button>
          ))}
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          {mode === "register" && (
            <div>
              <label className="block text-[11px] font-semibold uppercase tracking-[0.08em] text-[#9A9A9A] mb-1.5">Full Name</label>
              <input data-testid="user-register-name" placeholder="John Smith" value={form.name} onChange={update("name")} className={inputCls} required />
            </div>
          )}
          <div>
            <label className="block text-[11px] font-semibold uppercase tracking-[0.08em] text-[#9A9A9A] mb-1.5">Email</label>
            <input data-testid={mode === "login" ? "user-login-email" : "user-register-email"} type="email" placeholder="email@example.com" value={form.email} onChange={update("email")} className={inputCls} required />
          </div>
          <div>
            <label className="block text-[11px] font-semibold uppercase tracking-[0.08em] text-[#9A9A9A] mb-1.5">Password</label>
            <input data-testid={mode === "login" ? "user-login-password" : "user-register-password"} type="password" placeholder="Enter password" value={form.password} onChange={update("password")} className={inputCls} required />
          </div>
          {mode === "register" && (
            <div>
              <label className="block text-[11px] font-semibold uppercase tracking-[0.08em] text-[#9A9A9A] mb-1.5">Phone</label>
              <input data-testid="user-register-phone" placeholder="(704) 900-3512" value={form.phone} onChange={update("phone")} className={inputCls} />
            </div>
          )}
          <button
            data-testid={mode === "login" ? "user-login-btn" : "user-register-btn"}
            type="submit"
            disabled={loading}
            className="w-full h-12 bg-[#3B82F6] hover:bg-[#2563EB] text-white text-[14px] font-bold uppercase tracking-wide rounded transition-colors flex items-center justify-center"
          >
            {loading ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : null}
            {mode === "login" ? "Sign In" : "Create Account"}
          </button>
        </form>
      </div>
    </div>
  );
}
