'use client';

/**
 * HUB-315: merge two duplicate records. Pick the record to keep, then for every field whose
 * values differ, which value to keep (the suggestion is pre-selected). The other record's links,
 * activities, history, list memberships and enrollments move to the kept one, and the other is
 * deleted. Merging can't be undone.
 */
import { useEffect, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { useToast } from '@/components/crm/ToastProvider';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  getMergePreview,
  mergeRecords,
  OBJECT_NAMES,
  type DuplicateObjectType,
  type MergePreview,
  type MergeResult,
} from '../api.client';
import { useMergeValueFormatter } from '../format';

export interface MergeCandidate {
  id: string;
  label: string;
  secondary?: string | null;
}

/** Pipeline and stage come from the same deal, so they are picked together. */
const LINKED: Record<string, string> = { pipelineId: 'stageId', stageId: 'pipelineId' };

export function MergeDialog({
  open,
  objectType,
  records,
  keepId,
  onClose,
  onMerged,
  timeZone,
}: {
  open: boolean;
  objectType: DuplicateObjectType;
  /** The two records; null while nothing is being merged. */
  records: [MergeCandidate, MergeCandidate] | null;
  /** The record kept by default (else the first). */
  keepId?: string;
  onClose: () => void;
  onMerged: (result: MergeResult) => void;
  /** D10: date-time values in the user's zone (Contacts, Companies); else the browser's. */
  timeZone?: string;
}) {
  const toast = useToast();
  const names = OBJECT_NAMES[objectType];
  const format = useMergeValueFormatter(objectType, open, timeZone);
  const [survivorId, setSurvivorId] = useState<string | null>(null);
  const [preview, setPreview] = useState<MergePreview | null>(null);
  const [picks, setPicks] = useState<Record<string, string>>({});
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  // A new pair: start from the default record to keep.
  const pairKey = records ? `${records[0].id}|${records[1].id}` : '';
  useEffect(() => {
    if (!open || !records) return;
    setSurvivorId(keepId && records.some((r) => r.id === keepId) ? keepId : records[0].id);
  }, [open, pairKey]); // eslint-disable-line react-hooks/exhaustive-deps

  const other = records && survivorId ? records.find((r) => r.id !== survivorId) : undefined;
  const survivor = records && survivorId ? records.find((r) => r.id === survivorId) : undefined;

  useEffect(() => {
    if (!open || !survivorId || !other) return;
    let live = true;
    setLoading(true);
    setError(null);
    setPreview(null);
    getMergePreview({ objectType, survivorId, otherId: other.id })
      .then((p) => {
        if (!live) return;
        setPreview(p);
        setPicks(Object.fromEntries(p.fields.map((f) => [f.field, f.suggested])));
      })
      .catch((err: unknown) => live && setError(errorText(err)))
      .finally(() => live && setLoading(false));
    return () => {
      live = false;
    };
  }, [open, objectType, survivorId, other?.id]); // eslint-disable-line react-hooks/exhaustive-deps

  const pick = (field: string, recordId: string) =>
    setPicks((current) => {
      const next = { ...current, [field]: recordId };
      const linked = LINKED[field];
      if (linked && linked in current) next[linked] = recordId;
      return next;
    });

  const onMerge = async () => {
    if (!preview || busy) return;
    setBusy(true);
    try {
      const result = await mergeRecords({
        objectType,
        survivorId: preview.survivorId,
        otherId: preview.otherId,
        fields: picks,
      });
      toast(`Merged into ${preview.survivorLabel}.`, 'success');
      onMerged(result);
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 8000 });
    } finally {
      setBusy(false);
    }
  };

  return (
    <CrmModal id="mergeDialog" open={open} onClose={busy ? () => undefined : onClose} size="lg">
      <ModalHeader id="mergeDialog" title={`Merge ${names.plural}`} onClose={onClose} />
      <div className="modal__body merge-dialog">
        <Alert tone="warning">
          <strong>Merging can&apos;t be undone.</strong> The {names.singular} you don&apos;t keep is
          deleted. Its associations, activities, property history, list memberships and enrollments
          move to the one you keep.
        </Alert>

        {records ? (
          <section className="crm-mt-3">
            <h3 className="merge-dialog__title">Which {names.singular} do you want to keep?</h3>
            <div className="import-choice-list merge-dialog__keep">
              {records.map((r) => (
                <label
                  key={r.id}
                  className={cn('import-choice', survivorId === r.id && 'is-selected')}
                >
                  <input
                    type="radio"
                    name="mergeKeep"
                    value={r.id}
                    checked={survivorId === r.id}
                    disabled={busy}
                    onChange={() => setSurvivorId(r.id)}
                  />
                  <span>
                    <strong>{r.label || `Unnamed ${names.singular}`}</strong>
                    <span>{r.secondary || 'No email or details'}</span>
                  </span>
                </label>
              ))}
            </div>
          </section>
        ) : null}

        <section className="crm-mt-3">
          <h3 className="merge-dialog__title">Choose the values to keep</h3>
          {error ? <Alert tone="danger">{error}</Alert> : null}
          {loading ? <p className="crm-text-body-secondary">Comparing the records…</p> : null}
          {preview && !loading ? (
            preview.fields.length === 0 ? (
              <p className="crm-text-body-secondary">
                Every property has the same value on both {names.plural}; only their links and
                activity will be combined.
              </p>
            ) : (
              <div className="table-wrap">
                <table className="crm-table merge-table table">
                  <thead>
                    <tr>
                      <th>Property</th>
                      <th>
                        {survivor?.label || preview.survivorLabel}{' '}
                        <span className="badge badge--success">Kept</span>
                      </th>
                      <th>
                        {other?.label || preview.otherLabel}{' '}
                        <span className="badge badge--danger">Deleted</span>
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {preview.fields.map((f) => (
                      <tr key={f.field}>
                        <td className="crm-fw-semibold">{f.label}</td>
                        {(
                          [
                            [preview.survivorId, f.survivorValue],
                            [preview.otherId, f.otherValue],
                          ] as const
                        ).map(([recordId, value]) => {
                          const chosen = picks[f.field] === recordId;
                          return (
                            <td key={recordId}>
                              <label className={cn('merge-table__pick', chosen && 'is-selected')}>
                                <input
                                  type="radio"
                                  name={`merge-${f.field}`}
                                  checked={chosen}
                                  disabled={busy}
                                  onChange={() => pick(f.field, recordId)}
                                />
                                <span>{format(f.field, value)}</span>
                              </label>
                            </td>
                          );
                        })}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )
          ) : null}
          {preview && preview.fields.some((f) => f.field in LINKED) ? (
            <p className="field__help">Pipeline and stage are kept together from the same deal.</p>
          ) : null}
        </section>
      </div>
      <div className="modal__footer">
        <button
          type="button"
          className="btn-crm btn-crm--outline"
          disabled={busy}
          onClick={onClose}
        >
          Cancel
        </button>
        <button
          type="button"
          className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
          disabled={!preview || loading || busy}
          aria-busy={busy}
          onClick={() => void onMerge()}
        >
          {busy ? 'Merging…' : 'Merge'}
        </button>
      </div>
    </CrmModal>
  );
}
