'use client';

import Link from 'next/link';
import { useEffect, useRef, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { mapLimited } from '@/lib/utils/map-limited';
import { completeTask, getTask } from '../api.client';
import {
  DEFAULT_QUEUE_PAGE_SIZE,
  pageOfIndex,
  pagerWindow,
  QUEUE_PAGE_SIZES,
  queuePages,
  queueProgress,
  type QueuePageSize,
} from '../taskQueuePanel';
import { taskPageHref } from '../taskQueue';
import type { Task } from '../types';

type Row = { id: string; title: string; company: string; done: boolean; canEdit: boolean };

const rowOf = (task: Task): Row => ({
  id: task.id,
  title: task.title,
  company: task.links.find((l) => l.objectType === 'company')?.displayName ?? '',
  done: task.status === 'completed',
  canEdit: task.canEdit !== false,
});

const ListIcon = () => (
  <svg
    width="18"
    height="18"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="1.8"
    strokeLinecap="round"
    aria-hidden
  >
    <path d="M9 6h11M9 12h11M9 18h11M4 6l1 1 2-2M4 12l1 1 2-2M4 18l1 1 2-2" />
  </svg>
);
const CheckIcon = () => (
  <svg
    width="18"
    height="18"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
    strokeLinecap="round"
    strokeLinejoin="round"
    aria-hidden
  >
    <path d="m5 12 5 5 9-10" />
  </svg>
);

/**
 * TKB-b: the task queue side panel (26 Nov design task-record.php:116-141, task-record.js
 * :282-364): "Tasks", "n of N completed or rescheduled" with its bar, the queue's tasks (each
 * opens its page in the queue; its round check completes it), and the pager with 25 / 50 / 100
 * per page. The tasks are read when it opens; one that no longer loads (deleted, or no longer
 * visible) is left out. From 1400px it sits beside the page; narrower, over it with a backdrop.
 */
export function TaskQueuePanel({
  id,
  open,
  overlay,
  ids,
  currentId,
  currentDone,
  moved,
  canWrite,
  onClose,
  onCompleteCurrent,
}: {
  id: string;
  open: boolean;
  /** Narrower than 1400px: over the page, closed by the backdrop, Escape or opening a task. */
  overlay: boolean;
  ids: readonly string[];
  currentId: string;
  /** The page's own task was completed (the bar's Complete). */
  currentDone: boolean;
  /** Tasks rescheduled while the queue runs (design `moved`). */
  moved: ReadonlySet<string>;
  canWrite: boolean;
  onClose: (focusToggle: boolean) => void;
  /** Completing the page's own task goes through the bar's Complete (design :340). */
  onCompleteCurrent: () => void;
}) {
  const toast = useToast();
  const [rows, setRows] = useState<Row[] | null>(null);
  const [per, setPer] = useState<QueuePageSize>(DEFAULT_QUEUE_PAGE_SIZE);
  const [page, setPage] = useState(1);
  const [perOpen, setPerOpen] = useState(false);
  const [busyId, setBusyId] = useState<string | null>(null);
  const listRef = useRef<HTMLUListElement>(null);
  const perRef = useRef<HTMLDivElement>(null);

  const idsKey = ids.join(',');
  useEffect(() => {
    if (!open) return;
    let alive = true;
    void mapLimited([...ids], 6, (taskId) => getTask(taskId).then(rowOf, () => null)).then(
      (loaded) => {
        if (alive) setRows(loaded.filter((r): r is Row => r !== null));
      },
    );
    return () => {
      alive = false;
    };
    // `idsKey` stands for the queue; the panel reads it again each time it opens.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, idsKey]);

  const shown = (rows ?? []).map((r) =>
    r.id === currentId && currentDone ? { ...r, done: true } : r,
  );
  const currentIndex = Math.max(
    0,
    shown.findIndex((r) => r.id === currentId),
  );
  // Opening, or a new page size, shows the page holding the current task (design :333, :353).
  useEffect(() => {
    if (open) setPage(pageOfIndex(currentIndex, per));
  }, [open, per, currentIndex]);
  useEffect(() => {
    if (open) listRef.current?.querySelector('.is-cur')?.scrollIntoView({ block: 'nearest' });
  }, [open, page, rows]);
  useEffect(() => {
    if (!perOpen) return;
    const down = (e: MouseEvent) => {
      if (!perRef.current?.contains(e.target as Node)) setPerOpen(false);
    };
    document.addEventListener('mousedown', down);
    return () => document.removeEventListener('mousedown', down);
  }, [perOpen]);

  const pages = queuePages(shown.length, per);
  const from = (page - 1) * per;
  const handled = shown.filter((r) => r.done || moved.has(r.id)).length;
  const progress = queueProgress(handled, shown.length);

  const complete = async (row: Row) => {
    if (row.done || busyId) return;
    if (row.id === currentId) {
      onCompleteCurrent();
      return;
    }
    setBusyId(row.id);
    try {
      await completeTask(row.id);
      setRows((cur) => cur?.map((r) => (r.id === row.id ? { ...r, done: true } : r)) ?? cur);
      toast('Task marked as completed');
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 8000 });
    } finally {
      setBusyId(null);
    }
  };

  const pg = (label: string, to: number, text: string, disabled: boolean) => (
    <button
      type="button"
      className="trk-nav__pg"
      aria-label={label}
      disabled={disabled}
      onClick={() => {
        setPage(to);
        if (listRef.current) listRef.current.scrollTop = 0;
      }}
    >
      {text}
    </button>
  );

  return (
    <>
      {overlay && open ? (
        <div className="trk-nav__back" onClick={() => onClose(true)} aria-hidden="true" />
      ) : null}
      <aside
        className="trk-nav"
        id={id}
        aria-label="Task queue"
        hidden={!open}
        onKeyDown={(e) => {
          if (e.key !== 'Escape') return;
          if (perOpen) {
            e.stopPropagation();
            setPerOpen(false);
          } else if (overlay) {
            e.stopPropagation();
            onClose(true);
          }
        }}
      >
        <div className="trk-nav__head">
          <h2 className="trk-nav__title">Tasks</h2>
          <p className="trk-nav__count">{progress.text}</p>
          <div
            className="trk-nav__bar"
            role="progressbar"
            aria-valuemin={0}
            aria-valuemax={100}
            aria-valuenow={Math.round(progress.pct)}
            aria-label="Queue progress"
          >
            <span style={{ width: handled ? `max(6px, ${progress.pct}%)` : 0 }} />
          </div>
        </div>
        <ul className="trk-nav__list" ref={listRef}>
          {rows === null ? <li className="trk-nav__item crm-p-3">Loading…</li> : null}
          {shown.slice(from, from + per).map((r) => {
            const cur = r.id === currentId;
            const locked = !canWrite || !r.canEdit;
            return (
              <li key={r.id} className={cn('trk-nav__item', cur && 'is-cur')}>
                <Link
                  className="trk-nav__link"
                  href={taskPageHref(r.id, true)}
                  aria-current={cur ? 'true' : undefined}
                  onClick={() => {
                    if (overlay) onClose(false);
                  }}
                >
                  <span className="trk-nav__ico">
                    <ListIcon />
                  </span>
                  <span className="trk-nav__txt">
                    <strong>{r.title}</strong>
                    <small>{r.company || '--'}</small>
                  </span>
                </Link>
                <button
                  type="button"
                  className={cn('trk-nav__chk', r.done && 'is-done')}
                  aria-label={`${r.done ? 'Completed' : 'Mark complete'}: ${r.title}`}
                  aria-pressed={r.done}
                  disabled={r.done || locked || busyId !== null}
                  onClick={() => void complete(r)}
                >
                  {r.done ? <CheckIcon /> : null}
                </button>
              </li>
            );
          })}
        </ul>
        <div className="trk-nav__foot">
          <nav className="trk-nav__pager" aria-label="Task pages">
            {pg('First page', 1, '«', page === 1)}
            {pg('Previous page', page - 1, '‹', page === 1)}
            {pagerWindow(page, pages).map((n) => (
              <button
                key={n}
                type="button"
                className={cn('trk-nav__pg trk-nav__pg--n', n === page && 'is-on')}
                aria-current={n === page ? 'page' : undefined}
                aria-label={`Page ${n}`}
                onClick={() => setPage(n)}
              >
                {n}
              </button>
            ))}
            {pg('Next page', page + 1, '›', page === pages)}
            {pg('Last page', pages, '»', page === pages)}
          </nav>
          <div className="trk-nav__per" ref={perRef}>
            <button
              type="button"
              className="trk-nav__perbtn"
              aria-haspopup="listbox"
              aria-expanded={perOpen}
              onClick={() => setPerOpen((o) => !o)}
            >
              <span>{per} per page</span>
              <svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor" aria-hidden>
                <path d="M5 8h14l-7 9z" />
              </svg>
            </button>
            {perOpen ? (
              <ul className="trk-nav__permenu" role="listbox">
                {QUEUE_PAGE_SIZES.map((n) => (
                  <li
                    key={n}
                    role="option"
                    aria-selected={n === per}
                    onClick={() => {
                      setPer(n);
                      setPerOpen(false);
                    }}
                  >
                    {n} per page
                  </li>
                ))}
              </ul>
            ) : null}
          </div>
        </div>
      </aside>
    </>
  );
}
