'use client';

/**
 * HUB-315: "Manage duplicates" for contacts, companies or deals: the pairs the CRM suggests as
 * duplicates (HUB-314), with Review (merge preview and merge) and Dismiss (not a duplicate).
 * Laid out like the import "Check for duplicates" step (import-duplicates.php).
 */
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useCallback, useEffect, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { useToast } from '@/components/crm/ToastProvider';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { mergeScopeOf } from '@/features/auth/record-access';
import { isScopedRuleObject } from '@/features/permission-sets/api.client';
import { errorText } from '@/lib/api/errors';
import {
  dismissDuplicate,
  listDuplicates,
  MATCH_LABEL,
  OBJECT_NAMES,
  type DuplicateObjectType,
  type DuplicatePair,
} from '../api.client';
import { MergeDialog } from './MergeDialog';

const MATCH_RULES: Record<DuplicateObjectType, string> = {
  contact: 'Contacts are matched by email address, then by full name, then by phone number.',
  company: 'Companies are matched by domain, then by company name.',
  deal: 'Deals are matched by name when they belong to the same company.',
};

const PAGE = 25;

function RecordCell({
  path,
  id,
  label,
  secondary,
}: {
  path: string;
  id: string;
  label: string;
  secondary: string | null;
}) {
  return (
    <>
      <Link href={`${path}/${id}`} className="link crm-fw-semibold">
        {label || 'Unnamed'}
      </Link>
      {secondary ? (
        <>
          <br />
          <span className="crm-text-muted crm-fs-8">{secondary}</span>
        </>
      ) : null}
    </>
  );
}

export function DuplicatesView({ objectType }: { objectType: DuplicateObjectType }) {
  const me = useCurrentUser();
  const router = useRouter();
  const toast = useToast();
  const names = OBJECT_NAMES[objectType];
  const title = names.plural.charAt(0).toUpperCase() + names.plural.slice(1);
  const rule = me.permissionSet.rules.objects[objectType];
  // P2a: contacts and companies merge by the set's Merge scope; deals still need edit and
  // delete rights (the API checks each record again).
  const scopedMerge = isScopedRuleObject(objectType);
  const canMerge = scopedMerge
    ? mergeScopeOf(rule) !== 'none'
    : rule.edit !== 'none' && rule.delete;
  const canDismiss = rule.edit !== 'none';

  const [pairs, setPairs] = useState<DuplicatePair[]>([]);
  const [total, setTotal] = useState<number | null>(null);
  const [cursor, setCursor] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [dismissed, setDismissed] = useState(0);
  const [busyKey, setBusyKey] = useState<string | null>(null);
  const [reviewing, setReviewing] = useState<DuplicatePair | null>(null);

  const load = useCallback(
    async (after: string | null) => {
      setLoading(true);
      setError(null);
      try {
        const page = await listDuplicates({
          objectType,
          limit: PAGE,
          ...(after ? { cursor: after } : {}),
        });
        setPairs((current) => (after ? [...current, ...page.data] : page.data));
        setCursor(page.nextCursor);
        if (typeof page.total === 'number') setTotal(page.total);
      } catch (err) {
        setError(errorText(err));
      } finally {
        setLoading(false);
      }
    },
    [objectType],
  );

  useEffect(() => {
    void load(null);
  }, [load]);

  const onDismiss = async (pair: DuplicatePair) => {
    setBusyKey(pair.matchKey);
    try {
      await dismissDuplicate({ objectType, aId: pair.a.id, bId: pair.b.id });
      setPairs((current) => current.filter((p) => p.matchKey !== pair.matchKey));
      setTotal((n) => (n === null ? n : Math.max(0, n - 1)));
      setDismissed((n) => n + 1);
      toast('Marked as not a duplicate.', 'success');
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusyKey(null);
    }
  };

  const shownTotal = total ?? pairs.length;

  return (
    <div className="duplicates-page">
      <header className="company-record-header">
        <nav className="company-record-breadcrumb" aria-label="Breadcrumb">
          <Link href={names.path}>{title}</Link>
          <span aria-hidden>/</span>
          <span>Manage duplicates</span>
        </nav>
      </header>

      <div className="import-wizard__heading">
        <h1>Manage duplicates</h1>
        <p>
          Review {names.plural} that may be the same, then merge them or mark them as not a
          duplicate.
        </p>
      </div>

      <section className="import-card">
        <div className="import-card__head">
          <h2>Possible duplicates</h2>
          <p>{MATCH_RULES[objectType]}</p>
        </div>
        <div className="import-card__body">
          <div className="import-duplicate-summary">
            <div className="import-stat import-stat--warning">
              <span>Possible duplicates</span>
              <strong>{loading && total === null ? '…' : shownTotal.toLocaleString()}</strong>
            </div>
            <div className="import-stat">
              <span>Shown below</span>
              <strong>{pairs.length.toLocaleString()}</strong>
            </div>
            <div className="import-stat">
              <span>Dismissed this session</span>
              <strong>{dismissed.toLocaleString()}</strong>
            </div>
          </div>
          {!canMerge ? (
            <Alert tone="info">
              Your permissions don&apos;t allow you to merge {names.plural}
              {scopedMerge ? '.' : ': it needs edit and delete rights.'}
            </Alert>
          ) : null}
        </div>
      </section>

      <section className="import-card crm-mt-3 import-duplicate-card">
        <div className="import-card__body" style={{ padding: 0 }}>
          {error ? (
            <div className="crm-p-3">
              <Alert tone="danger">{error}</Alert>
            </div>
          ) : null}
          <div className="table-wrap">
            <table className="crm-table import-table import-table-duplicates table">
              <thead>
                <tr>
                  <th>{names.singular.charAt(0).toUpperCase() + names.singular.slice(1)}</th>
                  <th>Possible duplicate</th>
                  <th>Matched by</th>
                  <th className="col-actions">
                    <span className="crm-visually-hidden">Actions</span>
                  </th>
                </tr>
              </thead>
              <tbody>
                {pairs.map((pair) => (
                  <tr key={pair.matchKey}>
                    <td>
                      <RecordCell path={names.path} {...pair.a} />
                    </td>
                    <td>
                      <RecordCell path={names.path} {...pair.b} />
                    </td>
                    <td>
                      <span className="badge badge--info">{MATCH_LABEL[pair.reason]}</span>
                    </td>
                    <td className="col-actions">
                      <div className="duplicates-page__actions">
                        <button
                          type="button"
                          className="btn-crm btn-crm--primary btn-crm--sm"
                          disabled={!canMerge || busyKey === pair.matchKey}
                          title={
                            canMerge
                              ? undefined
                              : scopedMerge
                                ? 'Needs merge rights'
                                : 'Needs edit and delete rights'
                          }
                          onClick={() => setReviewing(pair)}
                        >
                          Review
                        </button>
                        <button
                          type="button"
                          className="btn-crm btn-crm--outline btn-crm--sm"
                          disabled={!canDismiss || busyKey === pair.matchKey}
                          onClick={() => void onDismiss(pair)}
                        >
                          Dismiss
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
                {!loading && pairs.length === 0 && !error ? (
                  <tr>
                    <td colSpan={4} className="crm-text-body-secondary duplicates-page__empty">
                      No possible duplicate {names.plural} right now.
                    </td>
                  </tr>
                ) : null}
                {loading ? (
                  <tr>
                    <td colSpan={4} className="crm-text-body-secondary">
                      Looking for duplicates…
                    </td>
                  </tr>
                ) : null}
              </tbody>
            </table>
          </div>
        </div>
      </section>

      <div className="import-actions">
        <Link href={names.path} className="import-btn btn-crm btn-crm--outline">
          Back to {names.plural}
        </Link>
        {cursor ? (
          <div className="import-actions__right">
            <button
              type="button"
              className="import-btn btn-crm btn-crm--outline"
              disabled={loading}
              onClick={() => void load(cursor)}
            >
              Show more
            </button>
          </div>
        ) : null}
      </div>

      <MergeDialog
        open={reviewing !== null}
        objectType={objectType}
        records={reviewing ? [reviewing.a, reviewing.b] : null}
        keepId={reviewing?.a.id}
        onClose={() => setReviewing(null)}
        onMerged={(result) => {
          setReviewing(null);
          router.push(`${names.path}/${result.survivorId}`);
        }}
      />
    </div>
  );
}
