'use client';

import { useEffect, useMemo, useState, type ReactNode } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { useToast } from '@/components/crm/ToastProvider';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  createPlaybookFolder,
  deletePlaybook,
  deletePlaybookFolder,
  getPlaybook,
  renamePlaybookFolder,
  updatePlaybook,
} from '../api.client';
import { deleteCopy, moveMessage, questionDesc, type DeleteTarget } from '../listModel';
import type { Playbook, PlaybookFolder, PlaybookSummary, PlaybookVisibility } from '../types';

/**
 * PB3: the Playbooks list's modals, as the 28 Oct design (playbooks.php:380-536): New / Edit
 * folder, Move to folder, Delete, Manage sharing and the Preview drawer. Escape and a click on
 * the backdrop close them (playbooks.js:103-111).
 */
export function PblModal({
  id,
  title,
  titleClass,
  role = 'dialog',
  className,
  drawer = false,
  onClose,
  children,
  footer,
}: {
  id: string;
  title: ReactNode;
  titleClass?: string;
  role?: 'dialog' | 'alertdialog';
  className?: string;
  drawer?: boolean;
  onClose: () => void;
  children: ReactNode;
  footer?: ReactNode;
}) {
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key !== 'Escape') return;
      e.stopPropagation();
      onClose();
    };
    document.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = prev;
    };
  }, [onClose]);
  const titleId = `${id}Title`;
  return (
    <div
      className={cn('modal-backdrop is-open', drawer && 'modal-backdrop--drawer')}
      id={id}
      role={role}
      aria-modal="true"
      aria-labelledby={titleId}
      onMouseDown={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div className={cn('modal', className ?? 'pbl-modal')}>
        <div className="modal__header">
          <h2 className={cn('modal__title', titleClass)} id={titleId}>
            {title}
          </h2>
          <button type="button" className="modal__close" aria-label="Close" onClick={onClose}>
            <CrmIcon name="x" className="iconSize-18" />
          </button>
        </div>
        {children}
        {footer}
      </div>
    </div>
  );
}

const cleanName = (s: string) => s.replace(/\s+/g, ' ').trim();
const DUPLICATE = 'A folder with this name already exists.';
const isConflict = (err: unknown) =>
  (err as { response?: { status?: number } })?.response?.status === 409;

/** New folder / Edit folder (playbooks.js:368-392). */
export function FolderDialog({
  folder,
  folders,
  onClose,
  onSaved,
}: {
  folder: PlaybookFolder | null;
  folders: PlaybookFolder[];
  onClose: () => void;
  onSaved: (folder: PlaybookFolder) => void;
}) {
  const toast = useToast();
  const [name, setName] = useState(folder?.name ?? '');
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  const submit = async () => {
    const value = cleanName(name);
    if (!value) return setError('Enter a folder name.');
    if (folders.some((f) => f.id !== folder?.id && f.name.toLowerCase() === value.toLowerCase())) {
      return setError(DUPLICATE);
    }
    setBusy(true);
    try {
      const saved = folder
        ? await renamePlaybookFolder(folder.id, value)
        : await createPlaybookFolder(value);
      toast(folder ? 'Folder renamed' : 'Folder created');
      onSaved(saved);
    } catch (err) {
      if (isConflict(err)) setError(DUPLICATE);
      else toast(errorText(err), 'danger');
    } finally {
      setBusy(false);
    }
  };

  return (
    <PblModal id="pblFolderModal" title={folder ? 'Edit folder' : 'New folder'} onClose={onClose}>
      <form
        className="modal__body"
        noValidate
        onSubmit={(e) => {
          e.preventDefault();
          void submit();
        }}
      >
        <div className={cn('field', error && 'is-invalid')}>
          <label className="field__label" htmlFor="pblFolderName">
            Folder Name:
          </label>
          <input
            className="input"
            type="text"
            id="pblFolderName"
            maxLength={80}
            autoComplete="off"
            autoFocus
            value={name}
            onChange={(e) => {
              setName(e.target.value);
              setError(null);
            }}
          />
          <p className="field__error">{error ?? 'Enter a folder name.'}</p>
        </div>
        <div className="pbl-modal__actions">
          <button type="submit" className="btn-crm btn-crm--primary" disabled={busy}>
            {folder ? 'Save folder' : 'Add folder'}
          </button>
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            Cancel
          </button>
        </div>
      </form>
    </PblModal>
  );
}

const FolderSvg = () => (
  <svg
    className="pbl-folder-ico"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="1.8"
    strokeLinecap="round"
    strokeLinejoin="round"
    aria-hidden="true"
  >
    <path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
  </svg>
);
export { FolderSvg };

const DocSvg = () => (
  <svg
    className="pbl-folder-ico"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="1.8"
    strokeLinecap="round"
    strokeLinejoin="round"
    aria-hidden="true"
  >
    <path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z" />
    <path d="M14 3v5h5" />
  </svg>
);

/** Move to folder (playbooks.js:395-440): pick a folder or No folder, or create one here. */
export function MoveDialog({
  playbooks,
  folders,
  onClose,
  onFolderCreated,
  onMoved,
}: {
  playbooks: PlaybookSummary[];
  folders: PlaybookFolder[];
  onClose: () => void;
  onFolderCreated: (folder: PlaybookFolder) => void;
  onMoved: () => void;
}) {
  const toast = useToast();
  const [q, setQ] = useState('');
  /** `''` is No folder; `null` nothing picked yet. */
  const [target, setTarget] = useState<string | null>(null);
  const [creating, setCreating] = useState(false);
  const [newName, setNewName] = useState('');
  const [newError, setNewError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  const current = useMemo(() => {
    const ids = playbooks.map((p) => p.folderId ?? '');
    return ids.every((f) => f === ids[0]) ? ids[0] : null;
  }, [playbooks]);
  const term = q.trim().toLowerCase();
  const shown = folders.filter((f) => !term || f.name.toLowerCase().includes(term));
  const targetName =
    target === '' ? 'No folder' : (folders.find((f) => f.id === target)?.name ?? '');
  const msg = target == null ? null : moveMessage(playbooks.length, targetName);

  const create = async () => {
    const value = cleanName(newName);
    if (!value) return setNewError('Enter a folder name.');
    if (folders.some((f) => f.name.toLowerCase() === value.toLowerCase())) {
      return setNewError(DUPLICATE);
    }
    try {
      const folder = await createPlaybookFolder(value);
      onFolderCreated(folder);
      setTarget(folder.id);
      setQ('');
      setCreating(false);
      setNewName('');
    } catch (err) {
      if (isConflict(err)) setNewError(DUPLICATE);
      else toast(errorText(err), 'danger');
    }
  };

  const move = async () => {
    if (target == null) return;
    setBusy(true);
    const folderId = target || null;
    const todo = playbooks.filter((p) => (p.folderId ?? null) !== folderId);
    const results = await Promise.allSettled(todo.map((p) => updatePlaybook(p.id, { folderId })));
    setBusy(false);
    const failed = results.filter((r) => r.status === 'rejected');
    const moved = results.length - failed.length;
    if (failed.length) {
      toast(errorText((failed[0] as PromiseRejectedResult).reason), 'danger');
    }
    if (moved) toast(`${moved} ${moved === 1 ? 'playbook' : 'playbooks'} moved to ${targetName}`);
    onMoved();
  };

  return (
    <PblModal
      id="pblMoveModal"
      title="Move to folder"
      className="pbl-modal pbl-move"
      onClose={onClose}
    >
      <div className="modal__body">
        <label className="pbl-search pbl-move__search">
          <input
            type="search"
            placeholder="Search"
            aria-label="Search folders"
            autoFocus
            value={q}
            onChange={(e) => setQ(e.target.value)}
          />
          <CrmIcon name="search" className="iconSize-16" />
        </label>
        <p className="pbl-move__msg" aria-live="polite">
          {msg ? (
            <>
              Moving <strong>{msg.count}</strong> into <strong>{msg.target}</strong>.
            </>
          ) : null}
        </p>
        <div className="pbl-move__list" role="listbox" aria-label="Folders">
          {!term || 'no folder'.includes(term) ? (
            <button
              type="button"
              className={cn('pbl-move__it', target === '' && 'is-on')}
              role="option"
              aria-selected={target === ''}
              onClick={() => setTarget('')}
            >
              <DocSvg />
              <span>No folder</span>
            </button>
          ) : null}
          {shown.map((f) => (
            <button
              type="button"
              key={f.id}
              className={cn('pbl-move__it', target === f.id && 'is-on')}
              role="option"
              aria-selected={target === f.id}
              onClick={() => setTarget(f.id)}
            >
              <FolderSvg />
              <span>{f.name}</span>
            </button>
          ))}
          {term && !shown.length && !'no folder'.includes(term) ? (
            <p className="pbl-move__none">No folders match.</p>
          ) : null}
        </div>
        <button
          type="button"
          className="pbl-move__new"
          aria-expanded={creating}
          onClick={() => setCreating((v) => !v)}
        >
          + Create new folder
        </button>
        {creating ? (
          <form
            className="pbl-move__create"
            noValidate
            onSubmit={(e) => {
              e.preventDefault();
              void create();
            }}
          >
            <h3>Create new folder</h3>
            <div className={cn('field', newError && 'is-invalid')}>
              <label className="field__label" htmlFor="pblMoveName">
                Folder Name
              </label>
              <input
                className="input"
                type="text"
                id="pblMoveName"
                maxLength={80}
                autoComplete="off"
                autoFocus
                value={newName}
                onChange={(e) => {
                  setNewName(e.target.value);
                  setNewError(null);
                }}
              />
              <p className="field__error">{newError ?? 'Enter a folder name.'}</p>
            </div>
            <div className="pbl-modal__actions">
              <button type="submit" className="btn-crm btn-crm--outline btn-crm--sm">
                Save
              </button>
              <button
                type="button"
                className="btn-crm btn-crm--outline btn-crm--sm"
                onClick={() => {
                  setCreating(false);
                  setNewName('');
                  setNewError(null);
                }}
              >
                Cancel
              </button>
            </div>
          </form>
        ) : null}
        <div className="pbl-modal__actions">
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            disabled={busy || target == null || target === current}
            onClick={() => void move()}
          >
            Move
          </button>
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            Cancel
          </button>
        </div>
      </div>
    </PblModal>
  );
}

/** Delete a folder, a playbook or several (playbooks.js:443-480). */
export function DeleteDialog({
  folders,
  playbooks,
  onClose,
  onDeleted,
}: {
  folders: PlaybookFolder[];
  playbooks: PlaybookSummary[];
  onClose: () => void;
  onDeleted: () => void;
}) {
  const toast = useToast();
  const [busy, setBusy] = useState(false);
  const targets: DeleteTarget[] = [
    ...folders.map((f) => ({ kind: 'folder' as const, name: f.name, inside: f.playbookCount })),
    ...playbooks.map((p) => ({ kind: 'playbook' as const, name: p.name })),
  ];
  const copy = deleteCopy(targets);
  const run = async () => {
    setBusy(true);
    const results = await Promise.allSettled([
      ...folders.map((f) => deletePlaybookFolder(f.id)),
      ...playbooks.map((p) => deletePlaybook(p.id)),
    ]);
    setBusy(false);
    const failed = results.filter((r) => r.status === 'rejected');
    if (failed.length) toast(errorText((failed[0] as PromiseRejectedResult).reason), 'danger');
    const done = results.length - failed.length;
    if (done) toast(done === 1 ? 'Deleted' : `${done} items deleted`);
    onDeleted();
  };
  return (
    <PblModal
      id="pblDeleteModal"
      role="alertdialog"
      title={copy.title}
      titleClass="pbl-modal__title--lg"
      onClose={onClose}
    >
      <div className="modal__body">
        <p className="pbl-modal__text">{copy.text}</p>
        <div className="pbl-modal__actions">
          <button
            type="button"
            className="btn-crm pbl-btn-danger"
            disabled={busy}
            onClick={() => void run()}
          >
            {copy.button}
          </button>
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            Cancel
          </button>
        </div>
      </div>
    </PblModal>
  );
}

const WHO: Array<{ value: PlaybookVisibility; label: string }> = [
  { value: 'everyone', label: 'Everyone on the team' },
  { value: 'teams', label: 'Specific teams' },
  { value: 'private', label: 'Only me' },
];

/** Manage sharing (playbooks.php:455-485, playbooks.js:486-500). */
export function ShareDialog({
  playbook,
  teams,
  onClose,
  onSaved,
}: {
  playbook: PlaybookSummary;
  teams: Array<{ id: string; name: string }>;
  onClose: () => void;
  onSaved: () => void;
}) {
  const toast = useToast();
  const [who, setWho] = useState<PlaybookVisibility>(playbook.visibility);
  const [chosen, setChosen] = useState<Set<string>>(new Set());
  const [busy, setBusy] = useState(false);
  useEffect(() => {
    if (playbook.visibility !== 'teams') return;
    let live = true;
    getPlaybook(playbook.id).then(
      (full: Playbook) => live && setChosen(new Set(full.teamIds ?? [])),
      (err: unknown) => live && toast(errorText(err), 'danger'),
    );
    return () => {
      live = false;
    };
  }, [playbook.id, playbook.visibility, toast]);

  const save = async () => {
    if (who === 'teams' && !chosen.size) {
      toast('Select at least one team.', 'info');
      return;
    }
    setBusy(true);
    try {
      await updatePlaybook(playbook.id, {
        visibility: who,
        ...(who === 'teams' && { teamIds: [...chosen] }),
      });
      toast('Sharing updated');
      onSaved();
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusy(false);
    }
  };

  return (
    <PblModal id="pblShareModal" title="Manage sharing" onClose={onClose}>
      <form
        className="modal__body"
        onSubmit={(e) => {
          e.preventDefault();
          void save();
        }}
      >
        <p className="pbl-modal__text">{playbook.name}</p>
        <div className="field">
          <label className="field__label" htmlFor="pblShareWho">
            Who can view and use this playbook?
          </label>
          <select
            className="input"
            id="pblShareWho"
            value={who}
            onChange={(e) => setWho(e.target.value as PlaybookVisibility)}
          >
            {WHO.map((w) => (
              <option key={w.value} value={w.value}>
                {w.label}
              </option>
            ))}
          </select>
        </div>
        {who === 'teams' ? (
          <div className="field pbl-share-teams">
            <span className="field__label">Teams</span>
            {teams.map((t) => (
              <label className="check pbl-check-row" key={t.id}>
                <input
                  type="checkbox"
                  value={t.id}
                  checked={chosen.has(t.id)}
                  onChange={(e) =>
                    setChosen((cur) => {
                      const next = new Set(cur);
                      if (e.target.checked) next.add(t.id);
                      else next.delete(t.id);
                      return next;
                    })
                  }
                />
                <span className="check__box" aria-hidden="true" />
                <span>{t.name}</span>
              </label>
            ))}
          </div>
        ) : null}
        <div className="pbl-modal__actions">
          <button type="submit" className="btn-crm btn-crm--primary" disabled={busy}>
            Save sharing
          </button>
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            Cancel
          </button>
        </div>
      </form>
    </PblModal>
  );
}

/** The Preview drawer: the playbook's questions (playbooks.js:537-555). */
export function PreviewDrawer({
  playbook,
  onClose,
}: {
  playbook: PlaybookSummary;
  onClose: () => void;
}) {
  const [full, setFull] = useState<Playbook | null>(null);
  const [error, setError] = useState<string | null>(null);
  useEffect(() => {
    let live = true;
    getPlaybook(playbook.id).then(
      (p) => live && setFull(p),
      (err: unknown) => live && setError(errorText(err)),
    );
    return () => {
      live = false;
    };
  }, [playbook.id]);
  const questions = (full?.content ?? []).flatMap((b) => (b.type === 'question' ? [b.q] : []));
  return (
    <PblModal
      id="pblPreview"
      title={playbook.name}
      className="pbl-preview"
      drawer
      onClose={onClose}
      footer={
        <div className="modal__footer">
          <button type="button" className="btn-crm btn-crm--primary" onClick={onClose}>
            Close
          </button>
        </div>
      }
    >
      <div className="modal__body">
        <h3 className="pbl-preview__name">{playbook.name}</h3>
        {error ? (
          <p className="pbl-preview__empty" role="alert">
            The playbook could not be loaded: {error}
          </p>
        ) : !full ? (
          <p className="pbl-preview__empty">Loading…</p>
        ) : !questions.length ? (
          <p className="pbl-preview__empty">
            This playbook has no questions yet. Open it in the editor to add content.
          </p>
        ) : (
          questions.map((q, i) => (
            <div className="pbl-q" key={i}>
              <span className="pbl-q__icon" aria-hidden="true">
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="1.8"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <path d="M4 5h16v11H9l-5 4z" />
                  <path d="M9.5 9.5a2.5 2.5 0 1 1 3.5 2.3c-.7.3-1 .7-1 1.4" />
                </svg>
              </span>
              <div className="pbl-q__body">
                <label className="pbl-q__title" htmlFor={`pblQ${i}`}>
                  {q.text}
                  {q.required ? (
                    <>
                      {' '}
                      <span className="pbl-q__req" aria-hidden="true">
                        *
                      </span>
                    </>
                  ) : null}
                </label>
                <p className="pbl-q__desc">{questionDesc(q)}</p>
                <input disabled className="input pbl-q__input" type="text" id={`pblQ${i}`} />
                {q.required ? (
                  <p className="pbl-q__err">Response is required for this question</p>
                ) : null}
              </div>
            </div>
          ))
        )}
      </div>
    </PblModal>
  );
}
