'use client';

import { useCallback, useEffect, useRef, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import {
  archivePicklistOption,
  createPicklistOption,
  listPicklistOptions,
  restorePicklistOption,
  updatePicklistOption,
  type PicklistOption,
} from '@/features/picklists/api.client';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  draftsFromCustoms,
  outcomeDraftIssues,
  outcomeDraftStatus,
  outcomeRowOrder,
  planCallOutcomeSave,
  rowsInOrder,
  splitCallOutcomes,
  type OutcomeDraft,
  type OutcomeSavePlan,
  type OutcomeSort,
} from '../../callOutcomes';

const SORT_LABEL: Record<OutcomeSort, string> = { alpha: 'Alphabetically', custom: 'Custom' };

function CloseIcon() {
  return (
    <svg viewBox="0 0 16 16" width="16" height="16" fill="currentColor" aria-hidden>
      <path d="M2.146 2.854a.5.5 0 11.708-.708L8 7.293l5.146-5.147a.5.5 0 01.708.708L8.707 8l5.147 5.146a.5.5 0 01-.708.708L8 8.707l-5.146 5.147a.5.5 0 01-.708-.708L7.293 8 2.146 2.854z" />
    </svg>
  );
}

function TrashIcon() {
  return (
    <svg viewBox="0 0 16 16" width="16" height="16" fill="currentColor" aria-hidden>
      <path d="M5.5 5.5A.5.5 0 016 6v6a.5.5 0 01-1 0V6a.5.5 0 01.5-.5zm2.5 0a.5.5 0 01.5.5v6a.5.5 0 01-1 0V6a.5.5 0 01.5-.5zm3 .5a.5.5 0 00-1 0v6a.5.5 0 001 0V6z" />
      <path
        fillRule="evenodd"
        d="M14.5 3a1 1 0 01-1 1H13v9a2 2 0 01-2 2H5a2 2 0 01-2-2V4h-.5a1 1 0 01-1-1V2a1 1 0 011-1H6a1 1 0 011-1h2a1 1 0 011 1h3.5a1 1 0 011 1v1zM4.118 4L4 4.059V13a1 1 0 001 1h6a1 1 0 001-1V4.059L11.882 4H4.118zM2.5 3V2h11v1h-11z"
        clipRule="evenodd"
      />
    </svg>
  );
}

function WarnIcon() {
  return (
    <svg viewBox="0 0 16 16" width="14" height="14" fill="currentColor" aria-hidden>
      <path d="M7.001 2.5a1.15 1.15 0 011.998 0l5.5 9.5A1.15 1.15 0 0113.501 13.5h-11a1.15 1.15 0 01-.998-1.5l5.5-9.5zM8 5a.75.75 0 00-.75.75v3a.75.75 0 001.5 0v-3A.75.75 0 008 5zm0 6a.875.875 0 100-1.75A.875.875 0 008 11z" />
    </svg>
  );
}

export interface CallOutcomesPanelProps {
  status: 'loading' | 'ready' | 'error';
  defaults: PicklistOption[];
  /** The custom outcomes as saved, to tell whether the drafts changed. */
  customs: PicklistOption[];
  drafts: OutcomeDraft[];
  /** Row keys in display order, set on open, Add and a sort change (not while typing). */
  order: string[];
  sort: OutcomeSort;
  /** Edit property settings: the picklist API refuses changes without it. */
  canEdit: boolean;
  saving: boolean;
  onDrafts: (next: OutcomeDraft[]) => void;
  /** Adds an empty row; returns its key. */
  onAdd: () => string;
  onSort: (sort: OutcomeSort) => void;
  onSave: () => void;
  onClose: () => void;
}

/** The design's "Edit call outcomes" drawer (setting-pages call-setup.php:407-441). */
export function CallOutcomesPanel({
  status,
  defaults,
  customs,
  drafts,
  order,
  sort,
  canEdit,
  saving,
  onDrafts,
  onAdd,
  onSort,
  onSave,
  onClose,
}: CallOutcomesPanelProps) {
  const [sortOpen, setSortOpen] = useState(false);
  const [selected, setSelected] = useState<string | null>(null);
  const [focusKey, setFocusKey] = useState<string | null>(null);
  const sortRef = useRef<HTMLDivElement>(null);
  const listRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!sortOpen) return;
    const down = (e: MouseEvent) => {
      if (!sortRef.current?.contains(e.target as Node)) setSortOpen(false);
    };
    document.addEventListener('mousedown', down);
    return () => document.removeEventListener('mousedown', down);
  }, [sortOpen]);

  useEffect(() => {
    if (!focusKey) return;
    listRef.current?.querySelector<HTMLInputElement>(`[data-outcome-key="${focusKey}"]`)?.focus();
    setFocusKey(null);
  }, [focusKey]);

  const ready = status === 'ready';
  const { hasEmpty, changed } = outcomeDraftStatus(customs, drafts);
  const issues = outcomeDraftIssues(defaults, customs, drafts);
  const blocked = Object.keys(issues).length > 0;
  const addOff = !ready || !canEdit || hasEmpty || saving;
  const saveOff = !ready || !canEdit || blocked || !changed || saving;
  const rows = ready ? rowsInOrder(defaults, drafts, order) : [];

  const setLabel = (key: string, label: string) =>
    onDrafts(drafts.map((d) => (d.key === key ? { ...d, label } : d)));

  return (
    <>
      <div className="call-types-drawer-backdrop" onClick={onClose} />
      <aside
        className="call-types-drawer"
        role="dialog"
        aria-modal="true"
        aria-labelledby="callOutcomesDrawerTitle"
      >
        <header className="call-types-drawer__header">
          <h2 id="callOutcomesDrawerTitle">Edit call outcomes</h2>
          <button
            type="button"
            className="call-types-drawer__close"
            aria-label="Close"
            onClick={onClose}
          >
            <CloseIcon />
          </button>
        </header>
        <div className="call-types-drawer__body">
          <div className="call-types-sort-wrap">
            <span className="call-types-sort-label">Sort:</span>
            <div className="call-types-sort-dropdown" ref={sortRef}>
              <button
                type="button"
                className="call-types-sort-trigger"
                aria-expanded={sortOpen}
                onClick={() => setSortOpen((o) => !o)}
              >
                <span>{SORT_LABEL[sort]}</span>
                <svg viewBox="0 0 16 16" width="12" height="12" fill="currentColor" aria-hidden>
                  <path d="M4.5 6l3.5 4 3.5-4z" />
                </svg>
              </button>
              {sortOpen ? (
                <div className="call-types-sort-menu">
                  {(['alpha', 'custom'] as const).map((s) => (
                    <button
                      key={s}
                      type="button"
                      className={cn('call-types-sort-opt', sort === s && 'is-active')}
                      onClick={() => {
                        onSort(s);
                        setSortOpen(false);
                      }}
                    >
                      {SORT_LABEL[s]}
                    </button>
                  ))}
                </div>
              ) : null}
            </div>
          </div>
          <div className="call-types-list" ref={listRef}>
            {status === 'loading' ? <p className="crm-text-muted">Loading call outcomes…</p> : null}
            {status === 'error' ? (
              <p className="crm-text-muted" role="alert">
                Call outcomes could not be loaded. Close the drawer and try again.
              </p>
            ) : null}
            {rows.map((row) => {
              const key = row.kind === 'default' ? row.option.id : row.draft.key;
              const isSelected = selected === key;
              if (row.kind === 'default') {
                return (
                  <div
                    key={key}
                    className={cn('call-outcome-row-item', isSelected && 'selected is-selected')}
                    onClick={() => setSelected(key)}
                  >
                    <div className="call-outcome-row call-outcome-row--default">
                      <div className="call-outcome-box">
                        <span>{row.option.label}</span>
                      </div>
                      <div className="call-outcome-popover">
                        Default call outcomes can&apos;t be deleted.
                      </div>
                    </div>
                  </div>
                );
              }
              const issue = issues[key];
              return (
                <div
                  key={key}
                  className={cn('call-outcome-row-item', isSelected && 'selected is-selected')}
                  onClick={() => setSelected(key)}
                >
                  <div className="call-type-row">
                    <div className={cn('call-outcome-custom-wrap', issue && 'is-error')}>
                      <input
                        type="text"
                        className="call-outcome-custom-input"
                        disabled={!canEdit || saving}
                        value={row.draft.label}
                        maxLength={191}
                        autoComplete="off"
                        spellCheck={false}
                        aria-label="Call outcome"
                        data-outcome-key={key}
                        onFocus={() => setSelected(key)}
                        onChange={(e) => setLabel(key, e.target.value)}
                      />
                    </div>
                    {canEdit ? (
                      <button
                        type="button"
                        className="call-type-delete"
                        title="Delete outcome"
                        aria-label="Delete"
                        disabled={saving}
                        onClick={(e) => {
                          e.stopPropagation();
                          onDrafts(drafts.filter((d) => d.key !== key));
                        }}
                      >
                        <TrashIcon />
                      </button>
                    ) : null}
                  </div>
                  {issue ? (
                    <div className="call-type-error-wrap">
                      <WarnIcon />
                      <span>{issue}</span>
                    </div>
                  ) : null}
                </div>
              );
            })}
          </div>
          <button
            type="button"
            className={cn('call-types-add-btn', addOff && 'is-disabled')}
            disabled={addOff}
            onClick={() => {
              const key = onAdd();
              setSelected(key);
              setFocusKey(key);
            }}
          >
            <span className="call-types-add-plus">+</span>Add outcome
          </button>
        </div>
        <footer className="call-types-drawer__footer">
          <button
            type="button"
            className="call-drawer-pill-btn call-drawer-pill-btn--save"
            disabled={saveOff}
            aria-busy={saving || undefined}
            onClick={onSave}
          >
            Save
          </button>
          <button
            type="button"
            className="call-drawer-pill-btn call-drawer-pill-btn--cancel"
            onClick={onClose}
          >
            Cancel
          </button>
        </footer>
      </aside>
    </>
  );
}

/** Runs a save plan on the picklist, one change at a time. */
async function applyPlan(plan: OutcomeSavePlan): Promise<void> {
  for (const id of plan.archive) await archivePicklistOption(id);
  for (const r of plan.rename) await updatePicklistOption(r.id, { label: r.label });
  for (const r of plan.restore) {
    await restorePicklistOption(r.id);
    if (r.label) await updatePicklistOption(r.id, { label: r.label });
  }
  for (const label of plan.create) {
    await createPicklistOption({ objectType: 'activity', field: 'callOutcome', label });
  }
}

/** Loads the call outcome picklist when opened and saves the drawer's changes to it. */
export function CallOutcomesDrawer({
  canEdit,
  onClose,
}: {
  canEdit: boolean;
  onClose: () => void;
}) {
  const toast = useToast();
  const [status, setStatus] = useState<'loading' | 'ready' | 'error'>('loading');
  const [options, setOptions] = useState<PicklistOption[]>([]);
  const [drafts, setDrafts] = useState<OutcomeDraft[]>([]);
  const [sort, setSort] = useState<OutcomeSort>('alpha');
  const [order, setOrder] = useState<string[]>([]);
  const [saving, setSaving] = useState(false);
  const newKey = useRef(0);

  const load = useCallback(async () => {
    setStatus('loading');
    try {
      const list = await listPicklistOptions({
        objectType: 'activity',
        field: 'callOutcome',
        includeArchived: true,
      });
      const split = splitCallOutcomes(list);
      const fresh = draftsFromCustoms(split.customs);
      setOptions(list);
      setDrafts(fresh);
      setSort('alpha');
      setOrder(outcomeRowOrder(split.defaults, fresh, 'alpha'));
      setStatus('ready');
    } catch {
      setStatus('error');
    }
  }, []);

  useEffect(() => {
    void load();
  }, [load]);

  useEffect(() => {
    const key = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && !saving) onClose();
    };
    document.addEventListener('keydown', key);
    return () => document.removeEventListener('keydown', key);
  }, [onClose, saving]);

  const { defaults, customs, archived } = splitCallOutcomes(options);

  const save = async () => {
    setSaving(true);
    try {
      await applyPlan(planCallOutcomeSave(customs, drafts, archived));
      toast('Call outcomes updated', 'success');
      onClose();
    } catch (err) {
      // Steps before the failing one are saved: reload so the list shows what is stored.
      toast(errorText(err), 'danger', { durationMs: 8000 });
      await load();
    } finally {
      setSaving(false);
    }
  };

  const add = () => {
    newKey.current += 1;
    const key = `new-${newKey.current}`;
    const next = [...drafts, { key, id: null, label: '' }];
    setDrafts(next);
    setOrder(outcomeRowOrder(defaults, next, sort));
    return key;
  };

  return (
    <CallOutcomesPanel
      status={status}
      defaults={defaults}
      customs={customs}
      drafts={drafts}
      order={order}
      sort={sort}
      canEdit={canEdit}
      saving={saving}
      onDrafts={setDrafts}
      onAdd={add}
      onSort={(next) => {
        setSort(next);
        setOrder(outcomeRowOrder(defaults, drafts, next));
      }}
      onSave={() => void save()}
      onClose={() => {
        if (!saving) onClose();
      }}
    />
  );
}
