"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { CheckCircle2, LogOut, ShieldCheck } from "lucide-react";

import { authClient } from "@/lib/auth-client";
import { Button } from "@/components/ui/button";
import { DashboardThemeToggle } from "@/components/dashboard-theme";
import { dashboardNavigation } from "@/lib/dashboard-navigation";
import { useState } from "react";
import { cn } from "@/lib/utils";
import { useRouter } from "next/navigation";

export function DashboardSidebar() {
  const pathname = usePathname();
  const router = useRouter();
  const [isSigningOut, setIsSigningOut] = useState(false);
  const [signOutError, setSignOutError] = useState<string | null>(null);
  const { data: session, isPending } = authClient.useSession();

  return (
    <aside className="flex w-full shrink-0 flex-col border-b border-sidebar-border bg-sidebar text-sidebar-foreground md:sticky md:top-0 md:h-dvh md:w-[19rem] md:self-start md:overflow-y-auto md:border-b-0 md:border-r">
      <div className="flex h-[5.25rem] items-center gap-3 border-b border-sidebar-border px-4">
        <div className="flex size-11 items-center justify-center rounded-md bg-sidebar-primary font-heading text-sm font-black text-sidebar-primary-foreground shadow-[inset_0_1px_0_color-mix(in_oklch,var(--sidebar-primary-foreground),transparent_75%)]">
          PF
        </div>
        <div className="min-w-0">
          <p className="truncate font-heading text-sm font-semibold">
            PitchFast
          </p>
          <p className="truncate text-xs font-medium text-muted-foreground">
            Agency Evidence Desk
          </p>
        </div>
      </div>

      <div className="grid gap-2 border-b border-sidebar-border p-3">
        <div className="rounded-md border border-sidebar-border bg-sidebar-accent p-3">
          <p className="text-xs font-semibold text-sidebar-accent-foreground">
            Workspace Safety
          </p>
          <div className="mt-2 grid gap-2 text-xs text-muted-foreground">
            <span className="inline-flex items-center gap-2">
              <ShieldCheck className="size-3.5 text-sidebar-primary" />
              Versand nur nach Freigabe
            </span>
            <span className="inline-flex items-center gap-2">
              <CheckCircle2 className="size-3.5 text-sidebar-primary" />
              Evidence vor Outreach
            </span>
          </div>
        </div>
      </div>

      <nav
        className="flex gap-1 overflow-x-auto p-3 md:grid md:gap-1.5 md:overflow-visible"
        aria-label="Dashboard navigation"
      >
        {dashboardNavigation.map((item) => {
          const Icon = item.icon;
          const isActive =
            item.href === "/dashboard"
              ? pathname === item.href
              : pathname.startsWith(item.href);

          return (
            <Link
              aria-current={isActive ? "page" : undefined}
              className={cn(
                "flex h-10 shrink-0 items-center gap-2 rounded-md px-3 text-sm font-semibold outline-none transition-colors focus-visible:ring-3 focus-visible:ring-ring/35",
                isActive
                  ? "bg-sidebar-primary text-sidebar-primary-foreground shadow-[inset_0_1px_0_color-mix(in_oklch,var(--sidebar-primary-foreground),transparent_82%)]"
                  : "text-muted-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
              )}
              href={item.href}
              key={item.href}
              prefetch={false}
            >
              <Icon className="size-4" />
              <span>{item.label}</span>
            </Link>
          );
        })}
      </nav>

      <div className="border-t border-sidebar-border p-3 md:mt-auto">
        <div className="mb-3 rounded-md border border-sidebar-border bg-sidebar-accent p-3 md:block">
          <p className="truncate text-sm font-semibold">
            {isPending ? "Lade..." : session?.user?.name ?? "Workspace"}
          </p>
          <p className="truncate text-xs font-medium text-muted-foreground">
            {session?.user?.email ?? "team@workspace"}
          </p>
        </div>
        <div className="mb-2">
          <DashboardThemeToggle />
        </div>
        <Button
          className="w-full justify-start"
          variant="outline"
          onClick={async () => {
            setIsSigningOut(true);
            setSignOutError(null);

            try {
              await authClient.signOut();
              router.replace("/login");
              router.refresh();
            } catch {
              setSignOutError("Abmeldung fehlgeschlagen.");
            } finally {
              setIsSigningOut(false);
            }
          }}
          disabled={isSigningOut}
        >
          <LogOut />
          {isSigningOut ? "Abmeldung läuft..." : "Abmelden"}
        </Button>
        {signOutError ? (
          <p className="mt-2 text-xs text-destructive" role="status">
            {signOutError}
          </p>
        ) : null}
      </div>
    </aside>
  );
}
