"use client";

import Link from "next/link";
import { FormEvent, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { getSupabaseBrowser } from "@/lib/supabase-browser";

export default function LoginPage() {
  const router = useRouter();
  const [mode, setMode] = useState<"login" | "signup">("login");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [displayName, setDisplayName] = useState("");
  const [busy, setBusy] = useState(false);
  const [message, setMessage] = useState("");

  useEffect(() => {
    getSupabaseBrowser().auth.getSession().then(({ data }) => {
      if (data.session) router.replace("/dashboard");
    });
  }, [router]);

  async function submit(event: FormEvent) {
    event.preventDefault();
    setBusy(true);
    setMessage("");
    const supabase = getSupabaseBrowser();
    try {
      if (mode === "signup") {
        const { data, error } = await supabase.auth.signUp({
          email,
          password,
          options: { data: { display_name: displayName || email.split("@")[0] } }
        });
        if (error) throw error;
        if (!data.session) {
          setMessage("Tài khoản đã được tạo. Hãy kiểm tra email để xác nhận rồi đăng nhập.");
          setMode("login");
          return;
        }
      } else {
        const { error } = await supabase.auth.signInWithPassword({ email, password });
        if (error) throw error;
      }
      const next = new URLSearchParams(window.location.search).get("next") || "/dashboard";
      router.replace(next.startsWith("/") ? next : "/dashboard");
    } catch (error) {
      setMessage(error instanceof Error ? error.message : "Không thể đăng nhập.");
    } finally {
      setBusy(false);
    }
  }

  return (
    <main className="authPage">
      <Link href="/" className="brand authBrand"><span className="brandMark">G</span> GroupVault</Link>
      <section className="authCard">
        <div className="authIntro">
          <span className="eyebrow">Không giảm chất lượng file</span>
          <h1>{mode === "login" ? "Chào mừng trở lại" : "Tạo tài khoản mới"}</h1>
          <p>{mode === "login" ? "Đăng nhập để truy cập kho dữ liệu của nhóm." : "Tạo tài khoản và mời đồng đội bằng liên kết riêng."}</p>
        </div>
        <form onSubmit={submit} className="authForm">
          {mode === "signup" && <label>Họ tên<input value={displayName} onChange={(e) => setDisplayName(e.target.value)} placeholder="Nguyễn Văn A" /></label>}
          <label>Email<input type="email" required value={email} onChange={(e) => setEmail(e.target.value)} placeholder="ban@congty.vn" /></label>
          <label>Mật khẩu<input type="password" minLength={6} required value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Tối thiểu 6 ký tự" /></label>
          {message && <div className="notice">{message}</div>}
          <button className="button primary full" disabled={busy}>{busy ? "Đang xử lý…" : mode === "login" ? "Đăng nhập" : "Tạo tài khoản"}</button>
        </form>
        <button className="textButton" onClick={() => { setMode(mode === "login" ? "signup" : "login"); setMessage(""); }}>
          {mode === "login" ? "Chưa có tài khoản? Đăng ký" : "Đã có tài khoản? Đăng nhập"}
        </button>
      </section>
    </main>
  );
}
