"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import type { ProfileUser } from "../lib/api";
import { StatusControls } from "./StatusControls";
import {
  BrandMark,
  IconBell,
  IconAt,
  IconCalendar,
  IconDocs,
  IconMessages,
  IconMore,
  IconPeople,
  IconPhone,
  IconStar,
  IconTasks,
  IconThreads,
} from "./icons";

export type GlobalNavActive = "activity" | "tasks" | "chat" | "threads" | "unreads" | "saved" | "people" | "calendar" | "calls" | "files" | "more";

/**
 * Far-left global navigation rail — dark icon strip for app-level sections.
 */
export function GlobalNav({
  workspaceId,
  active,
  activityCount = 0,
  taskCount = 0,
  chatCount = 0,
  missedCallCount = 0,
  myUserId,
  meName,
  meAvatarUrl,
}: {
  workspaceId: string;
  active?: GlobalNavActive;
  activityCount?: number;
  taskCount?: number;
  chatCount?: number;
  missedCallCount?: number;
  myUserId?: string | number | null;
  meName?: string | null;
  meAvatarUrl?: string | null;
}) {
  const pathname = usePathname();
  const [avatarUrl, setAvatarUrl] = useState(meAvatarUrl ?? null);

  useEffect(() => setAvatarUrl(meAvatarUrl ?? null), [meAvatarUrl]);
  useEffect(() => {
    function onProfileUpdated(event: Event) {
      const user = (event as CustomEvent<ProfileUser>).detail;
      if (user && String(user.id) === String(myUserId)) setAvatarUrl(user.avatarUrl);
    }
    window.addEventListener("profile:updated", onProfileUpdated);
    return () => window.removeEventListener("profile:updated", onProfileUpdated);
  }, [myUserId]);

  const resolved: GlobalNavActive =
    active ??
    (pathname?.startsWith("/activity")
      ? "activity"
      : pathname?.startsWith("/tasks")
        ? "tasks"
      : pathname?.startsWith("/threads")
        ? "threads"
      : pathname?.startsWith("/home")
        ? "activity"
        : pathname?.startsWith("/unreads")
          ? "unreads"
        : pathname?.startsWith("/saved")
          ? "saved"
          : pathname?.startsWith("/people")
            ? "people"
            : pathname?.startsWith("/calendar")
              ? "calendar"
              : pathname?.startsWith("/calls")
                ? "calls"
              : pathname?.startsWith("/files")
                  ? "files"
                  : "chat");

  const items: Array<{
    key: GlobalNavActive;
    href: string;
    label: string;
    Icon: typeof IconMessages;
    badge?: number;
  }> = [
    {
      key: "activity",
      href: `/activity?workspaceId=${workspaceId}`,
      label: "Activity",
      Icon: IconBell,
      badge: activityCount,
    },
    {
      key: "tasks",
      href: `/tasks?workspaceId=${workspaceId}`,
      label: "Tasks",
      Icon: IconTasks,
      badge: taskCount,
    },
    {
      key: "chat",
      href: `/workspace?id=${workspaceId}`,
      label: "Chat",
      Icon: IconMessages,
    },
    {
      key: "threads",
      href: `/threads?workspaceId=${workspaceId}`,
      label: "Threads",
      Icon: IconThreads,
    },
    {
      key: "unreads",
      href: `/unreads?workspaceId=${workspaceId}`,
      label: "Unreads",
      Icon: IconAt,
      badge: chatCount,
    },
    {
      key: "saved",
      href: `/saved?workspaceId=${workspaceId}`,
      label: "Saved",
      Icon: IconStar,
    },
    {
      key: "people",
      href: `/people?workspaceId=${workspaceId}`,
      label: "People",
      Icon: IconPeople,
    },
    {
      key: "calendar",
      href: `/calendar?workspaceId=${workspaceId}`,
      label: "Calendar",
      Icon: IconCalendar,
    },
    {
      key: "calls",
      href: `/calls?workspaceId=${workspaceId}`,
      label: "Calls",
      Icon: IconPhone,
      badge: missedCallCount,
    },
    {
      key: "files",
      href: `/files?workspaceId=${workspaceId}`,
      label: "Files",
      Icon: IconDocs,
    },
  ];

  return (
    <nav className="gnav" aria-label="Global">
      <Link className="gnav-brand" href={`/home?workspaceId=${workspaceId}`} aria-label="connectHUB home">
        <span className="gnav-brand-chip">
          <BrandMark size={20} />
        </span>
      </Link>

      <div className="gnav-nav">
        {items.map(({ key, href, label, Icon, badge }) => (
          <Link
            key={key}
            href={href}
            className={resolved === key ? "gnav-item active" : "gnav-item"}
            aria-label={label}
            title={label}
          >
            <Icon size={20} />
            <span className="gnav-label">{label}</span>
            {(badge ?? 0) > 0 && <span className="gnav-badge">{badge}</span>}
          </Link>
        ))}
        <button type="button" className="gnav-item" aria-label="More" title="More" disabled>
          <IconMore size={20} />
          <span className="gnav-label">More</span>
        </button>
      </div>

      <div className="gnav-spacer" />

      <StatusControls workspaceId={workspaceId} userId={myUserId} name={meName} avatarUrl={avatarUrl} />
    </nav>
  );
}
