'use client';

// Moving a lead to a closed stage (HUB-340): Disqualified asks for the reason (required) and a
// note; Qualified asks whether to convert the lead to a deal or only qualify it. Used by the
// lead page's buttons and by the board when a card is dropped on those stages.
import { useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { cn } from '@/lib/utils/cn';
import { DISQUALIFICATION_NOTE, DISQUALIFICATION_REASON } from '../../leads';
import type { CustomValues } from '../../types';
import { SnippetTextarea } from '@/features/snippets/ui/SnippetTextarea';

/** The reason (required) and note, sent with the stage move so the API checks the same rule. */
export function DisqualifyDialog({
  open,
  leadName,
  reasons,
  initialReason,
  onClose,
  onConfirm,
}: {
  open: boolean;
  leadName: string;
  reasons: Array<{ value: string; label: string }>;
  /** A reason already on the lead. */
  initialReason?: string | null;
  onClose: () => void;
  /** Moves the lead with these fields; throws with the message to show. */
  onConfirm: (fields: CustomValues) => Promise<void>;
}) {
  const [reason, setReason] = useState(initialReason ?? '');
  const [note, setNote] = useState('');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [wasOpen, setWasOpen] = useState(open);
  if (open !== wasOpen) {
    setWasOpen(open);
    if (open) {
      setReason(initialReason ?? '');
      setNote('');
      setError(null);
    }
  }

  const submit = async () => {
    if (busy) return;
    if (!reason) {
      setError('Choose a disqualification reason.');
      return;
    }
    setBusy(true);
    setError(null);
    try {
      await onConfirm({
        [DISQUALIFICATION_REASON]: reason,
        ...(note.trim() ? { [DISQUALIFICATION_NOTE]: note.trim() } : {}),
      });
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setBusy(false);
    }
  };

  const close = busy ? () => {} : onClose;
  return (
    <CrmModal id="leadDisqualifyModal" open={open} onClose={close}>
      <form
        noValidate
        onSubmit={(e) => {
          e.preventDefault();
          void submit();
        }}
      >
        <ModalHeader id="leadDisqualifyModal" title={`Disqualify ${leadName}`} onClose={close} />
        <div className="modal__body">
          {error ? <Alert tone="danger">{error}</Alert> : null}
          <div className={cn('field', error && !reason && 'is-invalid')}>
            <label className="field__label" htmlFor="leadDisqualifyReason">
              Reason *
            </label>
            <select
              className="input"
              id="leadDisqualifyReason"
              value={reason}
              required
              onChange={(e) => setReason(e.target.value)}
            >
              <option value="">Choose a reason</option>
              {reasons.map((r) => (
                <option key={r.value} value={r.value}>
                  {r.label}
                </option>
              ))}
            </select>
          </div>
          <div className="field crm-mt-3">
            <label className="field__label" htmlFor="leadDisqualifyNote">
              Note (optional)
            </label>
            <SnippetTextarea
              className="input"
              id="leadDisqualifyNote"
              rows={3}
              maxLength={2000}
              value={note}
              onChange={(e) => setNote(e.target.value)}
            />
          </div>
        </div>
        <div className="modal__footer">
          <button
            type="button"
            className="btn-crm btn-crm--outline"
            onClick={close}
            disabled={busy}
          >
            Cancel
          </button>
          <button
            type="submit"
            className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
            disabled={busy}
            aria-busy={busy}
          >
            Disqualify
          </button>
        </div>
      </form>
    </CrmModal>
  );
}

/** Qualify: convert to a deal (opens the convert drawer) or only move the lead to Qualified. */
export function QualifyDialog({
  open,
  leadName,
  stageName,
  converted,
  onClose,
  onConvert,
  onQualify,
}: {
  open: boolean;
  leadName: string;
  stageName: string;
  /** Already converted: only qualifying is offered. */
  converted: boolean;
  onClose: () => void;
  onConvert: () => void;
  /** Moves the lead; throws with the message to show. */
  onQualify: () => Promise<void>;
}) {
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [wasOpen, setWasOpen] = useState(open);
  if (open !== wasOpen) {
    setWasOpen(open);
    if (open) setError(null);
  }

  const qualify = async () => {
    if (busy) return;
    setBusy(true);
    setError(null);
    try {
      await onQualify();
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setBusy(false);
    }
  };

  const close = busy ? () => {} : onClose;
  return (
    <CrmModal id="leadQualifyModal" open={open} onClose={close}>
      <ModalHeader id="leadQualifyModal" title={`Qualify ${leadName}`} onClose={close} />
      <div className="modal__body">
        {error ? <Alert tone="danger">{error}</Alert> : null}
        <p>
          {converted
            ? `This lead is already converted to a deal. Move it to ${stageName}?`
            : `Convert this lead to a deal now, or only move it to ${stageName}? Converting also moves it to ${stageName}.`}
        </p>
      </div>
      <div className="modal__footer">
        <button type="button" className="btn-crm btn-crm--outline" onClick={close} disabled={busy}>
          Cancel
        </button>
        <button
          type="button"
          className={cn(
            'btn-crm',
            converted ? 'btn-crm--primary' : 'btn-crm--outline',
            busy && 'is-loading',
          )}
          disabled={busy}
          aria-busy={busy}
          onClick={() => void qualify()}
        >
          {converted ? `Move to ${stageName}` : 'Just qualify'}
        </button>
        {!converted ? (
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            disabled={busy}
            onClick={onConvert}
          >
            Convert to deal
          </button>
        ) : null}
      </div>
    </CrmModal>
  );
}
