'use client';

/**
 * The Inbox's left menu, as the design draws it (inbox-hs.js renderRail), with the report's
 * "Waiting on contact" and "Waiting on us" views. HUB-366.
 *
 * Chat, Email, Forms and Calls are the open conversations that began that way; chat, forms and
 * calls arrive in team inboxes only. Spam and Trash are the CRM's own: Gmail is not changed.
 */
import Link from 'next/link';
import { useCallback, useRef, useState } from 'react';
import { cn } from '@/lib/utils/cn';
import type { Availability } from '../api.client';
import type { InboxChannel, InboxThreadBox, InboxThreadCounts, InboxThreadStatus } from '../types';
import type { AlertChoices } from '../useNewMailAlerts';
import { IxIcon, IxPopover, Tri } from './ix';

export type InboxViewId = 'all' | 'unassigned' | 'mine';

/** What a view of the menu lists. */
export interface InboxViewChoice {
  view: InboxViewId;
  status: InboxThreadStatus;
  box: InboxThreadBox;
  sent: boolean;
  /** Only conversations that began this way. */
  channel: InboxChannel | undefined;
}

const SOON = 'Coming soon';

const TEAM_ONLY = 'Chat, forms and calls arrive in team inboxes';

type CountKey = Exclude<keyof InboxThreadCounts, 'byChannel'>;

interface Item {
  label: string;
  /** What choosing it shows. */
  select: InboxViewChoice;
  count: CountKey | InboxChannel;
  /** Only a team inbox has anything to show here. */
  teamOnly?: boolean;
  /** Hidden while the design's "More" is folded. */
  more?: boolean;
}

const choice = (change: Partial<InboxViewChoice> = {}): InboxViewChoice => ({
  view: 'all',
  status: 'open',
  box: 'inbox',
  sent: false,
  channel: undefined,
  ...change,
});

const ITEMS: Item[] = [
  { label: 'Unassigned', select: choice({ view: 'unassigned' }), count: 'unassigned' },
  { label: 'Assigned to me', select: choice({ view: 'mine' }), count: 'mine' },
  { label: 'All open', select: choice(), count: 'open' },
  {
    label: 'Waiting on contact',
    select: choice({ status: 'waiting_on_contact' }),
    count: 'waitingOnContact',
  },
  { label: 'Waiting on us', select: choice({ status: 'waiting_on_us' }), count: 'waitingOnUs' },
  { label: 'Chat', select: choice({ channel: 'chat' }), count: 'chat', teamOnly: true },
  { label: 'Email', select: choice({ channel: 'email' }), count: 'email', more: true },
  {
    label: 'Forms',
    select: choice({ channel: 'form' }),
    count: 'form',
    teamOnly: true,
    more: true,
  },
  {
    label: 'Calls',
    select: choice({ channel: 'call' }),
    count: 'call',
    teamOnly: true,
    more: true,
  },
  { label: 'All closed', select: choice({ status: 'closed' }), count: 'closed', more: true },
  { label: 'Sent', select: choice({ sent: true }), count: 'sent', more: true },
  { label: 'Spam', select: choice({ box: 'spam' }), count: 'spam', more: true },
  { label: 'Trash', select: choice({ box: 'trash' }), count: 'trash', more: true },
];

const isChannel = (key: CountKey | InboxChannel): key is InboxChannel =>
  key === 'email' || key === 'chat' || key === 'form' || key === 'call';

const countOf = (counts: InboxThreadCounts, key: CountKey | InboxChannel) =>
  isChannel(key) ? counts.byChannel[key] : counts[key];

export function InboxRail({
  current,
  inboxes,
  inbox,
  onInbox,
  canSetUpTeams,
  onLogCall,
  counts,
  searching,
  canManageSettings,
  availability,
  onAvailability,
  alerts,
  onToggleAlert,
  onSelect,
  onHide,
  onSearch,
  onCompose,
}: {
  current: InboxViewChoice;
  /** The team inboxes I may open. */
  inboxes: { id: string; name: string }[];
  /** The open team inbox; absent: my own email. */
  inbox: string | undefined;
  onInbox: (id: string | undefined) => void;
  canSetUpTeams: boolean;
  /** Absent: the open inbox takes no calls. */
  onLogCall?: () => void;
  counts: InboxThreadCounts | null;
  searching: boolean;
  canManageSettings: boolean;
  /** Null while it is not known. */
  availability: Availability | null;
  onAvailability: (next: Availability) => void;
  alerts: AlertChoices;
  onToggleAlert: (key: keyof AlertChoices) => void;
  onSelect: (next: InboxViewChoice) => void;
  onHide: () => void;
  onSearch: (on: boolean) => void;
  onCompose: () => void;
}) {
  const [more, setMore] = useState(true);
  const [menu, setMenu] = useState<'inboxes' | 'avail' | 'actions' | null>(null);
  const inboxesRef = useRef<HTMLButtonElement>(null);
  const availRef = useRef<HTMLButtonElement>(null);
  const actionsRef = useRef<HTMLButtonElement>(null);
  const close = useCallback(() => setMenu(null), []);
  const toggle = (next: 'inboxes' | 'avail' | 'actions') =>
    setMenu((m) => (m === next ? null : next));

  // The Open / Closed toggle narrows Unassigned and Assigned to me, which stay marked.
  const isCurrent = ({ select }: Item) =>
    !searching &&
    select.channel === current.channel &&
    select.view === current.view &&
    select.box === current.box &&
    select.sent === current.sent &&
    (select.view === 'unassigned' || select.view === 'mine' || select.status === current.status);
  const away = availability === 'away';

  const menuButtons = (
    <>
      <button
        type="button"
        className="ix-icon ix-tip"
        data-tip="Hide sidebar"
        aria-label="Hide sidebar"
        onClick={onHide}
      >
        <IxIcon name="dleft" />
      </button>
      <button
        ref={inboxesRef}
        type="button"
        className="ix-inboxbtn"
        aria-haspopup="menu"
        aria-expanded={menu === 'inboxes'}
        onClick={() => toggle('inboxes')}
      >
        <span className="ix-inboxbtn__t">
          {inboxes.find((i) => i.id === inbox)?.name ?? 'Inbox'}
        </span>
        <Tri />
      </button>
      <button
        type="button"
        className={cn('ix-icon ix-tip ix-rail__search', searching && 'is-on')}
        data-tip={searching ? 'Close search' : 'Search'}
        aria-label={searching ? 'Close search' : 'Search Inbox'}
        aria-pressed={searching}
        onClick={() => onSearch(!searching)}
      >
        <IxIcon name={searching ? 'x' : 'search'} />
      </button>
    </>
  );

  return (
    <nav className="ix-rail" aria-label="Inbox views">
      <div className="ix-rail__top">{menuButtons}</div>
      <div className="ix-avail">
        <button
          ref={availRef}
          type="button"
          className="ix-avail__btn"
          aria-haspopup="menu"
          aria-expanded={menu === 'avail'}
          onClick={() => toggle('avail')}
        >
          <span className={cn('ix-dot', availability !== 'available' && 'is-away')} />
          {availability === null ? 'Availability' : away ? 'You’re away' : 'You’re available'}
          <Tri />
        </button>
      </div>
      <ul className="ix-views">
        {ITEMS.map((item) => (
          <li key={item.label}>
            {item.label === 'Email' ? (
              <button
                type="button"
                className="ix-less"
                aria-expanded={more}
                onClick={() => setMore((v) => !v)}
              >
                <IxIcon name="chev" className={more ? undefined : 'is-rot'} />
                {more ? 'Less' : 'More'}
              </button>
            ) : null}
            {!item.more || more ? (
              <button
                type="button"
                className={cn(isCurrent(item) && 'is-active')}
                aria-current={isCurrent(item) ? 'page' : undefined}
                disabled={!!item.teamOnly && !inbox}
                title={item.teamOnly && !inbox ? TEAM_ONLY : undefined}
                onClick={() => onSelect(item.select)}
              >
                <span>{item.label}</span>
                {counts && !(item.teamOnly && !inbox) ? <b>{countOf(counts, item.count)}</b> : null}
              </button>
            ) : null}
          </li>
        ))}
      </ul>
      <div className="ix-rail__foot">
        <div className="ix-rail__btns">
          <button
            ref={actionsRef}
            type="button"
            className="ix-pill"
            aria-haspopup="menu"
            aria-expanded={menu === 'actions'}
            onClick={() => toggle('actions')}
          >
            Actions
            <Tri />
          </button>
          <button type="button" className="ix-pill" onClick={onCompose}>
            Compose
          </button>
        </div>
        {canManageSettings || canSetUpTeams ? (
          <Link className="ix-settings" href="/settings/inboxes">
            <IxIcon name="gear" className="ix-i--sm" />
            Inbox Settings
          </Link>
        ) : null}
      </div>

      {menu === 'inboxes' ? (
        <IxPopover
          anchor={inboxesRef.current}
          onClose={close}
          className="ix-pop--inboxes"
          label="Inboxes"
        >
          {[{ id: undefined, name: 'Inbox (my email)' }, ...inboxes].map((item) => (
            <button
              key={item.id ?? 'mine'}
              type="button"
              role="menuitemradio"
              aria-checked={item.id === inbox}
              className="ix-mi"
              onClick={() => {
                close();
                onInbox(item.id);
              }}
            >
              {item.name}
              {item.id === inbox ? <IxIcon name="check" className="ix-i--sm ix-mi__ok" /> : null}
            </button>
          ))}
          {!inboxes.length ? <p className="ix-none">No team inboxes yet</p> : null}
          {canSetUpTeams ? (
            <Link className="ix-mi" role="menuitem" href="/settings/inboxes">
              Set up team inboxes
            </Link>
          ) : null}
        </IxPopover>
      ) : null}
      {menu === 'avail' ? (
        <IxPopover
          anchor={availRef.current}
          onClose={close}
          className="ix-pop--avail"
          label="Availability"
        >
          <button
            type="button"
            role="menuitem"
            className="ix-mi"
            disabled={availability === null}
            onClick={() => {
              close();
              onAvailability(away ? 'available' : 'away');
            }}
          >
            <span className={cn('ix-dot', !away && 'is-away')} />
            {away ? 'Set as available' : 'Set as away'}
          </button>
          <Link className="ix-mi" role="menuitem" href="/settings/availability-management">
            Manage working hours and availability
          </Link>
        </IxPopover>
      ) : null}
      {menu === 'actions' ? (
        <IxPopover anchor={actionsRef.current} onClose={close} label="Inbox actions">
          {onLogCall ? (
            <button
              type="button"
              role="menuitem"
              className="ix-mi"
              onClick={() => {
                close();
                onLogCall();
              }}
            >
              Log a call
            </button>
          ) : null}
          <Link className="ix-mi" role="menuitem" href="/settings/availability-management">
            Manage team availability
          </Link>
          {(
            [
              ['sound', 'Sound on new email'],
              ['desktop', 'Desktop notifications'],
            ] as const
          ).map(([key, label]) => (
            <button
              key={key}
              type="button"
              role="menuitemcheckbox"
              aria-checked={alerts[key]}
              className="ix-mi"
              onClick={() => onToggleAlert(key)}
            >
              {label}
              {alerts[key] ? <IxIcon name="check" className="ix-i--sm ix-mi__ok" /> : null}
            </button>
          ))}
          <button type="button" role="menuitem" className="ix-mi" disabled title={SOON}>
            Create a view · {SOON}
          </button>
          {canManageSettings ? (
            <Link className="ix-mi" role="menuitem" href="/settings/channels">
              Connect a channel
            </Link>
          ) : null}
        </IxPopover>
      ) : null}
    </nav>
  );
}
