"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useRef } from "react";
import { signOutAction } from "@/core/auth/sign-out-action";
import { useDashboardNav } from "@/components/dashboard/nav-context";
import { PublicStudioLink } from "@/components/dashboard/public-studio-link";
import type { DashboardIconName } from "@/components/dashboard/sidebar-icons";

type NavItem = {
  href: string;
  label: string;
  icon: DashboardIconName;
  badge?: number;
};

type NavSection = {
  title: string;
  items: NavItem[];
};

function buildNav(counts: {
  newInquiryCount: number;
  draftProjectCount: number;
  draftJournalCount: number;
  unpublishedServiceCount: number;
}): NavSection[] {
  return [
    {
      title: "Overview",
      items: [{ href: "/dashboard", label: "Dashboard", icon: "dashboard" }],
    },
    {
      title: "Portfolio",
      items: [
        {
          href: "/dashboard/projects",
          label: "Projects",
          icon: "projects",
          badge: counts.draftProjectCount || undefined,
        },
        {
          href: "/dashboard/categories",
          label: "Categories",
          icon: "categories",
        },
      ],
    },
    {
      title: "Content",
      items: [
        {
          href: "/dashboard/services",
          label: "Services",
          icon: "services",
          badge: counts.unpublishedServiceCount || undefined,
        },
        {
          href: "/dashboard/journal",
          label: "Journal",
          icon: "journal",
          badge: counts.draftJournalCount || undefined,
        },
        { href: "/dashboard/media", label: "Media", icon: "media" },
      ],
    },
    {
      title: "Studio",
      items: [
        {
          href: "/dashboard/inquiries",
          label: "Inquiries",
          icon: "inquiries",
          badge: counts.newInquiryCount || undefined,
        },
        { href: "/dashboard/team", label: "Team", icon: "inquiries" },
        { href: "/dashboard/awards", label: "Awards", icon: "categories" },
        {
          href: "/dashboard/publications",
          label: "Publications",
          icon: "journal",
        },
        { href: "/dashboard/domains", label: "Domains", icon: "domains" },
        { href: "/dashboard/settings", label: "Settings", icon: "settings" },
      ],
    },
  ];
}

type DashboardSidebarProps = {
  studioName: string;
  userName: string | null | undefined;
  userEmail: string | null | undefined;
  userRole: string;
  siteUrl: string;
  tenantSlug: string;
  planName: string | null;
  planStatus: string | null;
  trialEndsAt: string | null;
  newInquiryCount: number;
  draftProjectCount: number;
  draftJournalCount: number;
  unpublishedServiceCount: number;
};

export function DashboardSidebar({
  studioName,
  userName,
  userEmail,
  userRole,
  siteUrl,
  tenantSlug,
  planName,
  planStatus,
  trialEndsAt,
  newInquiryCount,
  draftProjectCount,
  draftJournalCount,
  unpublishedServiceCount,
}: DashboardSidebarProps) {
  const pathname = usePathname();
  const { open, setOpen } = useDashboardNav();
  const navRef = useRef<HTMLElement>(null);
  const displayName = userName?.trim() || userEmail?.split("@")[0] || "Studio";
  const sections = buildNav({
    newInquiryCount,
    draftProjectCount,
    draftJournalCount,
    unpublishedServiceCount,
  });

  useEffect(() => {
    setOpen(false);
    navRef.current?.scrollTo({ top: 0, behavior: "instant" as ScrollBehavior });
  }, [pathname, setOpen]);

  return (
    <>
      <button
        type="button"
        aria-label="Close menu"
        className={`fixed inset-0 z-40 bg-black/50 backdrop-blur-[2px] transition-opacity duration-300 lg:hidden ${
          open ? "opacity-100" : "pointer-events-none opacity-0"
        }`}
        onClick={() => setOpen(false)}
      />
      <aside
        className={`fixed inset-y-0 left-0 z-50 flex h-[100dvh] w-[260px] max-w-[85vw] flex-col border-r border-[var(--archi-line-on-dark)] bg-[var(--archi-dark)] text-white shadow-2xl transition-transform duration-300 ease-[cubic-bezier(0.22,1,0.36,1)] lg:max-w-none lg:shadow-none ${
          open ? "translate-x-0" : "-translate-x-full lg:translate-x-0"
        }`}
      >
        <div className="flex shrink-0 items-center gap-2.5 border-b border-white/10 px-5 py-4">
          <span className="flex h-8 w-8 items-center justify-center rounded-lg bg-[var(--archi-gold)]/15">
            <ArchMark className="h-4 w-4" />
          </span>
          <div className="min-w-0">
            <p className="truncate text-sm font-semibold tracking-wide text-white">
              ARCHI
            </p>
            <p className="truncate text-[11px] text-white/50">Architecture Platform</p>
          </div>
        </div>

        <div className="mx-3 mt-3 flex shrink-0 items-center gap-2.5 rounded-xl border border-white/10 bg-white/[0.03] px-3 py-2.5">
          <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-[var(--archi-gold)]/20 text-xs font-semibold text-[var(--archi-gold-bright)]">
            {studioName.slice(0, 1).toUpperCase()}
          </span>
          <div className="min-w-0">
            <p className="truncate text-sm font-medium text-white">{studioName}</p>
            <p className="truncate text-[10px] capitalize text-white/45">
              {userRole}
            </p>
          </div>
        </div>

        <nav
          ref={navRef}
          className="min-h-0 flex-1 space-y-4 overflow-y-auto overscroll-contain px-3 py-3 lg:overflow-y-auto"
        >
          {sections.map((section) => (
            <div key={section.title}>
              <p className="mb-1 px-3 text-[10px] font-semibold tracking-[0.18em] text-white/40 uppercase">
                {section.title}
              </p>
              <div className="space-y-0.5">
                {section.items.map((item) => {
                  const active =
                    item.href === "/dashboard"
                      ? pathname === "/dashboard"
                      : pathname.startsWith(item.href);
                  return (
                    <Link
                      key={item.href}
                      href={item.href}
                      className={`flex w-full items-center gap-3 rounded-xl px-3 py-2 text-[13px] transition ${
                        active
                          ? "bg-[var(--archi-gold)]/15 font-medium text-[var(--archi-gold-bright)] ring-1 ring-[var(--archi-gold)]/25"
                          : "text-white/75 hover:bg-white/5 hover:text-white"
                      }`}
                    >
                      <NavIcon name={item.icon} />
                      <span className="flex-1 truncate">{item.label}</span>
                      {item.badge ? (
                        <span className="inline-flex min-w-5 items-center justify-center rounded-full bg-[var(--archi-gold)] px-1.5 py-0.5 text-[10px] font-bold text-[var(--archi-dark)]">
                          {item.badge > 99 ? "99+" : item.badge}
                        </span>
                      ) : null}
                    </Link>
                  );
                })}
              </div>
            </div>
          ))}
        </nav>

        <div className="shrink-0 space-y-2 border-t border-white/10 p-3">
          {planName ? (
            <div className="rounded-xl border border-white/10 bg-white/[0.03] px-3 py-2.5">
              <p className="text-[10px] tracking-[0.12em] text-white/40 uppercase">
                {planName}
              </p>
              <p className="mt-0.5 text-[11px] capitalize text-white/55">
                {planStatus?.replaceAll("_", " ")}
                {trialEndsAt ? ` · trial ends ${trialEndsAt}` : ""}
              </p>
            </div>
          ) : null}

          <PublicStudioLink
            slug={tenantSlug}
            href={siteUrl}
            target="_blank"
            rel="noreferrer"
            className="flex items-center justify-center gap-1.5 rounded-xl border border-white/10 bg-white/[0.03] py-2 text-[11px] text-white/60 transition hover:border-[var(--archi-gold)]/30 hover:text-white"
          >
            View public site
            <span aria-hidden>↗</span>
          </PublicStudioLink>

          <div className="flex items-center gap-2.5 rounded-xl border border-white/10 bg-white/[0.03] px-2.5 py-2">
            <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-[var(--archi-gold)]/20 text-xs font-semibold text-[var(--archi-gold-bright)]">
              {displayName.slice(0, 1).toUpperCase()}
            </span>
            <div className="min-w-0 flex-1">
              <p className="truncate text-sm font-medium text-white">
                {displayName}
              </p>
              <p className="truncate text-[10px] capitalize text-white/45">
                {userRole}
              </p>
            </div>
            <form action={signOutAction}>
              <button
                type="submit"
                className="text-[10px] text-white/50 hover:text-white"
              >
                Sign out
              </button>
            </form>
          </div>
        </div>
      </aside>
    </>
  );
}

function ArchMark({ className = "h-5 w-5" }: { className?: string }) {
  return (
    <svg viewBox="0 0 32 32" className={className} aria-hidden fill="none">
      <path
        d="M16 3L28 28H22.5L19.7 21.2H12.3L9.5 28H4L16 3Z"
        fill="var(--archi-gold)"
      />
      <path d="M13.4 18.2H18.6L16 12.2L13.4 18.2Z" fill="var(--archi-dark)" />
    </svg>
  );
}

function NavIcon({ name }: { name: DashboardIconName }) {
  const props = {
    viewBox: "0 0 24 24",
    className: "h-4 w-4 shrink-0",
    fill: "none" as const,
    "aria-hidden": true as const,
  };
  const stroke = "currentColor";

  switch (name) {
    case "dashboard":
      return (
        <svg {...props}>
          <rect x="3" y="3" width="8" height="8" rx="1.5" stroke={stroke} strokeWidth="1.5" />
          <rect x="13" y="3" width="8" height="5" rx="1.5" stroke={stroke} strokeWidth="1.5" />
          <rect x="13" y="10" width="8" height="11" rx="1.5" stroke={stroke} strokeWidth="1.5" />
          <rect x="3" y="13" width="8" height="8" rx="1.5" stroke={stroke} strokeWidth="1.5" />
        </svg>
      );
    case "projects":
      return (
        <svg {...props}>
          <path d="M4 7h16v12H4z" stroke={stroke} strokeWidth="1.5" />
          <path d="M8 7V5h8v2" stroke={stroke} strokeWidth="1.5" />
        </svg>
      );
    case "categories":
      return (
        <svg {...props}>
          <path d="M4 6h7v7H4zM13 6h7v4h-7zM13 12h7v6h-7zM4 15h7v3H4z" stroke={stroke} strokeWidth="1.5" />
        </svg>
      );
    case "services":
      return (
        <svg {...props}>
          <path d="M12 3l2.2 4.5L19 8.2l-3.5 3.4.8 4.9L12 14.8 7.7 16.5l.8-4.9L5 8.2l4.8-.7L12 3z" stroke={stroke} strokeWidth="1.5" strokeLinejoin="round" />
        </svg>
      );
    case "journal":
      return (
        <svg {...props}>
          <path d="M6 4h11a2 2 0 012 2v14H8a2 2 0 01-2-2V4z" stroke={stroke} strokeWidth="1.5" />
          <path d="M9 8h7M9 12h7M9 16h4" stroke={stroke} strokeWidth="1.5" strokeLinecap="round" />
        </svg>
      );
    case "inquiries":
      return (
        <svg {...props}>
          <rect x="3" y="5" width="18" height="14" rx="2" stroke={stroke} strokeWidth="1.5" />
          <path d="M3 8l9 6 9-6" stroke={stroke} strokeWidth="1.5" />
        </svg>
      );
    case "media":
      return (
        <svg {...props}>
          <rect x="3" y="5" width="18" height="14" rx="2" stroke={stroke} strokeWidth="1.5" />
          <circle cx="9" cy="11" r="2" stroke={stroke} strokeWidth="1.5" />
          <path d="M3 16l5-4 4 3 3-2 6 4" stroke={stroke} strokeWidth="1.5" />
        </svg>
      );
    case "domains":
      return (
        <svg {...props}>
          <circle cx="12" cy="12" r="9" stroke={stroke} strokeWidth="1.5" />
          <path d="M3 12h18M12 3c2.5 3 4 6 4 9s-1.5 6-4 9c-2.5-3-4-6-4-9s1.5-6 4-9z" stroke={stroke} strokeWidth="1.5" />
        </svg>
      );
    case "settings":
      return (
        <svg {...props}>
          <circle cx="12" cy="12" r="3" stroke={stroke} strokeWidth="1.5" />
          <path
            d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6l1.4 1.4M17 17l1.4 1.4M5.6 18.4l1.4-1.4M17 7l1.4-1.4"
            stroke={stroke}
            strokeWidth="1.5"
            strokeLinecap="round"
          />
        </svg>
      );
  }
}
