'use client';

import {
  useCallback,
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
  type ReactNode,
  type RefObject,
} from 'react';
import { createPortal } from 'react-dom';
import { useToast } from '@/components/crm/ToastProvider';
import { actionErrorText } from '@/features/contacts/ui/actions/shared';
import { isApiError } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { createTaskQueue, updateTaskQueue } from '../api.client';
import {
  MAX_TASK_QUEUE_NAME,
  TASK_QUEUE_ACCESS,
  type TaskQueue,
  type TaskQueueAccess,
} from '../types';

/** A person the queue can be shared with (an active owner of the business). */
export interface QueueUser {
  id: string;
  name: string;
  email: string;
}

const ACCESS_KEYS = Object.keys(TASK_QUEUE_ACCESS) as TaskQueueAccess[];

function Caret() {
  return (
    <svg className="tq-caret" viewBox="0 0 10 6" aria-hidden>
      <path d="M0 0h10L5 6z" fill="currentColor" />
    </svg>
  );
}

function Tick() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden>
      <path
        d="m5 12.5 4.5 4.5L19 7"
        fill="none"
        stroke="currentColor"
        strokeWidth="3"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function SmallX() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden>
      <path
        d="M18 6 6 18M6 6l12 12"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
      />
    </svg>
  );
}

export function SearchIcon() {
  return (
    <svg
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      aria-hidden
    >
      <circle cx="11" cy="11" r="7" />
      <path d="m20 20-3.5-3.5" />
    </svg>
  );
}

/**
 * The design's `DT.pop` (data-tools-common.js): a fixed `.dt-pop` under its anchor, the anchor's
 * width. `users`: the "Add users" list stays under the field (up to 380 px) and only goes above
 * it when less than 200 px are left below (task-queues.js `openUsers`).
 */
function DtPop({
  anchorRef,
  onClose,
  className,
  users = false,
  placeKey,
  children,
}: {
  anchorRef: RefObject<HTMLElement | null>;
  onClose: () => void;
  className: string;
  users?: boolean;
  /** Changes when the anchor may have moved or grown (chips added). */
  placeKey?: string;
  children: ReactNode;
}) {
  const ref = useRef<HTMLDivElement>(null);
  const [style, setStyle] = useState<React.CSSProperties>({ visibility: 'hidden' });

  useLayoutEffect(() => {
    const anchor = anchorRef.current;
    const el = ref.current;
    if (!anchor || !el) return;
    const r = anchor.getBoundingClientRect();
    const room = window.innerHeight - r.bottom - 14;
    if (users && room >= 200) {
      setStyle({
        top: r.bottom + 6,
        left: r.left,
        width: r.width,
        maxHeight: Math.min(380, room),
      });
      return;
    }
    const h = el.offsetHeight;
    let top = r.bottom + 6;
    if (top + h > window.innerHeight - 8 && r.top - h - 6 > 8) top = r.top - h - 6;
    setStyle({
      top: Math.max(8, top),
      left: Math.max(8, Math.min(r.left, window.innerWidth - r.width - 8)),
      width: r.width,
    });
  }, [anchorRef, users, placeKey]);

  useEffect(() => {
    const down = (e: MouseEvent) => {
      const target = e.target as Node;
      if (ref.current?.contains(target) || anchorRef.current?.contains(target)) return;
      onClose();
    };
    const resize = () => onClose();
    document.addEventListener('mousedown', down, true);
    window.addEventListener('resize', resize);
    return () => {
      document.removeEventListener('mousedown', down, true);
      window.removeEventListener('resize', resize);
    };
  }, [anchorRef, onClose]);

  return createPortal(
    <div
      ref={ref}
      className={cn('dt-pop', className)}
      style={style}
      data-tq-pop
      onKeyDown={(e) => {
        if (e.key === 'Escape') {
          e.preventDefault();
          e.stopPropagation();
          onClose();
          anchorRef.current?.focus();
          return;
        }
        const items = [...(ref.current?.querySelectorAll<HTMLElement>('.dt-menu__item') ?? [])];
        const i = items.indexOf(document.activeElement as HTMLElement);
        if (e.key === 'ArrowDown' && items.length) {
          e.preventDefault();
          items[(i + 1) % items.length]?.focus();
        }
        if (e.key === 'ArrowUp' && items.length) {
          e.preventDefault();
          items[i <= 0 ? items.length - 1 : i - 1]?.focus();
        }
      }}
    >
      {children}
    </div>,
    document.body,
  );
}

/**
 * Create / Edit queue (13 Nov design, task-queues.js `dialog`): name, Access type (label and
 * description), and for Shared the "Add users to queue" chip field with a searchable checkbox
 * list. Save stays off until there is a name, an access type, and for Shared a user.
 */
export function TaskQueueDialog({
  queue,
  queues,
  users,
  onClose,
  onSaved,
}: {
  /** The queue to edit; null to create one. */
  queue: TaskQueue | null;
  /** The loaded queues, for the design's duplicate-name check. */
  queues: TaskQueue[];
  users: QueueUser[];
  onClose: () => void;
  onSaved: (saved: TaskQueue) => void;
}) {
  const toast = useToast();
  const editing = queue !== null;
  const [name, setName] = useState(queue?.name ?? '');
  const [access, setAccess] = useState<TaskQueueAccess | ''>(queue?.access ?? '');
  const [userIds, setUserIds] = useState<string[]>(queue?.access === 'shared' ? queue.userIds : []);
  const [invalid, setInvalid] = useState(false);
  const [pop, setPop] = useState<'access' | 'users' | null>(null);
  const [userQuery, setUserQuery] = useState('');
  const [busy, setBusy] = useState(false);
  const nameRef = useRef<HTMLInputElement>(null);
  const accessRef = useRef<HTMLButtonElement>(null);
  const usersRef = useRef<HTMLDivElement>(null);
  const modalRef = useRef<HTMLDivElement>(null);
  const userSearchRef = useRef<HTMLInputElement>(null);

  // Shared only with teams (through the API): keeping them counts as shared with someone.
  const teamIds = queue?.access === 'shared' ? queue.teamIds : [];
  const canSave =
    !busy &&
    Boolean(name.trim()) &&
    Boolean(access) &&
    (access !== 'shared' || userIds.length + teamIds.length > 0);

  const closePop = useCallback(() => setPop(null), []);

  useEffect(() => {
    nameRef.current?.focus();
    document.body.classList.add('dt-noscroll');
    return () => document.body.classList.remove('dt-noscroll');
  }, []);

  useEffect(() => {
    if (pop === 'users') userSearchRef.current?.focus();
    if (pop === 'access') {
      const el = document.querySelector<HTMLElement>(
        '.tq-pop [aria-selected="true"], .tq-pop .tq-opt',
      );
      el?.focus();
    }
  }, [pop]);

  const save = async () => {
    if (!canSave || !access) return;
    const trimmed = name.trim();
    const dupe = queues.some(
      (q) => q.name.toLowerCase() === trimmed.toLowerCase() && q.id !== queue?.id,
    );
    if (dupe) {
      setInvalid(true);
      toast(`A queue named "${trimmed}" already exists`, 'danger');
      return;
    }
    setBusy(true);
    try {
      const shared = access === 'shared' ? userIds : [];
      const saved = editing
        ? await updateTaskQueue(queue.id, {
            ...(trimmed !== queue.name && { name: trimmed }),
            access,
            userIds: shared,
          })
        : await createTaskQueue({ name: trimmed, access, userIds: shared });
      toast(editing ? `Queue "${trimmed}" saved` : `Queue "${trimmed}" created`);
      onSaved(saved);
      onClose();
    } catch (err) {
      if (isApiError(err) && err.isConflict) {
        setInvalid(true);
        toast(`A queue named "${trimmed}" already exists`, 'danger');
      } else {
        toast(actionErrorText(err), 'danger', { durationMs: 8000 });
      }
    } finally {
      setBusy(false);
    }
  };

  const toggleUser = (id: string) =>
    setUserIds((cur) => (cur.includes(id) ? cur.filter((u) => u !== id) : [...cur, id]));
  const userName = (id: string) => users.find((u) => u.id === id)?.name ?? 'Unknown user';
  const q = userQuery.trim().toLowerCase();
  const shownUsers = users.filter((u) => !q || `${u.name} ${u.email}`.toLowerCase().includes(q));

  const onKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Escape') {
      if (pop) return;
      e.preventDefault();
      onClose();
      return;
    }
    if (e.key !== 'Tab' || !modalRef.current) return;
    const focusable = [
      ...modalRef.current.querySelectorAll<HTMLElement>(
        'button, input, select, textarea, a[href], [tabindex="0"]',
      ),
    ].filter((x) => !(x as HTMLButtonElement).disabled && x.offsetParent);
    if (!focusable.length) return;
    const first = focusable[0]!;
    const last = focusable[focusable.length - 1]!;
    if (e.shiftKey && document.activeElement === first) {
      e.preventDefault();
      last.focus();
    } else if (!e.shiftKey && document.activeElement === last) {
      e.preventDefault();
      first.focus();
    }
  };

  return createPortal(
    <div
      className="dt-modal-ov"
      onMouseDown={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
      onKeyDown={onKeyDown}
    >
      <div
        ref={modalRef}
        className="dt-modal dt-modal--tq"
        role="dialog"
        aria-modal="true"
        aria-labelledby="dtMT"
      >
        <header className="dt-modal__head">
          <h2 id="dtMT">{editing ? 'Edit queue' : 'Create queue'}</h2>
          <button type="button" className="dt-x" aria-label="Close" onClick={onClose}>
            <SmallX />
          </button>
        </header>
        <div className="dt-modal__body">
          <div className="tq-f">
            <label className="tq-f__lbl" htmlFor="tqName">
              Task queue name
            </label>
            <input
              ref={nameRef}
              className="tq-in"
              id="tqName"
              maxLength={MAX_TASK_QUEUE_NAME}
              autoComplete="off"
              aria-invalid={invalid || undefined}
              value={name}
              onChange={(e) => {
                setName(e.target.value);
                setInvalid(false);
              }}
              onKeyDown={(e) => {
                if (e.key === 'Enter' && canSave) {
                  e.preventDefault();
                  void save();
                }
              }}
            />
          </div>
          <div className="tq-f">
            <span className="tq-f__lbl" id="tqAccL">
              Access type
            </span>
            <button
              ref={accessRef}
              type="button"
              className={cn('tq-dd', !access && 'is-placeholder')}
              aria-haspopup="listbox"
              aria-expanded={pop === 'access'}
              aria-labelledby="tqAccL tqAccV"
              onClick={() => setPop((p) => (p === 'access' ? null : 'access'))}
            >
              <span id="tqAccV">
                {access ? TASK_QUEUE_ACCESS[access][0] : 'Select a queue access type'}
              </span>
              <Caret />
            </button>
            <p className="tq-f__hint" hidden={!access}>
              {access ? TASK_QUEUE_ACCESS[access][1] : ''}
            </p>
          </div>
          <div className="tq-f" hidden={access !== 'shared'}>
            <span className="tq-f__lbl" id="tqUsrL">
              Add users to queue
            </span>
            <div
              ref={usersRef}
              className="tq-dd tq-multi"
              role="button"
              tabIndex={0}
              aria-haspopup="listbox"
              aria-expanded={pop === 'users'}
              aria-labelledby="tqUsrL"
              onClick={() => {
                setUserQuery('');
                setPop((p) => (p === 'users' ? null : 'users'));
              }}
              onKeyDown={(e) => {
                if (e.target !== e.currentTarget) return;
                if (e.key === 'Enter' || e.key === ' ' || e.key === 'ArrowDown') {
                  e.preventDefault();
                  setUserQuery('');
                  setPop('users');
                }
              }}
            >
              <span className="tq-chips">
                {userIds.length ? (
                  userIds.map((id) => (
                    <span key={id} className="tq-chip">
                      {userName(id)}
                      <button
                        type="button"
                        className="tq-chip__x"
                        aria-label={`Remove ${userName(id)}`}
                        onClick={(e) => {
                          e.stopPropagation();
                          toggleUser(id);
                        }}
                      >
                        <SmallX />
                      </button>
                    </span>
                  ))
                ) : (
                  <span className="tq-ph">Search users</span>
                )}
              </span>
              <Caret />
            </div>
          </div>
        </div>
        <footer className="dt-modal__foot">
          <button
            type="button"
            className="dt-btn dt-btn--primary"
            disabled={!canSave}
            aria-busy={busy}
            onClick={() => void save()}
          >
            Save
          </button>
          <button type="button" className="dt-btn tq-cancel" onClick={onClose}>
            Cancel
          </button>
        </footer>
      </div>

      {pop === 'access' ? (
        <DtPop anchorRef={accessRef} onClose={closePop} className="tq-pop">
          <div className="tq-list" role="listbox" aria-label="Access type">
            {ACCESS_KEYS.map((k) => (
              <button
                key={k}
                type="button"
                role="option"
                className="dt-menu__item tq-opt"
                aria-selected={access === k}
                onClick={() => {
                  setAccess(k);
                  setPop(null);
                  accessRef.current?.focus();
                  if (k === 'shared' && !userIds.length) {
                    window.setTimeout(() => usersRef.current?.focus(), 30);
                  }
                }}
              >
                <b>{TASK_QUEUE_ACCESS[k][0]}</b>
                <small>{TASK_QUEUE_ACCESS[k][1]}</small>
              </button>
            ))}
          </div>
        </DtPop>
      ) : null}
      {pop === 'users' ? (
        <DtPop
          anchorRef={usersRef}
          onClose={closePop}
          className="tq-pop tq-pop--users"
          users
          placeKey={userIds.join()}
        >
          <label className="tq-psearch">
            <span className="dt-sr">Search users</span>
            <input
              ref={userSearchRef}
              type="search"
              placeholder="Search"
              autoComplete="off"
              value={userQuery}
              onChange={(e) => setUserQuery(e.target.value)}
            />
            <SearchIcon />
          </label>
          <div className="tq-ulist" role="listbox" aria-multiselectable="true" aria-label="Users">
            {shownUsers.length ? (
              shownUsers.map((u) => {
                const on = userIds.includes(u.id);
                return (
                  <button
                    key={u.id}
                    type="button"
                    role="option"
                    className={cn('tq-uopt', on && 'is-on')}
                    aria-selected={on}
                    onClick={() => toggleUser(u.id)}
                  >
                    <span className="tq-box">
                      <Tick />
                    </span>
                    <span className="tq-uopt__txt">
                      <b>{u.name}</b>
                      <small>{u.email}</small>
                    </span>
                  </button>
                );
              })
            ) : (
              <p className="tq-none">No users found</p>
            )}
          </div>
        </DtPop>
      ) : null}
    </div>,
    document.body,
  );
}
