"use client";
import { useState } from "react";
import { API_BASE } from "@/lib/api";

export default function LoginPage() {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [err, setErr] = useState("");
  const [isLoading, setIsLoading] = useState(false);

  async function onSubmit(e) {
    e.preventDefault();
    setErr("");
    setIsLoading(true);
    try {
      const res = await fetch(`${API_BASE}/api/auth/login`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ username, password }),
      });

      const data = await res.json();

      if (!res.ok) {
        setErr(data.error || "เข้าสู่ระบบไม่สำเร็จ");
        return;
      }

      if (data.token) {
        localStorage.setItem("token", data.token);
        localStorage.setItem("refresh_token", data.refresh_token);
        location.href = "/dashboard";
      } else {
        setErr("ไม่ได้รับ Token");
      }
    } catch (error) {
      console.error("Login failed:", error);
      setErr("เกิดข้อผิดพลาดในการเชื่อมต่อ");
    } finally {
      setIsLoading(false);
    }
  }

  return (
    <div className="grid min-h-screen place-items-center" style={{background: 'linear-gradient(to bottom right, #00c6ff, #0072ff)'}}>
      <form onSubmit={onSubmit} className="w-full max-w-sm p-8 space-y-4 shadow-lg bg-white/20 backdrop-blur-md rounded-3xl">
        <div className="text-2xl font-bold text-center text-white">เข้าสู่ระบบ</div>
        <input
          disabled={isLoading}
          className="w-full p-3 text-white placeholder-gray-200 border bg-white/30 border-white/30 rounded-xl focus:outline-none focus:ring-2 focus:ring-white/50 disabled:opacity-50"
          placeholder="ชื่อผู้ใช้"
          value={username}
          onChange={e=>setUsername(e.target.value)}
        />
        <input
          type="password"
          disabled={isLoading}
          className="w-full p-3 text-white placeholder-gray-200 border bg-white/30 border-white/30 rounded-xl focus:outline-none focus:ring-2 focus:ring-white/50 disabled:opacity-50"
          placeholder="รหัสผ่าน"
          value={password}
          onChange={e=>setPassword(e.target.value)}
        />
        {err && <div className="text-sm text-center text-yellow-300">{err}</div>}
        <button
          type="submit"
          disabled={isLoading}
          className="w-full p-3 font-bold text-white transition-colors duration-300 bg-blue-500 rounded-xl hover:bg-blue-600 disabled:bg-blue-400 disabled:cursor-not-allowed"
        >
          {isLoading ? 'กำลังเข้าสู่ระบบ...' : 'เข้าสู่ระบบ'}
        </button>
      </form>
    </div>
  );
}
