'use client';

/**
 * The conversation's Owner row and picker (inbox-hs.js renderThread `.ix-owner`, ownerPicker).
 * Email in the user's own mailbox is private, so it can be assigned to the user or to nobody.
 * In a team inbox it can go to the inbox's members or to one of its teams, with the "Reassign
 * conversations" permission. HUB-366.
 */
import { useCallback, useRef, useState } from 'react';
import { cn } from '@/lib/utils/cn';
import { IxIcon, IxPopover, Tri, ixInitials } from './ix';

export const ASSIGN_PERSONAL =
  'Your own email is private. Teammates can be assigned in a team inbox.';
export const ASSIGN_NEEDS_PERMISSION =
  'You need the “Reassign conversations” permission to give conversations to others';

type Team = { id: string; name: string };

interface PickerProps {
  /** The current owner; null for several conversations at once. */
  assignee: { id: string; name: string } | null;
  assigneeTeam?: Team | null;
  me: { id: string; name: string };
  /** The others it could go to. */
  teammates: { id: string; name: string; email: string }[];
  /** The team inbox's teams it could go to. */
  teams?: Team[];
  /** Why they can't be picked; null: they can. */
  othersWhy: string | null;
  /** It is someone else's, and I may not move it. */
  locked?: boolean;
  /** Whether "Unassign" has something to do. */
  canUnassign: boolean;
  /** Why it can't be unassigned; null: it can. */
  unassignWhy?: string | null;
  onAssign: (userId: string | null) => void;
  onAssignTeam?: (teamId: string) => void;
}

/** The list of whom a conversation can go to, in the design's order: me, a team, a teammate. */
export function OwnerPicker({
  anchor,
  onClose,
  assignee,
  assigneeTeam,
  me,
  teammates,
  teams = [],
  othersWhy,
  locked = false,
  canUnassign,
  unassignWhy = null,
  onAssign,
  onAssignTeam,
}: PickerProps & { anchor: HTMLElement | null; onClose: () => void }) {
  const [q, setQ] = useState('');
  const ql = q.trim().toLowerCase();
  const matches = (name: string) => !ql || name.toLowerCase().includes(ql);
  const meShown = matches(me.name);
  const others = teammates.filter((u) => u.id !== me.id && matches(u.name));
  const teamHits = teams.filter((t) => matches(t.name));
  const pick = (id: string | null) => {
    onClose();
    onAssign(id);
  };

  return (
    <IxPopover
      anchor={anchor}
      onClose={onClose}
      className="ix-pop--owner"
      role="dialog"
      label="Assign conversation"
    >
      <label className="ix-psearch">
        <span className="crm-visually-hidden">Search for a specific user or team</span>
        <input
          type="search"
          placeholder={
            teams.length ? 'Search for a specific user or team' : 'Search for a specific user'
          }
          autoComplete="off"
          autoFocus
          value={q}
          onChange={(e) => setQ(e.target.value)}
        />
        <IxIcon name="search" className="ix-i--sm" />
      </label>
      <div className="ix-own">
        <div className="ix-own__top">
          <button
            type="button"
            className="ix-pill ix-pill--xs"
            disabled={!canUnassign || locked || !!unassignWhy}
            title={locked ? ASSIGN_NEEDS_PERMISSION : (unassignWhy ?? undefined)}
            onClick={() => pick(null)}
          >
            Unassign
          </button>
        </div>
        {meShown ? (
          <button
            type="button"
            role="menuitem"
            className={cn('ix-mi ix-mi--user', assignee?.id === me.id && 'is-cur')}
            disabled={locked}
            title={locked ? ASSIGN_NEEDS_PERMISSION : undefined}
            onClick={() => pick(me.id)}
          >
            <span className="ix-av ix-av--sm">{ixInitials(me.name)}</span>
            <span>
              <strong>{me.name} (you)</strong>
            </span>
            {assignee?.id === me.id ? <IxIcon name="check" className="ix-i--sm" /> : null}
          </button>
        ) : null}
        {teamHits.length && onAssignTeam ? (
          <>
            <p className="ix-pop__h">Assign to a team</p>
            {teamHits.map((t) => (
              <button
                key={t.id}
                type="button"
                role="menuitem"
                className={cn('ix-mi ix-mi--user', assigneeTeam?.id === t.id && 'is-cur')}
                disabled={!!othersWhy}
                aria-disabled={!!othersWhy}
                title={othersWhy ?? undefined}
                onClick={() => {
                  onClose();
                  onAssignTeam(t.id);
                }}
              >
                <span className="ix-av ix-av--sm">{ixInitials(t.name)}</span>
                <span>
                  <strong>{t.name}</strong>
                  <small>Team</small>
                </span>
                {assigneeTeam?.id === t.id ? <IxIcon name="check" className="ix-i--sm" /> : null}
              </button>
            ))}
          </>
        ) : null}
        {others.length ? (
          <>
            <p className="ix-pop__h">Assign to another user</p>
            {othersWhy ? <p className="ix-none">{othersWhy}</p> : null}
            {others.map((u) => (
              <button
                key={u.id}
                type="button"
                role="menuitem"
                className={cn('ix-mi ix-mi--user', assignee?.id === u.id && 'is-cur')}
                disabled={!!othersWhy}
                aria-disabled={!!othersWhy}
                title={othersWhy ?? undefined}
                onClick={() => pick(u.id)}
              >
                <span className="ix-av ix-av--sm">{ixInitials(u.name)}</span>
                <span>
                  <strong>{u.name}</strong>
                  <small>{u.email}</small>
                </span>
                {assignee?.id === u.id ? <IxIcon name="check" className="ix-i--sm" /> : null}
              </button>
            ))}
          </>
        ) : null}
        {!meShown && !others.length && !teamHits.length ? (
          <p className="ix-none">No users match &ldquo;{q}&rdquo;</p>
        ) : null}
      </div>
    </IxPopover>
  );
}

export function ThreadOwner({
  subject,
  busy,
  children,
  ...picker
}: Omit<PickerProps, 'canUnassign'> & {
  subject: string;
  busy: boolean;
  /** Beside the Owner picker: the conversation's status. */
  children?: React.ReactNode;
}) {
  const btnRef = useRef<HTMLButtonElement>(null);
  const [open, setOpen] = useState(false);
  const close = useCallback(() => setOpen(false), []);
  const { assignee, assigneeTeam } = picker;
  const owner = assignee?.name ?? assigneeTeam?.name ?? null;

  return (
    <div className="ix-owner">
      <div>
        <span className="ix-owner__l">Owner</span>
        <button
          ref={btnRef}
          type="button"
          className="ix-owner__btn"
          aria-haspopup="dialog"
          aria-expanded={open}
          disabled={busy}
          onClick={() => setOpen((v) => !v)}
        >
          <span className={cn('ix-av ix-av--xs', !owner && 'is-none')}>
            {owner ? ixInitials(owner) : <IxIcon name="user" className="ix-i--xs" />}
          </span>
          {owner ?? 'No owner'}
          <Tri />
        </button>
      </div>
      {children}
      <span className="ix-owner__sub" title={subject}>
        {subject}
      </span>

      {open ? (
        <OwnerPicker {...picker} anchor={btnRef.current} onClose={close} canUnassign={!!owner} />
      ) : null}
    </div>
  );
}
