'use client';

import { useEffect, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CustomSelect, type CustomSelectOption } from '@/components/crm/CustomSelect';
import { useToast } from '@/components/crm/ToastProvider';
import { updateCall } from '@/features/activities/api.client';
import { CALL_TYPE_OPTIONS } from '@/features/activities/callTypes';
import { LpModal } from '@/features/list-page/ui/LpModal';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  BULK_EDIT_CONCURRENCY,
  CALL_BULK_FIELDS,
  EMPTY_BULK_VALUE,
  callBulkBody,
  callBulkDoneMessage,
  callBulkField,
  callBulkReady,
  settleInBatches,
  type CallBulkValue,
} from '../bulkEdit';
import type { CallRow } from '../types';

const DIRECTION_OPTIONS: CustomSelectOption[] = [
  { value: 'inbound', label: 'Inbound' },
  { value: 'outbound', label: 'Outbound' },
];

/**
 * CL5a: the Calls page's bulk Edit (design list-page.js `bulkEdit` with `BE_HS.calls`), in the
 * shared bar's markup. Each selected call is saved with PATCH /activities/calls/:id, as bulk Delete
 * deletes them one by one; the calls the person may not edit are counted as not changed.
 */
export function CallsBulkEdit({
  open,
  rows,
  canEdit,
  outcomes,
  owners,
  timeZone,
  onClose,
  onDone,
}: {
  open: boolean;
  /** The selected calls. */
  rows: CallRow[];
  canEdit: (row: CallRow) => boolean;
  /** Active call outcomes. */
  outcomes: CustomSelectOption[];
  /** Active users a call can be given to. */
  owners: CustomSelectOption[];
  timeZone: string;
  onClose: () => void;
  onDone: () => void;
}) {
  const toast = useToast();
  const [key, setKey] = useState('');
  const [value, setValue] = useState<CallBulkValue>(EMPTY_BULK_VALUE);
  const [clear, setClear] = useState(false);
  const [confirming, setConfirming] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!open) return;
    setKey('');
    setValue(EMPTY_BULK_VALUE);
    setClear(false);
    setConfirming(false);
    setError(null);
  }, [open]);

  const field = callBulkField(key);
  const ready = callBulkReady(field, value, clear);
  const n = rows.length;
  const recs = `${n.toLocaleString()} ${n === 1 ? 'record' : 'records'}`;
  const optionsOf = (k: string): CustomSelectOption[] =>
    k === 'direction'
      ? DIRECTION_OPTIONS
      : k === 'outcome'
        ? outcomes
        : k === 'callType'
          ? CALL_TYPE_OPTIONS.map((o) => ({ value: o.value, label: o.label }))
          : owners;

  const run = async () => {
    if (!field || ready === 'off' || busy || !n) return;
    setBusy(true);
    setError(null);
    const editable = rows.filter(canEdit);
    const results = await settleInBatches(editable, BULK_EDIT_CONCURRENCY, (r) =>
      updateCall(r.id, callBulkBody(field, value, clear, r, timeZone)),
    );
    setBusy(false);
    const rejected = results.filter((r): r is PromiseRejectedResult => r.status === 'rejected');
    const ok = results.length - rejected.length;
    if (!ok) {
      // Nothing changed: the dialog stays open with the reason.
      setError(
        rejected.length ? errorText(rejected[0]!.reason) : 'You can only edit calls you may edit',
      );
      setConfirming(false);
      return;
    }
    toast(callBulkDoneMessage(field.label, ok, n - ok), ok === n ? 'success' : 'info');
    onClose();
    onDone();
  };

  const valueId = 'calls-bulk-value';
  return (
    <>
      <LpModal
        open={open && !confirming}
        title={`Bulk edit ${recs}`}
        // Not while the calls are being saved (as the clear confirmation).
        onClose={() => !busy && onClose()}
        className="lp-modal--bulk lp-modal--open-list"
        footer={
          <div className="lp-modal__acts lp-modal__acts--start">
            <button
              type="button"
              className={cn('lp-btn lp-btn--primary', busy && 'is-loading')}
              disabled={busy || ready === 'off' || !n}
              onClick={() => {
                // CT-28: clearing asks first; the confirmation sends it.
                if (ready === 'clear') {
                  setError(null);
                  setConfirming(true);
                  return;
                }
                void run();
              }}
            >
              Update
            </button>
            <button
              type="button"
              className="lp-btn lp-btn--outline"
              disabled={busy}
              onClick={onClose}
            >
              Cancel
            </button>
          </div>
        }
      >
        {error ? <Alert tone="danger">{error}</Alert> : null}
        <div className="lp-field">
          <label>Property to update</label>
          <CustomSelect
            className="lp-bx__select"
            placeholder="Select a property to edit"
            value={key}
            options={CALL_BULK_FIELDS.map((f) => ({ value: f.key, label: f.label }))}
            onChange={(v) => {
              setKey(v);
              setValue(EMPTY_BULK_VALUE);
              setClear(false);
            }}
          />
        </div>
        {field ? (
          <div className="lp-field">
            <label htmlFor={valueId}>{field.label}</label>
            {field.kind === 'enum' || field.kind === 'owner' ? (
              <CustomSelect
                id={valueId}
                className="lp-bx__select"
                placeholder="--"
                value={value.text}
                options={optionsOf(field.key)}
                onChange={(v) => setValue({ ...value, text: v })}
                disabled={clear}
              />
            ) : field.kind === 'duration' ? (
              // As Log call asks for it: minutes and seconds.
              <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                <input
                  id={valueId}
                  type="number"
                  min={0}
                  max={1440}
                  className="lp-input lp-input--num"
                  style={{ width: 90 }}
                  aria-label="Minutes"
                  value={value.minutes}
                  onChange={(e) => setValue({ ...value, minutes: e.target.value })}
                  disabled={clear}
                />
                <span className="crm-text-muted crm-fs-8">min</span>
                <input
                  type="number"
                  min={0}
                  max={59}
                  className="lp-input lp-input--num"
                  style={{ width: 90 }}
                  aria-label="Seconds"
                  value={value.seconds}
                  onChange={(e) => setValue({ ...value, seconds: e.target.value })}
                  disabled={clear}
                />
                <span className="crm-text-muted crm-fs-8">sec</span>
              </div>
            ) : field.kind === 'longtext' ? (
              <textarea
                id={valueId}
                className="lp-input"
                rows={4}
                value={value.text}
                onChange={(e) => setValue({ ...value, text: e.target.value })}
                disabled={clear}
              />
            ) : (
              <input
                id={valueId}
                className="lp-input"
                type={field.kind === 'date' ? 'date' : 'text'}
                value={value.text}
                onChange={(e) => setValue({ ...value, text: e.target.value })}
                disabled={clear}
              />
            )}
          </div>
        ) : null}
        {field?.clearable ? (
          <label className="lp-check">
            <input
              type="checkbox"
              checked={clear}
              onChange={(e) => {
                setClear(e.target.checked);
                // A cleared property has no value: the box empties the control.
                if (e.target.checked) setValue(EMPTY_BULK_VALUE);
              }}
            />
            <span>Clear this property</span>
          </label>
        ) : null}
      </LpModal>

      <LpModal
        open={open && confirming}
        title={`Clear ${field?.label ?? 'property'}?`}
        // Back to Bulk edit with its picks, as Cancel.
        onClose={() => {
          if (busy) return;
          setError(null);
          setConfirming(false);
        }}
        className="lp-modal--pick lp-modal--del"
        footer={
          <div className="lp-modal__acts lp-modal__acts--start">
            <button
              type="button"
              className={cn('lp-btn lp-btn--danger', busy && 'is-loading')}
              disabled={busy || !field}
              onClick={() => void run()}
            >
              Clear property
            </button>
            <button
              type="button"
              className="lp-btn lp-btn--outline"
              disabled={busy}
              onClick={() => {
                setError(null);
                setConfirming(false);
              }}
            >
              Cancel
            </button>
          </div>
        }
      >
        {error ? <Alert tone="danger">{error}</Alert> : null}
        <p>
          <strong>{field?.label}</strong> will be emptied on {recs}. Their current values are
          removed.
        </p>
      </LpModal>
    </>
  );
}
