"use client";

import { useEffect, useState } from "react";
import { createClient, isSupabaseConfigured } from "@/lib/supabase/client";
import Link from "next/link";
import type { User } from "@supabase/supabase-js";

interface Profile {
  display_name?: string | null;
  total_cost_usd?: number;
  budget_cap_usd?: number;
  daily_used?: number;
  daily_quota?: number;
}

export function AuthBar() {
  const [user, setUser] = useState<User | null>(null);
  const [profile, setProfile] = useState<Profile | null>(null);
  const [loaded, setLoaded] = useState(false);

  useEffect(() => {
    if (!isSupabaseConfigured()) {
      setLoaded(true);
      return;
    }
    const supabase = createClient();
    supabase.auth.getUser().then(({ data }) => {
      setUser(data.user);
      setLoaded(true);
      if (data.user) {
        fetch("/api/me")
          .then((r) => (r.ok ? r.json() : null))
          .then((d) => setProfile(d?.profile ?? null))
          .catch(() => {});
      }
    });
    const { data: sub } = supabase.auth.onAuthStateChange((_e, session) => {
      setUser(session?.user ?? null);
    });
    return () => sub.subscription.unsubscribe();
  }, []);

  if (!loaded) return null;

  if (!isSupabaseConfigured()) {
    return (
      <div className="font-mono text-[10px] text-[#5a6678] uppercase tracking-widest">
        auth: disabled (dev)
      </div>
    );
  }

  if (!user) {
    return (
      <Link
        href="/auth/signin"
        className="font-mono text-xs px-3 py-1 border border-[rgba(0,255,156,0.32)]
                   text-[#00ff9c] hover:bg-[rgba(0,255,156,0.08)] rounded"
      >
        sign in
      </Link>
    );
  }

  return (
    <div className="flex items-center gap-3">
      {profile && (
        <div className="font-mono text-[9px] text-[#5a6678] uppercase tracking-widest text-right">
          <div>{profile.display_name ?? user.email}</div>
          <div>
            ${(profile.total_cost_usd ?? 0).toFixed(2)} / ${(profile.budget_cap_usd ?? 0).toFixed(2)} ·{" "}
            {profile.daily_used ?? 0}/{profile.daily_quota ?? 0} msgs today
          </div>
        </div>
      )}
      <form action="/auth/signout" method="POST">
        <button
          type="submit"
          className="font-mono text-[10px] px-2 py-1 text-[#8896aa] hover:text-[#ff3344]
                     border border-transparent hover:border-[#ff3344] rounded"
        >
          sign out
        </button>
      </form>
    </div>
  );
}
