"use client";

import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { LogOut, User, ChevronDown, Zap, Settings, Crown } from "lucide-react";
import { createClient } from "@/lib/supabase/client";
import { toast } from "sonner";
import type { Profile } from "@/types";
import { cn } from "@/lib/utils";

interface TopBarProps {
  profile: Profile | null;
}

export default function TopBar({ profile }: TopBarProps) {
  const [open, setOpen] = useState(false);
  const router = useRouter();
  const supabase = createClient();

  async function handleLogout() {
    await supabase.auth.signOut();
    toast.success("Berhasil keluar");
    router.push("/");
    router.refresh();
  }

  const usageCount   = profile?.usage_count ?? 0;
  const usageLimit   = profile?.usage_limit ?? 50;
  const usagePercent = Math.round((usageCount / usageLimit) * 100);
  const isNearLimit  = usagePercent >= 80;

  return (
    <header className="h-16 gold-border-b flex items-center justify-between px-6 bg-card/40 backdrop-blur-sm sticky top-0 z-10">

      {/* Mobile logo */}
      <div className="flex items-center gap-2 md:hidden">
        <div className="w-7 h-7 rounded-lg bg-gradient-to-br from-purple-500 to-cyan-500 flex items-center justify-center shadow-md shadow-purple-500/30">
          <Zap className="w-3.5 h-3.5 text-white" />
        </div>
        <span className="font-bold gold-shimmer-text text-sm">PromptMotion</span>
      </div>

      <div className="hidden md:block" />

      <div className="flex items-center gap-4">

        {/* Usage indicator */}
        {profile && (
          <div className="hidden sm:flex items-center gap-3 text-sm">
            <div className="text-right">
              <p className="text-[11px] text-muted-foreground leading-none">Kuota</p>
              <p className="text-xs font-medium leading-tight mt-0.5">
                <span className={cn("font-bold", isNearLimit ? "text-amber-400" : "text-foreground")}>
                  {usageCount}
                </span>
                <span className="text-muted-foreground">/{usageLimit}</span>
              </p>
            </div>
            {/* Gold-tinted usage bar */}
            <div
              className="w-24 h-1.5 rounded-full overflow-hidden"
              role="progressbar"
              aria-valuenow={usagePercent}
              aria-valuemin={0}
              aria-valuemax={100}
              aria-label={`Kuota terpakai ${usageCount} dari ${usageLimit}`}
              style={{ background: "rgba(212,175,55,0.1)", border: "1px solid rgba(212,175,55,0.15)" }}
            >
              <div
                className="h-full rounded-full transition-all"
                style={{
                  width: `${Math.min(usagePercent, 100)}%`,
                  background: isNearLimit
                    ? "linear-gradient(90deg, #f59e0b, #ef4444)"
                    : "linear-gradient(90deg, #7c3aed, #06b6d4)",
                }}
              />
            </div>
          </div>
        )}

        {/* User menu */}
        <div className="relative">
          <button
            onClick={() => setOpen(!open)}
            onKeyDown={(e) => { if (e.key === "Escape") setOpen(false); }}
            aria-expanded={open}
            aria-haspopup="menu"
            aria-label={`Menu pengguna, ${profile?.full_name ?? profile?.email ?? "User"}`}
            className="flex items-center gap-2 px-2.5 py-1.5 rounded-xl hover:bg-white/5 transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-amber-400"
          >
            {/* Avatar with gold ring for admin */}
            <div
              className={cn(
                "w-7 h-7 rounded-full flex items-center justify-center text-white text-xs font-bold",
                "bg-gradient-to-br from-purple-500 to-cyan-500"
              )}
              style={
                profile?.role === "admin"
                  ? {
                      outline: "2px solid transparent",
                      outlineOffset: "2px",
                      boxShadow: "0 0 0 2px rgba(212,175,55,0.6)",
                    }
                  : {}
              }
            >
              {profile?.full_name?.[0]?.toUpperCase() ?? <User className="w-3.5 h-3.5" />}
            </div>
            <span className="text-sm font-medium hidden sm:block max-w-[120px] truncate">
              {profile?.full_name ?? profile?.email ?? "User"}
            </span>
            {profile?.role === "admin" && (
              <Crown className="w-3 h-3 text-amber-400 hidden sm:block" aria-label="Admin" />
            )}
            <ChevronDown className={cn("w-3.5 h-3.5 text-muted-foreground transition-transform", open && "rotate-180")} aria-hidden="true" />
          </button>

          {open && (
            <>
              <div className="fixed inset-0 z-10" onClick={() => setOpen(false)} aria-hidden="true" />
              <div
                role="menu"
                aria-label="Menu pengguna"
                className="absolute right-0 top-full mt-2 w-52 rounded-2xl bg-card overflow-hidden z-20 shadow-2xl shadow-black/40"
                style={{ border: "1px solid rgba(212,175,55,0.25)" }}
                onKeyDown={(e) => { if (e.key === "Escape") setOpen(false); }}
              >

                {/* User info */}
                <div className="p-4 gold-border-b">
                  <p className="text-sm font-semibold truncate">{profile?.full_name ?? "—"}</p>
                  <p className="text-xs text-muted-foreground truncate mt-0.5">{profile?.email}</p>
                  <div className="flex items-center gap-1.5 mt-2">
                    <span className={cn(
                      "inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium capitalize",
                      profile?.plan === "pro"        ? "bg-purple-500/20 text-purple-300"
                      : profile?.plan === "enterprise" ? "bg-amber-500/20 text-amber-300"
                      : "bg-white/[0.08] text-muted-foreground"
                    )}>
                      {profile?.plan === "free" ? "Free Plan" : profile?.plan === "pro" ? "Pro Plan" : profile?.plan ?? "Free Plan"}
                    </span>
                    {profile?.role === "admin" && (
                      <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-amber-500/15 text-amber-400">
                        <Crown className="w-2.5 h-2.5" aria-hidden="true" /> Admin
                      </span>
                    )}
                  </div>
                </div>

                {/* Actions */}
                <div className="p-1.5">
                  <Link
                    href="/settings"
                    role="menuitem"
                    onClick={() => setOpen(false)}
                    className="w-full flex items-center gap-2.5 px-3 py-2 text-sm rounded-lg text-muted-foreground hover:text-foreground hover:bg-white/5 transition-colors"
                  >
                    <Settings className="w-4 h-4" aria-hidden="true" />
                    Pengaturan
                  </Link>
                  <div className="gold-hr-soft my-1" />
                  <button
                    role="menuitem"
                    onClick={handleLogout}
                    className="w-full flex items-center gap-2.5 px-3 py-2 text-sm rounded-lg text-red-400 hover:bg-red-500/10 transition-colors"
                  >
                    <LogOut className="w-4 h-4" aria-hidden="true" />
                    Keluar
                  </button>
                </div>
              </div>
            </>
          )}
        </div>
      </div>
    </header>
  );
}
