'use client';

import { useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { actionErrorText } from '@/features/contacts/ui/actions/shared';
import { bulkTasks } from '@/features/tasks/api.client';
import { dueFromInputs, priorityLabel } from '@/features/tasks/format';
import {
  TASK_PRIORITIES,
  type BulkTasksBody,
  type TaskBulkAction,
  type TaskPriority,
} from '@/features/tasks/types';
import { cn } from '@/lib/utils/cn';
import { ConfirmDialog } from './ConfirmDialog';

type Panel = 'reassign' | 'reschedule' | 'priority' | 'queue' | null;

/**
 * Actions on the selected rows (POST /tasks/bulk, up to 100): complete, reopen, reassign
 * (needs the owners list), reschedule, set priority, change queue (TK6, QA #679), delete. Tells
 * how many tasks changed. The API refuses the whole action when any selected task can't be
 * changed (BL3; delete too since TK1).
 */
export function TaskBulkBar({
  ids,
  members,
  queues = [],
  timeZone,
  onClear,
  onDone,
}: {
  ids: string[];
  /** People a task can be reassigned to; empty hides Reassign. */
  members: { userId: string; name: string }[];
  /** Task queues the caller can use; empty leaves only "No queue". */
  queues?: { id: string; name: string }[];
  timeZone: string;
  onClear: () => void;
  onDone: () => void;
}) {
  const toast = useToast();
  const [busy, setBusy] = useState<TaskBulkAction | null>(null);
  const [panel, setPanel] = useState<Panel>(null);
  const [assigneeId, setAssigneeId] = useState('');
  const [day, setDay] = useState('');
  const [time, setTime] = useState('');
  /** '' = no priority. */
  const [priority, setPriority] = useState<TaskPriority | ''>('');
  /** '' = no queue. */
  const [queueId, setQueueId] = useState('');
  const [confirmDelete, setConfirmDelete] = useState(false);

  const run = async (action: TaskBulkAction, extra: Partial<BulkTasksBody> = {}) => {
    if (busy) return;
    setBusy(action);
    try {
      const { updated } = await bulkTasks({ ids, action, ...extra });
      const skipped = ids.length - updated;
      toast(
        `${updated} of ${ids.length} task${ids.length === 1 ? '' : 's'} updated` +
          (skipped ? ` (${skipped} already in that state or gone)` : ''),
      );
      setPanel(null);
      setConfirmDelete(false);
      onDone();
    } catch (err) {
      toast(actionErrorText(err), 'danger', { durationMs: 8000 });
    } finally {
      setBusy(null);
    }
  };

  const reschedule = () => {
    const due = dueFromInputs(day, time, timeZone);
    if ('error' in due) {
      toast(due.error, 'danger');
      return;
    }
    // both null clears the due date
    void run('reschedule', due.dueAt ? { dueAt: due.dueAt } : { dueDate: due.dueDate });
  };

  const btn = (action: TaskBulkAction) =>
    cn('btn-crm btn-crm--outline btn-crm--sm', busy === action && 'is-loading');

  return (
    <div
      className="crm-d-flex crm-align-items-center crm-gap-2 crm-flex-wrap crm-mb-3"
      role="toolbar"
      aria-label="Bulk actions"
    >
      <strong className="crm-fs-7">{ids.length} selected</strong>
      <button
        type="button"
        className={btn('complete')}
        disabled={busy !== null}
        onClick={() => void run('complete')}
      >
        Complete
      </button>
      <button
        type="button"
        className={btn('reopen')}
        disabled={busy !== null}
        onClick={() => void run('reopen')}
      >
        Reopen
      </button>
      {members.length ? (
        <button
          type="button"
          className={cn(btn('reassign'), panel === 'reassign' && 'is-active')}
          disabled={busy !== null}
          onClick={() => setPanel((p) => (p === 'reassign' ? null : 'reassign'))}
        >
          Reassign…
        </button>
      ) : null}
      <button
        type="button"
        className={cn(btn('reschedule'), panel === 'reschedule' && 'is-active')}
        disabled={busy !== null}
        onClick={() => setPanel((p) => (p === 'reschedule' ? null : 'reschedule'))}
      >
        Reschedule…
      </button>
      <button
        type="button"
        className={cn(btn('set_priority'), panel === 'priority' && 'is-active')}
        disabled={busy !== null}
        onClick={() => setPanel((p) => (p === 'priority' ? null : 'priority'))}
      >
        Set priority…
      </button>
      <button
        type="button"
        className={cn(btn('set_queue'), panel === 'queue' && 'is-active')}
        disabled={busy !== null}
        onClick={() => setPanel((p) => (p === 'queue' ? null : 'queue'))}
      >
        Change queue…
      </button>
      <button
        type="button"
        className={cn(btn('delete'), 'crm-text-danger')}
        disabled={busy !== null}
        onClick={() => setConfirmDelete(true)}
      >
        Delete
      </button>
      <button
        type="button"
        className="btn-crm btn-crm--ghost btn-crm--sm"
        disabled={busy !== null}
        onClick={onClear}
      >
        Clear selection
      </button>

      {panel === 'reassign' ? (
        <div className="crm-d-flex crm-align-items-center crm-gap-2" style={{ flexBasis: '100%' }}>
          <select
            className="input"
            style={{ maxWidth: 260 }}
            aria-label="New assignee"
            value={assigneeId}
            onChange={(e) => setAssigneeId(e.target.value)}
          >
            <option value="">Nobody</option>
            {members.map((m) => (
              <option key={m.userId} value={m.userId}>
                {m.name}
              </option>
            ))}
          </select>
          <button
            type="button"
            className={cn(
              'btn-crm btn-crm--primary btn-crm--sm',
              busy === 'reassign' && 'is-loading',
            )}
            disabled={busy !== null}
            onClick={() => void run('reassign', { assigneeId: assigneeId || null })}
          >
            Reassign {ids.length}
          </button>
        </div>
      ) : null}

      {panel === 'reschedule' ? (
        <div className="crm-d-flex crm-align-items-center crm-gap-2" style={{ flexBasis: '100%' }}>
          <input
            className="input"
            type="date"
            style={{ maxWidth: 180 }}
            aria-label="New due date"
            value={day}
            onChange={(e) => setDay(e.target.value)}
          />
          <input
            className="input"
            type="time"
            style={{ maxWidth: 140 }}
            aria-label="New due time (optional)"
            value={time}
            onChange={(e) => setTime(e.target.value)}
          />
          <button
            type="button"
            className={cn(
              'btn-crm btn-crm--primary btn-crm--sm',
              busy === 'reschedule' && 'is-loading',
            )}
            disabled={busy !== null}
            onClick={reschedule}
          >
            {day ? `Reschedule ${ids.length}` : `Clear due date of ${ids.length}`}
          </button>
          <span className="crm-fs-8 crm-text-muted">Times are in {timeZone}.</span>
        </div>
      ) : null}

      {panel === 'priority' ? (
        <div className="crm-d-flex crm-align-items-center crm-gap-2" style={{ flexBasis: '100%' }}>
          <select
            className="input"
            style={{ maxWidth: 200 }}
            aria-label="New priority"
            value={priority}
            onChange={(e) => setPriority(e.target.value as TaskPriority | '')}
          >
            <option value="">{priorityLabel(null)}</option>
            {TASK_PRIORITIES.map((p) => (
              <option key={p} value={p}>
                {priorityLabel(p)}
              </option>
            ))}
          </select>
          <button
            type="button"
            className={cn(
              'btn-crm btn-crm--primary btn-crm--sm',
              busy === 'set_priority' && 'is-loading',
            )}
            disabled={busy !== null}
            onClick={() => void run('set_priority', { priority: priority || null })}
          >
            Set priority of {ids.length}
          </button>
        </div>
      ) : null}

      {panel === 'queue' ? (
        <div className="crm-d-flex crm-align-items-center crm-gap-2" style={{ flexBasis: '100%' }}>
          <select
            className="input"
            style={{ maxWidth: 260 }}
            aria-label="New queue"
            value={queueId}
            onChange={(e) => setQueueId(e.target.value)}
          >
            <option value="">No queue</option>
            {queues.map((q) => (
              <option key={q.id} value={q.id}>
                {q.name}
              </option>
            ))}
          </select>
          <button
            type="button"
            className={cn(
              'btn-crm btn-crm--primary btn-crm--sm',
              busy === 'set_queue' && 'is-loading',
            )}
            disabled={busy !== null}
            onClick={() => void run('set_queue', { queueId: queueId || null })}
          >
            Move {ids.length}
          </button>
        </div>
      ) : null}

      <ConfirmDialog
        id="taskBulkDeleteConfirm"
        open={confirmDelete}
        title={`Delete ${ids.length} task${ids.length === 1 ? '' : 's'}?`}
        confirmLabel="Delete"
        busy={busy === 'delete'}
        onCancel={() => setConfirmDelete(false)}
        onConfirm={() => void run('delete')}
      >
        The selected tasks will be deleted. An admin can restore each one.
      </ConfirmDialog>
    </div>
  );
}
