'use client';

import { useState } from 'react';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { useToast } from '@/components/crm/ToastProvider';
import { deleteDeal } from '@/features/deals/api.client';
import { actionErrorText } from '@/features/contacts/ui/actions/shared';
import { cn } from '@/lib/utils/cn';

/** Confirm, then soft-delete the deal (DELETE /deals/:id). */
export function DeleteDealDialog({
  open,
  onClose,
  dealId,
  dealName,
  onDeleted,
}: {
  open: boolean;
  onClose: () => void;
  dealId: string;
  dealName: string;
  onDeleted: () => void;
}) {
  const toast = useToast();
  const [busy, setBusy] = useState(false);

  const onDelete = async () => {
    if (busy) return;
    setBusy(true);
    try {
      await deleteDeal(dealId);
      toast(`${dealName} was deleted`);
      onDeleted();
    } catch (err) {
      toast(actionErrorText(err), 'danger', { durationMs: 8000 });
    } finally {
      setBusy(false);
    }
  };

  return (
    <CrmModal id="dealDeleteModal" open={open} onClose={busy ? () => {} : onClose}>
      <ModalHeader id="dealDeleteModal" title="Delete deal?" onClose={onClose} />
      <div className="modal__body">
        <p>
          <strong>{dealName}</strong> will be removed from the CRM. Its notes, tasks and links to
          contacts and companies are kept, and an admin can restore it for a limited time.
        </p>
      </div>
      <div className="modal__footer">
        <button
          type="button"
          className="btn-crm btn-crm--outline"
          onClick={onClose}
          disabled={busy}
        >
          Cancel
        </button>
        <button
          type="button"
          className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
          onClick={onDelete}
          disabled={busy}
          aria-busy={busy}
          style={{ background: 'var(--danger)', borderColor: 'var(--danger)' }}
        >
          Delete
        </button>
      </div>
    </CrmModal>
  );
}
