"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import {
  LayoutDashboard,
  PlusCircle,
  History,
  CreditCard,
  LogOut,
  User,
} from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { Badge } from "@/components/ui/badge";
import { PLAN_LIMITS, getPlanBadgeColor } from "@/lib/plan-limits";
import { LogoIcon } from "@/components/shared/logo";
import { userApi, type UserResponse } from "@/lib/api";
import { getValidToken, logout } from "@/lib/auth-store";

const navItems = [
  { href: "/dashboard", icon: LayoutDashboard, label: "Overview" },
  { href: "/dashboard/new-job", icon: PlusCircle, label: "New Job" },
  { href: "/dashboard/jobs", icon: History, label: "Job History" },
  { href: "/dashboard/account", icon: CreditCard, label: "Account & Billing" },
];

export function DashboardSidebar() {
  const pathname = usePathname();
  const [user, setUser] = useState<UserResponse | null>(null);
  const [confirmLogout, setConfirmLogout] = useState(false);

  useEffect(() => {
    (async () => {
      const token = await getValidToken();
      if (!token) return;
      try {
        const u = await userApi.getMe(token);
        setUser(u);
      } catch {
        // non-critical — sidebar still renders without user info
      }
    })();
  }, []);

  const planKey = (user?.plan && user.plan in PLAN_LIMITS) ? user.plan : "free";
  const avatarLetter = user?.name ? user.name[0].toUpperCase() : "?";

  return (
    <>
      <aside className="fixed left-0 top-0 bottom-0 w-56 z-40 flex flex-col border-r border-white/8 bg-black/60 backdrop-blur-xl">
        {/* Logo */}
        <div className="flex items-center gap-2.5 h-16 px-4 border-b border-white/8">
          <LogoIcon size={30} />
          <span className="text-sm font-bold gradient-text">ReelsCutter</span>
        </div>

        {/* User info */}
        <div className="px-4 py-3 border-b border-white/8">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 rounded-full bg-gradient-to-br from-violet-600 to-cyan-500 flex items-center justify-center text-sm font-bold text-white flex-shrink-0">
              {avatarLetter}
            </div>
            <div className="min-w-0">
              <div className="text-xs font-medium text-white truncate">
                {user?.name ?? "Loading..."}
              </div>
              <Badge className={`text-[10px] px-1.5 py-0 mt-0.5 ${getPlanBadgeColor(planKey)}`}>
                {PLAN_LIMITS[planKey].name}
              </Badge>
            </div>
          </div>
        </div>

        {/* Nav */}
        <nav className="flex-1 py-4 px-2 space-y-1 overflow-y-auto">
          {navItems.map((item) => {
            const active =
              item.href === "/dashboard" ? pathname === item.href : pathname.startsWith(item.href);
            return (
              <Link
                key={item.href}
                href={item.href}
                className={cn(
                  "flex items-center gap-3 px-3 h-10 rounded-lg text-sm font-medium transition-all",
                  active
                    ? "bg-violet-600/20 text-violet-300 border border-violet-500/30"
                    : "text-zinc-400 hover:text-white hover:bg-white/5"
                )}
              >
                <item.icon className="w-4 h-4 flex-shrink-0" />
                {item.label}
              </Link>
            );
          })}
        </nav>

        {/* Footer */}
        <div className="px-2 pb-4 border-t border-white/8 pt-4 space-y-1">
          <Link
            href="/dashboard/account"
            className="flex items-center gap-3 px-3 h-9 rounded-lg text-sm text-zinc-500 hover:text-white hover:bg-white/5 transition-all"
          >
            <User className="w-4 h-4" />
            Profile
          </Link>
          <button
            onClick={() => setConfirmLogout(true)}
            className="w-full flex items-center gap-3 px-3 h-9 rounded-lg text-sm text-zinc-500 hover:text-white hover:bg-white/5 transition-all"
          >
            <LogOut className="w-4 h-4" />
            Sign Out
          </button>
        </div>
      </aside>

      <Dialog open={confirmLogout} onOpenChange={setConfirmLogout}>
        <DialogContent className="bg-zinc-900 border-white/10 text-white max-w-sm">
          <DialogHeader>
            <DialogTitle>Sign out?</DialogTitle>
            <DialogDescription className="text-zinc-400">
              You will be returned to the login page.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter className="gap-2">
            <Button
              variant="outline"
              className="bg-white/5 border-white/10 text-zinc-300 hover:bg-white/10 hover:text-white"
              onClick={() => setConfirmLogout(false)}
            >
              Cancel
            </Button>
            <Button
              onClick={logout}
              className="bg-red-600 hover:bg-red-500 text-white border-0"
            >
              Sign Out
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
