'use client';

import { useEffect, useMemo, useRef, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import type { BusinessSummary, Role } from '@/types/api';

/**
 * The account section of the profile menu (HubSpot's "Account" block and "All accounts" list):
 * the business you are in, and, when you belong to others, a "Switch account" list of all of
 * them (the current one ticked, a search above 5). Each business has a coloured initial so the
 * accounts are told apart at a glance. Switching reloads the app in the other business; the
 * next page shows "Switched to …".
 */

/** sessionStorage key: the business just switched to, shown once after the reload. */
const SWITCHED_KEY = 'crm:switched-to';
/** Above this many accounts the list gets a search box. */
const SEARCH_FROM = 6;
/** Badge colours (design tokens), picked per business so each keeps its colour. */
const TONES = ['indigo', 'teal', 'orange', 'pink', 'cyan', 'yellow'] as const;

function toneOf(id: string): (typeof TONES)[number] {
  let h = 0;
  for (const c of id) h = (h * 31 + c.charCodeAt(0)) >>> 0;
  return TONES[h % TONES.length]!;
}

export function AccountBadge({
  business,
  size = 'sm',
}: {
  business: BusinessSummary;
  size?: 'sm' | 'md';
}) {
  const initial = business.name.trim().charAt(0).toUpperCase() || '?';
  return (
    <span
      className={`account-badge account-badge--${size} account-badge--${toneOf(business.id)}`}
      aria-hidden
    >
      {initial}
    </span>
  );
}

/** Remembers the account switched to, so the reloaded page can say so. */
export function rememberSwitch(name: string) {
  try {
    sessionStorage.setItem(SWITCHED_KEY, name);
  } catch {
    // Storage blocked: the switch still works, only the message is skipped.
  }
}

/** Shows "Switched to …" once after a switch (the app reloads in the new business). */
export function useSwitchedToast() {
  const toast = useToast();
  useEffect(() => {
    let name: string | null = null;
    try {
      name = sessionStorage.getItem(SWITCHED_KEY);
      if (name) sessionStorage.removeItem(SWITCHED_KEY);
    } catch {
      return;
    }
    if (name) toast(`Switched to ${name}`, 'success');
  }, [toast]);
}

export function AccountSwitcher({
  current,
  role,
  memberships,
  switching,
  onSwitch,
}: {
  current: BusinessSummary;
  role: Role;
  memberships: Array<{ business: BusinessSummary; role: Role }>;
  switching: boolean;
  onSwitch: (business: BusinessSummary) => void;
}) {
  const [open, setOpen] = useState(false);
  const [query, setQuery] = useState('');
  const searchRef = useRef<HTMLInputElement>(null);
  const firstItemRef = useRef<HTMLButtonElement>(null);

  const accounts = useMemo(() => {
    const all = memberships.map((m) => m.business);
    if (!all.some((b) => b.id === current.id)) all.unshift(current);
    return all.sort((a, b) =>
      a.id === current.id ? -1 : b.id === current.id ? 1 : a.name.localeCompare(b.name),
    );
  }, [memberships, current]);
  const canSwitch = accounts.length > 1;
  const searchable = accounts.length >= SEARCH_FROM;
  const q = query.trim().toLowerCase();
  const shown = q
    ? accounts.filter((b) => b.name.toLowerCase().includes(q) || b.slug.toLowerCase().includes(q))
    : accounts;

  // Opening the list moves focus into it, so keyboard users land on the accounts.
  useEffect(() => {
    if (!open) return;
    (searchable ? searchRef.current : firstItemRef.current)?.focus();
  }, [open, searchable]);

  const roleLabel = role === 'admin' ? 'Admin' : role === 'read_only' ? 'Read only' : 'Standard';

  return (
    <div className="dropdown__section dropdown__section--muted account-switcher">
      <p className="dropdown__eyebrow">Account</p>
      <div className="account-switcher__current">
        <AccountBadge business={current} size="md" />
        <div className="crm-overflow-hidden">
          <p className="account-meta__name">{current.name}</p>
          <p className="account-meta__id">
            {current.slug} · {roleLabel}
          </p>
        </div>
      </div>

      {canSwitch ? (
        <button
          type="button"
          className="dropdown__item account-switcher__toggle"
          role="menuitem"
          aria-expanded={open}
          aria-controls="account-switcher-list"
          onClick={() => {
            setOpen((v) => !v);
            setQuery('');
          }}
        >
          <span>Switch account</span>
          <span className="account-switcher__count">{accounts.length}</span>
          <svg
            className={`icon iconSize-16 account-switcher__chevron${open ? 'is-open' : ''}`}
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
            aria-hidden
          >
            <path d="m9 6 6 6-6 6" />
          </svg>
        </button>
      ) : null}

      {canSwitch && open ? (
        <div className="account-switcher__panel" id="account-switcher-list">
          <p className="account-switcher__title">All accounts</p>
          {searchable ? (
            <input
              ref={searchRef}
              type="search"
              className="account-switcher__search"
              placeholder="Search accounts"
              aria-label="Search accounts"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === 'ArrowDown') {
                  e.preventDefault();
                  firstItemRef.current?.focus();
                }
              }}
            />
          ) : null}
          <ul className="account-switcher__list" role="group" aria-label="All accounts">
            {shown.map((b, i) => {
              const isCurrent = b.id === current.id;
              return (
                <li key={b.id}>
                  <button
                    ref={i === 0 ? firstItemRef : undefined}
                    type="button"
                    className={`dropdown__item account-switcher__item${isCurrent ? 'is-current' : ''}`}
                    role="menuitemradio"
                    aria-checked={isCurrent}
                    disabled={switching}
                    onClick={() => (isCurrent ? setOpen(false) : onSwitch(b))}
                  >
                    <AccountBadge business={b} />
                    <span className="account-switcher__name">
                      <span>{b.name}</span>
                      <small>{b.slug}</small>
                    </span>
                    {isCurrent ? (
                      <svg
                        className="icon iconSize-16 account-switcher__check"
                        width="16"
                        height="16"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="2.25"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        aria-hidden
                      >
                        <path d="M20 6 9 17l-5-5" />
                      </svg>
                    ) : null}
                  </button>
                </li>
              );
            })}
            {shown.length === 0 ? (
              <li className="account-switcher__empty">No account matches “{query.trim()}”</li>
            ) : null}
          </ul>
          {switching ? (
            <p className="account-switcher__status" role="status">
              Switching…
            </p>
          ) : null}
        </div>
      ) : null}
    </div>
  );
}
