import { useRef, useState } from 'react';
import { ChevronDown, CornerUpLeft, Globe } from 'lucide-react';

import { useScopeContext } from '@/contexts/scope-context';
import { useTenantChildren } from '@/business/scope/queries';
import { getTenantInitials } from '@/business/scope/selectors';
import { useOnClickOutside } from '@/hooks/useOnClickOutside';

const LEVEL_LABEL: Record<string, string> = {
  organization: 'Organization',
  school: 'School',
  campus: 'Campus',
  class: 'Classroom',
};

/**
 * Interactive active-tenant badge + drill-down switcher. Shows the effective
 * tenant (or "Platform" for global admins with no own tenant); opening it lists
 * the child tenants the user can drill into (organizations for a global admin),
 * plus a "back to my scope" reset once a child is selected.
 */
export function TenantSwitcher() {
  const { tier, effectiveTenant, selectedTenant, canDrill, drillInto, resetScope } =
    useScopeContext();
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  useOnClickOutside(ref, () => setOpen(false), open);

  const parent = effectiveTenant
    ? { level: effectiveTenant.level, id: effectiveTenant.id }
    : null;
  const { data, isLoading } = useTenantChildren(open ? parent : null);
  const children = data?.rows ?? [];

  // Global admins have no own tenant — show a "Platform" root they can drill from.
  const isPlatformRoot = !effectiveTenant && tier === 'global';
  if (!effectiveTenant && !isPlatformRoot) {
    return null;
  }

  const label = effectiveTenant?.name ?? 'Platform';
  const levelLabel = effectiveTenant
    ? (LEVEL_LABEL[effectiveTenant.level] ?? 'Tenant')
    : 'Platform';
  const mark = effectiveTenant?.logo ? (
    <img src={effectiveTenant.logo} alt="" className="w-full h-full object-cover" />
  ) : effectiveTenant ? (
    <span className="text-white text-[8px] font-bold">
      {getTenantInitials(effectiveTenant.name)}
    </span>
  ) : (
    <Globe size={11} className="text-white" />
  );

  return (
    <div ref={ref} className="relative hidden sm:block">
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        className="flex items-center gap-2 px-3 py-1.5 rounded-xl text-xs font-semibold border border-slate-700/50 bg-slate-800/40 text-slate-200 hover:bg-slate-800/70 transition-colors"
      >
        <span className="w-4 h-4 rounded bg-gradient-to-br from-violet-500 to-indigo-600 flex items-center justify-center overflow-hidden">
          {mark}
        </span>
        <span className="truncate max-w-[10rem]">{label}</span>
        <span className="text-slate-500">· {levelLabel}</span>
        {canDrill && <ChevronDown size={14} className="text-slate-500" />}
      </button>

      {open && (
        <div className="absolute right-0 mt-2 w-64 rounded-xl border border-slate-700/60 bg-slate-900/95 backdrop-blur-sm shadow-xl py-1.5 z-40">
          {selectedTenant && (
            <button
              type="button"
              onClick={() => {
                resetScope();
                setOpen(false);
              }}
              className="w-full flex items-center gap-2 px-3 py-2 text-xs text-slate-300 hover:bg-slate-800/70"
            >
              <CornerUpLeft size={14} /> Back to my scope
            </button>
          )}
          {canDrill ? (
            isLoading ? (
              <div className="px-3 py-2 text-xs text-slate-500">Loading…</div>
            ) : children.length > 0 ? (
              children.map((c) => (
                <button
                  key={c.id}
                  type="button"
                  onClick={() => {
                    drillInto(c);
                    setOpen(false);
                  }}
                  className="w-full flex items-center justify-between px-3 py-2 text-xs text-slate-200 hover:bg-slate-800/70"
                >
                  <span className="truncate">{c.name ?? '—'}</span>
                  <span className="text-slate-500">{LEVEL_LABEL[c.level]}</span>
                </button>
              ))
            ) : (
              <div className="px-3 py-2 text-xs text-slate-500">
                No child tenants
              </div>
            )
          ) : (
            <div className="px-3 py-2 text-xs text-slate-500">
              No deeper scope
            </div>
          )}
        </div>
      )}
    </div>
  );
}
