"use client";
import { useState } from "react";
import { api } from "@/lib/api";
import { setToken } from "@/lib/auth";
import { useRouter } from "next/navigation";

export default function LoginPage() {
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [password, setPassword] = useState("");
  const [msg, setMsg] = useState("");
  const router = useRouter();

  async function login() {
    setMsg("Logging in...");
    const res = await api<any>("/auth/login", {
      method: "POST",
      body: JSON.stringify({ email: email || undefined, phone: phone || undefined, password }),
    });
    setToken(res.accessToken);
    setMsg("");
    router.push("/client");
  }

  async function register() {
    setMsg("Registering...");
    const res = await api<any>("/auth/register", {
      method: "POST",
      body: JSON.stringify({ email: email || undefined, phone: phone || undefined, password, displayName: "User" }),
    });
    setToken(res.accessToken);
    setMsg("");
    router.push("/client");
  }

  return (
    <div className="max-w-md border rounded p-4 grid gap-2">
      <h1 className="text-xl font-semibold">Login / Register</h1>
      <input className="border rounded p-2" placeholder="Email (optional)" value={email} onChange={(e)=>setEmail(e.target.value)} />
      <input className="border rounded p-2" placeholder="Phone (optional)" value={phone} onChange={(e)=>setPhone(e.target.value)} />
      <input className="border rounded p-2" placeholder="Password" type="password" value={password} onChange={(e)=>setPassword(e.target.value)} />
      <div className="flex gap-2">
        <button className="bg-black text-white rounded p-2 flex-1" onClick={login}>Login</button>
        <button className="border rounded p-2 flex-1" onClick={register}>Register</button>
      </div>
      {msg && <div className="text-sm opacity-80">{msg}</div>}
    </div>
  );
}
