'use client';

import { useState } from 'react';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { useToast } from '@/components/crm/ToastProvider';
import type { LinkTargetType, ObjectNames } from '@/features/associations/types';
import { cn } from '@/lib/utils/cn';
import { associationErrorText, namesOf } from './shared';

/**
 * Confirm, then remove a link. `onConfirm` does the API call (and the success toast); when it
 * throws, the error shows as a toast and the dialog stays open. Both records are kept.
 */
export function RemoveAssociationDialog({
  id,
  open,
  onClose,
  targetType,
  targetNames,
  recordName,
  anchorName,
  note,
  onConfirm,
}: {
  id: string;
  open: boolean;
  onClose: () => void;
  /** A built-in type or a custom object key. */
  targetType: LinkTargetType;
  /** A custom object's names; built-in types have their own. */
  targetNames?: ObjectNames;
  /** The linked record being removed. */
  recordName: string;
  /** The record whose page this is. */
  anchorName: string;
  /** Extra line, e.g. what happens to the primary company. */
  note?: string;
  onConfirm: () => Promise<void>;
}) {
  const toast = useToast();
  const [busy, setBusy] = useState(false);
  const names = namesOf(targetType, targetNames);

  const onRemove = async () => {
    if (busy) return;
    setBusy(true);
    try {
      await onConfirm();
    } catch (err) {
      toast(associationErrorText(err), 'danger', { durationMs: 8000 });
    } finally {
      setBusy(false);
    }
  };

  const close = busy ? () => {} : onClose;

  return (
    <CrmModal id={id} open={open} onClose={close}>
      <ModalHeader id={id} title={`Remove ${names.one} association?`} onClose={close} />
      <div className="modal__body">
        <p>
          <strong>{recordName}</strong> will no longer be associated with{' '}
          <strong>{anchorName}</strong>. Both records stay in the CRM.
        </p>
        {note ? <p className="crm-text-body-secondary crm-mt-3">{note}</p> : null}
      </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={onRemove}
          disabled={busy}
          aria-busy={busy}
          style={{ background: 'var(--danger)', borderColor: 'var(--danger)' }}
        >
          Remove
        </button>
      </div>
    </CrmModal>
  );
}
