"use client"

/**
 * The one scope (school > program / brand > site > location) picker menu.
 *
 * This body was previously copy-pasted into `UtilityBarSchoolSwitcher` and the
 * sidebar's `TeamSwitcher`, each with its own `useState` — so the two chrome
 * surfaces could show different programs at the same time. Both now render
 * this component over shared `useActiveScope` state, which the products home
 * writes to before the user has even entered the product.
 *
 * Only the *trigger* differs per surface: an avatar circle in the utility bar,
 * a full row in the sidebar, a card row on the products home. The menu itself
 * is identical everywhere, so it lives here once.
 */

import * as React from "react"

import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import {
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu"
import type { Product } from "@/contexts/product-context"
import { useActiveScope } from "@/hooks/use-active-scope"
import type { ScopeChild, ScopeConfig, ScopeParent } from "@/lib/scope-switcher"
import { cn } from "@/lib/utils"

export interface ScopeSwitcherBag {
  config: ScopeConfig
  parent: ScopeParent
  child: ScopeChild
  subView: "main" | "parents"
  /** Pass to `DropdownMenu` so the menu reopens on the main view. */
  onOpenChange: (open: boolean) => void
  showParents: () => void
  showMain: () => void
  selectParent: (parent: ScopeParent) => void
  selectChild: (child: ScopeChild) => void
  /** `"<Parent> · <Child>. <how to change it>"` — for `aria-label`. */
  ariaLabel: string
}

/** Shared state + handlers for any trigger that opens `ScopeSwitcherMenuBody`. */
export function useScopeSwitcher(product: Product, customIndex?: number): ScopeSwitcherBag {
  const { config, parent, child, selectParent, selectChild } = useActiveScope(
    product,
    customIndex,
  )
  const [subView, setSubView] = React.useState<"main" | "parents">("main")

  return {
    config,
    parent,
    child,
    subView,
    onOpenChange: open => {
      if (!open) setSubView("main")
    },
    showParents: () => setSubView("parents"),
    showMain: () => setSubView("main"),
    selectParent: next => {
      selectParent(next)
      setSubView("main")
    },
    selectChild,
    ariaLabel: `${parent.name} · ${child.name}. ${config.ariaSuffix}`,
  }
}

/** Menu contents. Render inside a `DropdownMenuContent`. */
export function ScopeSwitcherMenuBody({ scope }: { scope: ScopeSwitcherBag }) {
  const { config, parent, child, subView, showParents, showMain } = scope

  if (subView === "parents") {
    return (
      <>
        <DropdownMenuItem
          onSelect={e => {
            e.preventDefault()
            showMain()
          }}
        >
          <i className="fa-light fa-arrow-left text-xs" aria-hidden="true" />
          <span>Back</span>
        </DropdownMenuItem>
        <DropdownMenuSeparator />
        <DropdownMenuLabel className="text-xs text-muted-foreground">
          {config.parentSelectLabel}
        </DropdownMenuLabel>
        {config.parents.map(option => (
          <DropdownMenuItem
            key={option.id}
            // Stay open and return to the program/site list — closing here
            // forced a second open just to finish the scope pick.
            onSelect={event => {
              event.preventDefault()
              scope.selectParent(option)
            }}
            className="items-start py-2"
          >
            <Avatar size="sm" className="mt-0.5 shrink-0">
              <AvatarImage src={option.logo} alt="" referrerPolicy="origin" />
              <AvatarFallback className="text-xs font-semibold">
                {option.initials}
              </AvatarFallback>
            </Avatar>
            <span className="min-w-0 flex-1 break-words whitespace-normal">
              {option.name}
            </span>
            {option.id === parent.id && (
              <i
                className="fa-solid fa-check ms-1 mt-0.5 shrink-0 text-xs text-brand"
                aria-hidden="true"
              />
            )}
          </DropdownMenuItem>
        ))}
      </>
    )
  }

  return (
    <>
      <div className="p-1">
        <button
          type="button"
          onClick={showParents}
          className={cn(
            "flex w-full items-center gap-2.5 rounded-md p-2 text-left transition-colors",
            "hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
          )}
        >
          <Avatar className="size-9 shrink-0">
            <AvatarImage
              src={parent.logo}
              alt=""
              referrerPolicy="origin"
              className="object-contain p-0.5"
            />
            <AvatarFallback className="text-xs font-semibold">
              {parent.initials}
            </AvatarFallback>
          </Avatar>
          <div className="min-w-0 flex-1">
            <p className="line-clamp-2 break-words text-sm font-semibold leading-snug whitespace-normal">
              {parent.name}
            </p>
            <p className="truncate text-xs text-muted-foreground">{child.name}</p>
          </div>
          <span className="shrink-0 text-sm font-medium text-brand">Change</span>
        </button>
      </div>

      <DropdownMenuSeparator />

      <DropdownMenuLabel className="text-xs text-muted-foreground">
        {config.childNoun}
      </DropdownMenuLabel>
      {config.childrenOf(parent).map(option => (
        <DropdownMenuItem
          key={option.id}
          onClick={() => scope.selectChild(option)}
          className="items-start py-2"
        >
          <i
            className={`fa-light fa-${config.childIcon} mt-0.5 shrink-0 text-xs`}
            aria-hidden="true"
          />
          <span className="min-w-0 flex-1 break-words whitespace-normal">
            {option.name}
          </span>
          {option.id === child.id && (
            <i
              className="fa-solid fa-check ms-1 mt-0.5 shrink-0 text-xs text-brand"
              aria-hidden="true"
            />
          )}
        </DropdownMenuItem>
      ))}
    </>
  )
}
