'use client';

import { useSearchParams } from 'next/navigation';
import { Suspense, useMemo } from 'react';
import { deleteContact, getContact, updateContact } from '@/features/contacts/api.client';
import { listCustomProperties } from '@/features/custom-properties/api.client';
import { getDeal } from '@/features/deals/api.client';
import {
  dismissDuplicate,
  listDuplicates,
  mergeRecords,
  type DuplicateObjectType,
  type DuplicatePair,
} from '@/features/duplicates/api.client';
import { listAllOwners } from '@/features/owners/api.client';
import { apiGet, apiPost } from '@/lib/api/client';
import { DesignFrame, type DesignLive } from './DesignFrame';
import {
  actionObject,
  CONTACT_CITY_PROPERTY,
  designColumns,
  designPair,
  designProps,
  designUsers,
  loadAllPairs,
  mergeRequest,
  type DesignRecord,
} from './manageDuplicatesData';

/* ------------------------------------------------------------------ duplicates */

const DUP_OBJECTS: Array<[string, DuplicateObjectType | null]> = [
  ['contacts', 'contact'],
  ['companies', 'company'],
  ['deals', 'deal'],
  ['events', null],
];
const META: Record<string, Record<string, string>> = {
  contacts: {
    single: 'contact',
    plural: 'contacts',
    Single: 'Contact',
    Plural: 'Contacts',
    list: 'contacts.php',
    name: 'Name',
  },
  companies: {
    single: 'company',
    plural: 'companies',
    Single: 'Company',
    Plural: 'Companies',
    list: 'companies.php',
    name: 'Company name',
  },
  deals: {
    single: 'deal',
    plural: 'deals',
    Single: 'Deal',
    Plural: 'Deals',
    list: 'deals.php',
    name: 'Deal name',
  },
  events: {
    single: 'event',
    plural: 'events',
    Single: 'Event',
    Plural: 'Events',
    list: 'events.php',
    name: 'Event name',
  },
};
/** A deal's values for the merge dialog (deals are unchanged by G6: one record request a side). */
async function dealDetail(id: string): Promise<Partial<DesignRecord>> {
  const d = await getDeal(id);
  return {
    amount: d.amount ? Number(d.amount) : '',
    stage: d.stage.name,
    pipeline: d.pipeline.name,
    closeDate: d.closeDate ?? '',
    owner: d.owner?.name ?? '',
    createDate: d.createdAt.slice(0, 10),
    created: d.createdAt.slice(0, 10),
  };
}

/** Deals' pairs, as before G6: the first 100, with details only on the tab the page opened on. */
async function dealPairs(withDetail: boolean) {
  const page = await listDuplicates({ objectType: 'deal', limit: 100 });
  return Promise.all(
    page.data.map(async (p: DuplicatePair) => {
      const side = async (r: DuplicatePair['a']): Promise<DesignRecord> => ({
        id: r.id,
        name: r.label,
        sub: r.secondary ?? '',
        real: true,
        ...(withDetail ? await dealDetail(r.id).catch(() => ({})) : {}),
      });
      return {
        id: p.matchKey,
        similarity: null,
        found: null,
        a: await side(p.a),
        b: await side(p.b),
      };
    }),
  );
}

/**
 * G6: a contact or company tab's pairs, every page, with details. A failure on the tab the page
 * opened on fails the load (DesignFrame shows the error) rather than showing "no duplicates";
 * another tab's failure leaves that tab empty, as before.
 */
async function recordPairs(
  key: string,
  type: 'contact' | 'company',
  opened: boolean,
  hasCity: boolean,
) {
  const load = loadAllPairs(type, listDuplicates).then((pairs) =>
    pairs.map((p) => designPair(key, p, hasCity)),
  );
  return opened ? load : load.catch(() => []);
}

function ManageDuplicates() {
  const params = useSearchParams();
  const object = META[params.get('object') ?? ''] ? (params.get('object') as string) : 'contacts';

  const live = useMemo<DesignLive>(
    () => ({
      selector: '[data-md-config]',
      load: async () => {
        // G6: the Owner filter's names and whether contacts have City. Either failing leaves
        // that filter or property out; the pairs still show.
        const [properties, owners] = await Promise.all([
          listCustomProperties({ objectType: 'contact' }).catch(() => []),
          listAllOwners().catch(() => []),
        ]);
        const hasCity = properties.some((p) => p.name === CONTACT_CITY_PROPERTY);
        const entries = await Promise.all(
          DUP_OBJECTS.map(async ([key, type]) => {
            const opened = key === object;
            const pairs =
              type === 'contact' || type === 'company'
                ? await recordPairs(key, type, opened, hasCity)
                : type === 'deal'
                  ? await dealPairs(opened).catch(() => [])
                  : [];
            const columns = designColumns(key, hasCity);
            return [
              key,
              {
                meta: META[key],
                props: designProps(key, hasCity),
                pairs,
                ...(columns.length ? { columns } : {}),
              },
            ] as const;
          }),
        );
        return {
          value: {
            logoDomains: {},
            object,
            objects: Object.fromEntries(entries),
            users: designUsers(owners),
            lastScan: new Date().toISOString(),
          },
        };
      },
      onAction: async (type, payload) => {
        // The tab the action was done on, not only the one the page opened on.
        const obj = actionObject(payload, object);
        const objectType = DUP_OBJECTS.find(([k]) => k === obj)?.[1];
        if (!objectType) return;
        if (type === 'reject') {
          const { a, b } = payload as { a: string; b: string };
          await dismissDuplicate({ objectType, aId: a, bId: b });
        }
        if (type === 'merge') {
          await mergeRecords({
            objectType,
            ...mergeRequest(
              obj,
              payload as {
                keep: DesignRecord;
                pair: { a: DesignRecord; b: DesignRecord };
                primary?: 'a' | 'b';
              },
            ),
          });
        }
      },
    }),
    [object],
  );
  return (
    <DesignFrame key={object} page="manage-duplicates" title="Manage Duplicates" live={live} />
  );
}

export function ManageDuplicatesLive() {
  return (
    <Suspense>
      <ManageDuplicates />
    </Suspense>
  );
}

/* ----------------------------------------------------------- formatting issues */

interface IssueRecord {
  id: string;
  name: string | null;
  field: string;
  value: string | null;
  suggestion: string | null;
}
const FIELD_LABEL: Record<string, string> = {
  firstName: 'First name',
  lastName: 'Last name',
  email: 'Email',
  phone: 'Phone number',
};
const LABEL_FIELD: Record<string, string> = {
  'First name': 'firstName',
  'Last name': 'lastName',
  Email: 'email',
};

/** The design's rows (one per record) from the API's issues (one per field). */
async function issueRows(issue: 'name' | 'email') {
  const res = await apiGet<{ data: IssueRecord[] }>('/data-quality/issues', {
    params: { objectType: 'contact', issue, limit: 200 },
  });
  const byId = new Map<string, IssueRecord[]>();
  for (const r of res.data) byId.set(r.id, [...(byId.get(r.id) ?? []), r]);
  const ids = [...byId.keys()].slice(0, 100);
  return Promise.all(
    ids.map(async (id) => {
      const list = byId.get(id)!;
      const email = await getContact(id).then(
        (c) => c.email ?? '',
        () => '',
      );
      return {
        id,
        n: list[0]!.name ?? email ?? 'Contact',
        e: email || id,
        imp: -1,
        issues: [
          [
            'format',
            list.map((r) => [FIELD_LABEL[r.field] ?? r.field, r.value ?? '', r.suggestion ?? '']),
          ],
        ],
      };
    }),
  );
}

function FormattingIssues() {
  const live = useMemo<DesignLive>(
    () => ({
      selector: '[data-fi-config]',
      load: async () => {
        const [name, email] = await Promise.all([issueRows('name'), issueRows('email')]);
        return {
          value: {
            imports: [],
            issueTypes: {
              name: [['format', 'A different format may be preferred']],
              email: [['format', 'A different format may be preferred']],
              location: [],
            },
            monitored: ['Email', 'First Name', 'Last Name'],
            name,
            email,
            location: [],
            tab: 'name',
          },
        };
      },
      onAction: async (type, payload) => {
        const p = payload as {
          tab: 'name' | 'email';
          id: string;
          edits?: Array<[string, string]>;
        };
        if (type === 'fi-accepted') {
          if (p.edits?.length) {
            const body: Record<string, string> = {};
            for (const [label, value] of p.edits) {
              const field = LABEL_FIELD[label];
              if (field) body[field] = value;
            }
            await updateContact(p.id, body);
          } else {
            await apiPost('/data-quality/fix', {
              objectType: 'contact',
              issue: p.tab,
              recordIds: [p.id],
            });
          }
        }
        if (type === 'fi-delete') await deleteContact(p.id);
        // "Reject" keeps the value; the CRM doesn't store rejected issues yet (this browser does).
      },
    }),
    [],
  );
  return <DesignFrame page="formatting-issues" title="Formatting Issues" live={live} />;
}

export function FormattingIssuesLive() {
  return (
    <Suspense>
      <FormattingIssues />
    </Suspense>
  );
}
