import { CrmActivityType, CrmContactStatus, CrmPropertyType, Prisma } from '@prisma/client';
import { z } from 'zod';
import { prismaUnscoped } from '../../lib/prisma';
import { BadRequestError } from '../../lib/errors';
import type { Actor } from './crm-users.service';
import {
  FIELD_LABEL,
  PROPERTY_TYPE_LABEL,
  STATUS_LABEL,
  allMatching,
  assertMember,
  cleanTags,
  cleanUrl,
  emailKeyOf,
  phoneKeyOf,
  type ContactQuery,
} from './crm-contacts.service';
import { addMembers } from './crm-lists.service';
import { notify } from './crm-notify';
import { crmUrl } from './crm-mail';

/**
 * CSV in and out.
 *
 * Import: the browser parses the file and maps its columns, then sends rows
 * of plain strings in batches. Each row is coerced (dates, beds, labels),
 * validated like a typed-in contact, and matched against existing contacts
 * by email or phone; the caller picks whether a match is skipped, updated
 * (filling only the columns the file has) or created anyway. One bad row
 * never sinks the batch — it comes back with its row number and the reason.
 *
 * Export: every matching contact as CSV, with cells that a spreadsheet would
 * run as a formula defused.
 */

export const IMPORT_FIELDS = [
  'firstName',
  'lastName',
  'email',
  'phone',
  'whatsapp',
  'designation',
  'companyName',
  'website',
  'linkedinUrl',
  'city',
  'state',
  'country',
  'address',
  'propertyType',
  'approxBeds',
  'status',
  'source',
  'tags',
  'about',
  'nextFollowUpAt',
  'lastContactedAt',
] as const;
export type ImportField = (typeof IMPORT_FIELDS)[number];
export type ImportRow = Partial<Record<ImportField, string>> & { row: number };

const MAX = {
  firstName: 80, lastName: 80, email: 160, phone: 20, whatsapp: 20, designation: 120, companyName: 160, website: 255,
  linkedinUrl: 255, city: 80, state: 80, country: 80, address: 500, source: 60, about: 2000,
} as const;

function enumFrom<T extends string>(raw: string, labels: Record<T, string>, extra: Record<string, T> = {}): T | undefined {
  const v = raw.trim().toLowerCase().replace(/[\s_-]+/g, '');
  for (const [key, label] of Object.entries(labels) as [T, string][]) {
    if (key.toLowerCase().replace(/_/g, '') === v || label.toLowerCase().replace(/[\s_-]+/g, '') === v) return key;
  }
  return extra[v];
}

/** YYYY-MM-DD, DD/MM/YYYY, DD-MM-YYYY (Indian order), or anything Date parses with a 4-digit year. */
export function parseDate(raw: string): Date | undefined {
  const v = raw.trim();
  let m = /^(\d{4})-(\d{1,2})-(\d{1,2})(?:[ T](\d{1,2}):(\d{2}))?/.exec(v);
  if (m) return new Date(Date.UTC(+m[1], +m[2] - 1, +m[3], m[4] ? +m[4] - 5 : 4, m[5] ? +m[5] - 30 : 30)); // IST wall time; date-only = 10:00 IST
  m = /^(\d{1,2})[/.-](\d{1,2})[/.-](\d{4})$/.exec(v);
  if (m) return new Date(Date.UTC(+m[3], +m[2] - 1, +m[1], 4, 30));
  if (/\d{4}/.test(v)) {
    const d = new Date(v);
    if (!Number.isNaN(d.getTime())) return d;
  }
  return undefined;
}

const emailRe = z.string().email();

/** One row of strings → contact fields, or the first reason it cannot be. */
function coerce(r: ImportRow): { data: Prisma.CrmContactUncheckedCreateInput } | { error: string } {
  const get = (k: ImportField) => (r[k] ?? '').toString().trim();
  const firstName = get('firstName');
  if (!firstName) return { error: 'First name is missing' };
  const d: Record<string, unknown> = { firstName };
  for (const k of ['lastName', 'designation', 'companyName', 'city', 'state', 'country', 'address', 'source', 'about', 'whatsapp'] as const) {
    const v = get(k);
    if (v) d[k] = v;
  }
  for (const [k, max] of Object.entries(MAX) as [keyof typeof MAX, number][]) {
    const v = get(k as ImportField);
    if (v.length > max) return { error: `${k} is longer than ${max} characters` };
  }
  const email = get('email');
  if (email) {
    if (!emailRe.safeParse(email).success) return { error: `"${email}" is not a valid email` };
    d.email = email.toLowerCase();
    d.emailKey = emailKeyOf(email);
  }
  const phone = get('phone');
  if (phone) {
    if (!/^[0-9+()\-\s.]{5,20}$/.test(phone)) return { error: `"${phone}" is not a valid phone number` };
    d.phone = phone;
    d.phoneKey = phoneKeyOf(phone);
  }
  for (const k of ['website', 'linkedinUrl'] as const) {
    const v = get(k);
    if (v) d[k] = cleanUrl(v);
  }
  const pt = get('propertyType');
  if (pt) {
    const v = enumFrom<CrmPropertyType>(pt, PROPERTY_TYPE_LABEL, { pg: CrmPropertyType.PG, payingguest: CrmPropertyType.PG, coliving: CrmPropertyType.COLIVING, dorm: CrmPropertyType.DORMITORY, college: CrmPropertyType.UNIVERSITY });
    if (!v) return { error: `Property type "${pt}" is not one of ${Object.values(PROPERTY_TYPE_LABEL).join(', ')}` };
    d.propertyType = v;
  }
  const beds = get('approxBeds');
  if (beds) {
    const n = Number(beds.replace(/[,\s]/g, ''));
    if (!Number.isInteger(n) || n < 0 || n > 100_000) return { error: `Beds "${beds}" is not a whole number` };
    d.approxBeds = n;
  }
  const st = get('status');
  if (st) {
    const v = enumFrom<CrmContactStatus>(st, STATUS_LABEL, { converted: CrmContactStatus.CUSTOMER, won: CrmContactStatus.CUSTOMER, lead: CrmContactStatus.NEW });
    if (!v) return { error: `Status "${st}" is not one of ${Object.values(STATUS_LABEL).join(', ')}` };
    d.status = v;
  }
  const tags = get('tags');
  if (tags) d.tags = cleanTags(tags.split(/[;,|]/)).slice(0, 20);
  for (const k of ['nextFollowUpAt', 'lastContactedAt'] as const) {
    const v = get(k);
    if (!v) continue;
    const date = parseDate(v);
    if (!date) return { error: `"${v}" is not a date (use YYYY-MM-DD or DD/MM/YYYY)` };
    d[k] = date;
  }
  return { data: d as Prisma.CrmContactUncheckedCreateInput };
}

export interface ImportOptions {
  duplicateMode: 'skip' | 'update' | 'create';
  listId?: string | null;
  ownerId?: string | null;
  defaultStatus?: CrmContactStatus;
  defaultSource?: string | null;
  fileName?: string | null;
}

export async function importContacts(rows: ImportRow[], opts: ImportOptions, actor: Actor) {
  if (opts.ownerId) await assertMember(opts.ownerId);
  if (opts.listId && !(await prismaUnscoped.crmList.findUnique({ where: { id: opts.listId }, select: { id: true } }))) {
    throw new BadRequestError('That list no longer exists.', 'LIST_NOT_FOUND');
  }
  const result = { created: 0, updated: 0, skipped: 0, failed: 0, errors: [] as { row: number; message: string }[] };
  const prepared = rows.map((r) => ({ row: r.row, ...coerce(r) }));

  // Everything this batch could match, in one query; kept current as rows are written.
  const emails = prepared.flatMap((p) => ('data' in p && p.data.emailKey ? [p.data.emailKey] : []));
  const phones = prepared.flatMap((p) => ('data' in p && p.data.phoneKey ? [p.data.phoneKey] : []));
  const existing = emails.length || phones.length
    ? await prismaUnscoped.crmContact.findMany({
        where: { deletedAt: null, OR: [{ emailKey: { in: emails } }, { phoneKey: { in: phones } }] },
        select: { id: true, emailKey: true, phoneKey: true },
      })
    : [];
  const byEmail = new Map(existing.filter((e) => e.emailKey).map((e) => [e.emailKey!, e.id]));
  const byPhone = new Map(existing.filter((e) => e.phoneKey).map((e) => [e.phoneKey!, e.id]));
  const touched: string[] = [];

  for (const p of prepared) {
    if ('error' in p) {
      result.failed++;
      result.errors.push({ row: p.row, message: p.error });
      continue;
    }
    const data = p.data;
    const match = (data.emailKey && byEmail.get(data.emailKey)) || (data.phoneKey && byPhone.get(data.phoneKey)) || null;
    try {
      if (match && opts.duplicateMode === 'skip') {
        result.skipped++;
        continue;
      }
      if (match && opts.duplicateMode === 'update') {
        // Fill in what the file has; never blank out what it does not.
        const { firstName: _f, ...rest } = data;
        const before = await prismaUnscoped.crmContact.findUnique({ where: { id: match } });
        const prev = (before ?? {}) as Record<string, unknown>;
        const plain = (v: unknown) => (v instanceof Date ? v.toISOString() : v ?? null);
        const changes = Object.entries(rest)
          .filter(([k, v]) => k in FIELD_LABEL && JSON.stringify(plain(prev[k])) !== JSON.stringify(plain(v)))
          .map(([k, v]) => ({ field: k, label: FIELD_LABEL[k as keyof typeof FIELD_LABEL], from: plain(prev[k]), to: plain(v) }));
        await prismaUnscoped.$transaction([
          prismaUnscoped.crmContact.update({ where: { id: match }, data: { ...rest, updatedById: actor.id } }),
          prismaUnscoped.crmActivity.create({
            data: { contactId: match, type: CrmActivityType.UPDATED, changes: changes as Prisma.InputJsonValue, meta: { import: opts.fileName ?? true }, actorId: actor.id, actorName: actor.name },
          }),
        ]);
        result.updated++;
        touched.push(match);
        continue;
      }
      const created = await prismaUnscoped.$transaction(async (tx) => {
        const c = await tx.crmContact.create({
          data: {
            ...data,
            status: data.status ?? opts.defaultStatus ?? CrmContactStatus.NEW,
            source: data.source ?? (opts.defaultSource || null),
            ownerId: opts.ownerId === undefined ? actor.id : opts.ownerId,
            createdById: actor.id,
            updatedById: actor.id,
          },
          select: { id: true, emailKey: true, phoneKey: true },
        });
        await tx.crmActivity.create({
          data: { contactId: c.id, type: CrmActivityType.IMPORTED, meta: { fileName: opts.fileName ?? null }, actorId: actor.id, actorName: actor.name },
        });
        return c;
      });
      if (created.emailKey) byEmail.set(created.emailKey, created.id);
      if (created.phoneKey) byPhone.set(created.phoneKey, created.id);
      result.created++;
      touched.push(created.id);
    } catch (e) {
      result.failed++;
      result.errors.push({ row: p.row, message: e instanceof Error ? 'Could not be saved' : String(e) });
    }
  }
  if (opts.listId && touched.length) await addMembers(opts.listId, touched, actor);
  if (result.created || result.updated) {
    notify({
      actor,
      text: `${actor.name} imported ${result.created} new contact${result.created === 1 ? '' : 's'}${result.updated ? ` and updated ${result.updated}` : ''}${opts.fileName ? ` from ${opts.fileName}` : ''}${opts.ownerId && opts.ownerId !== actor.id ? ', owned by you' : ''}`,
      url: crmUrl('contacts'),
      about: [opts.ownerId],
    });
  }
  return result;
}

// ── Export ─────────────────────────────────────────────────────────────────

/** Quote for CSV, and stop a spreadsheet from running a cell as a formula. */
export function csvCell(v: unknown): string {
  let s = v === null || v === undefined ? '' : v instanceof Date ? v.toISOString().slice(0, 10) : Array.isArray(v) ? v.join('; ') : String(v);
  if (/^[=+\-@\t\r]/.test(s)) s = `'${s}`;
  return /[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
}

export async function exportContacts(query: ContactQuery) {
  const rows = await allMatching(query);
  const header = [
    'First name', 'Last name', 'Email', 'Phone', 'WhatsApp', 'Designation', 'Company', 'Website', 'LinkedIn', 'City', 'State',
    'Country', 'Address', 'Property type', 'Approx beds', 'Status', 'Source', 'Tags', 'Owner', 'Next follow-up', 'Last contacted',
    'About', 'Created', 'Updated',
  ];
  const lines = rows.map((c) =>
    [
      c.firstName, c.lastName, c.email, c.phone, c.whatsapp, c.designation, c.companyName, c.website, c.linkedinUrl, c.city, c.state,
      c.country, c.address, c.propertyType ? PROPERTY_TYPE_LABEL[c.propertyType] : '', c.approxBeds, STATUS_LABEL[c.status], c.source,
      c.tags, c.owner?.name, c.nextFollowUpAt, c.lastContactedAt, c.about, c.createdAt, c.updatedAt,
    ].map(csvCell).join(','),
  );
  // A BOM so Excel opens the UTF-8 (₹, Hindi names) correctly.
  return { csv: `\uFEFF${[header.join(','), ...lines].join('\r\n')}\r\n`, count: rows.length };
}
