import { CrmStageKind, Prisma } from '@prisma/client';
import { prismaUnscoped } from '../../lib/prisma';
import { ist, istAt, istDayStart } from './crm-mail';
import { dealRef } from './crm-deals.service';
import { ensureStages } from './crm-stages.service';
import { fullName } from './crm-contacts.service';

/**
 * The CRM dashboard: the figures a sales team runs on, for "me" (what I own
 * or am assigned) or the whole team. India calendar months throughout.
 */

const DAY = 86_400_000;

function monthStart(now: Date, offset = 0) {
  const { date } = ist(now);
  const [y, m] = date.split('-').map(Number);
  const d = new Date(Date.UTC(y, m - 1 + offset, 1));
  return istAt(d.toISOString().slice(0, 10), 0);
}

const pct = (a: number, b: number) => (b ? Math.round(((a - b) / b) * 100) : null);

export async function dashboard(scope: 'me' | 'team', meId: string, now = new Date()) {
  await ensureStages();
  const mine = scope === 'me';
  const dealScope: Prisma.CrmDealWhereInput = { deletedAt: null, ...(mine ? { assigneeId: meId } : {}) };
  const contactScope: Prisma.CrmContactWhereInput = { deletedAt: null, ...(mine ? { ownerId: meId } : {}) };
  const today = istDayStart(now);
  const tomorrow = new Date(today.getTime() + DAY);
  const thisMonth = monthStart(now);
  const lastMonth = monthStart(now, -1);
  const nextMonth = monthStart(now, 1);
  const yearAgo = monthStart(now, -11);
  const ninety = new Date(now.getTime() - 90 * DAY);

  const [stages, open, wonRecent, lostRecent, won12, lost12, contactsNew, followContacts, followDeals, tasks, sources, people] = await Promise.all([
    prismaUnscoped.crmStage.findMany({ orderBy: { position: 'asc' } }),
    prismaUnscoped.crmDeal.findMany({
      where: { ...dealScope, stage: { kind: CrmStageKind.OPEN } },
      select: { id: true, number: true, title: true, value: true, probability: true, stageId: true, expectedCloseDate: true, updatedAt: true, assigneeId: true, stage: { select: { probability: true } } },
    }),
    prismaUnscoped.crmDeal.findMany({ where: { ...dealScope, stage: { kind: CrmStageKind.WON }, wonAt: { gte: lastMonth } }, select: { value: true, wonAt: true } }),
    prismaUnscoped.crmDeal.count({ where: { ...dealScope, stage: { kind: CrmStageKind.LOST }, lostAt: { gte: ninety } } }),
    prismaUnscoped.crmDeal.findMany({ where: { ...dealScope, stage: { kind: CrmStageKind.WON }, wonAt: { gte: yearAgo } }, select: { value: true, wonAt: true, createdAt: true, assigneeId: true, source: true } }),
    prismaUnscoped.crmDeal.findMany({ where: { ...dealScope, stage: { kind: CrmStageKind.LOST }, lostAt: { gte: yearAgo } }, select: { lostAt: true } }),
    prismaUnscoped.crmContact.findMany({ where: { ...contactScope, createdAt: { gte: lastMonth } }, select: { createdAt: true } }),
    prismaUnscoped.crmContact.findMany({ where: { ...contactScope, nextFollowUpAt: { lt: tomorrow } }, orderBy: { nextFollowUpAt: 'asc' }, take: 50, select: { id: true, firstName: true, lastName: true, companyName: true, nextFollowUpAt: true } }),
    prismaUnscoped.crmDeal.findMany({ where: { ...dealScope, stage: { kind: CrmStageKind.OPEN }, nextActionAt: { lt: tomorrow } }, orderBy: { nextActionAt: 'asc' }, take: 50, select: { id: true, number: true, title: true, nextStep: true, nextActionAt: true } }),
    prismaUnscoped.crmTask.findMany({
      where: { done: false, dueAt: { lt: tomorrow }, ...(mine ? { assigneeId: meId } : {}), OR: [{ dealId: null }, { deal: { deletedAt: null } }] },
      orderBy: { dueAt: 'asc' },
      take: 50,
      include: { deal: { select: { id: true, number: true } }, assignee: { select: { id: true, name: true } } },
    }),
    prismaUnscoped.crmDeal.findMany({ where: { ...dealScope, createdAt: { gte: yearAgo } }, select: { source: true, value: true, stage: { select: { kind: true } } } }),
    prismaUnscoped.user.findMany({ where: { role: { in: ['CRM_USER', 'SUPER_ADMIN'] }, deactivatedAt: null }, select: { id: true, name: true } }),
  ]);

  const weighted = (d: { value: number; probability: number | null; stage: { probability: number } }) => (d.value * (d.probability ?? d.stage.probability)) / 100;
  const wonThis = wonRecent.filter((d) => d.wonAt! >= thisMonth);
  const wonLast = wonRecent.filter((d) => d.wonAt! < thisMonth);
  const won90 = won12.filter((d) => d.wonAt! >= ninety);
  const lastActivity = await prismaUnscoped.crmActivity.groupBy({
    by: ['dealId'],
    where: { dealId: { in: open.map((d) => d.id) } },
    _max: { createdAt: true },
  });
  const quietSince = new Date(now.getTime() - 14 * DAY);
  const stale = open
    .filter((d) => {
      const last = lastActivity.find((a) => a.dealId === d.id)?._max.createdAt ?? d.updatedAt;
      return last < quietSince;
    })
    .map((d) => ({ id: d.id, ref: dealRef(d.number), title: d.title, value: d.value, quietDays: Math.floor((now.getTime() - (lastActivity.find((a) => a.dealId === d.id)?._max.createdAt ?? d.updatedAt).getTime()) / DAY) }))
    .sort((a, b) => b.quietDays - a.quietDays);

  // Twelve India months, oldest first.
  const trend = Array.from({ length: 12 }, (_, i) => {
    const from = monthStart(now, i - 11);
    const to = monthStart(now, i - 10);
    const w = won12.filter((d) => d.wonAt! >= from && d.wonAt! < to);
    return {
      month: ist(from).date.slice(0, 7),
      wonValue: w.reduce((s, d) => s + d.value, 0),
      wonCount: w.length,
      lostCount: lost12.filter((d) => d.lostAt! >= from && d.lostAt! < to).length,
    };
  });

  const funnel = stages
    .filter((s) => s.kind === CrmStageKind.OPEN)
    .map((s) => {
      const ds = open.filter((d) => d.stageId === s.id);
      return { stageId: s.id, name: s.name, color: s.color, probability: s.probability, count: ds.length, value: ds.reduce((a, d) => a + d.value, 0) };
    });

  // Deals opened in the last 12 months by source, and how many of those same deals were won.
  const bySource = new Map<string, { source: string; deals: number; won: number; wonValue: number }>();
  for (const d of sources) {
    const key = d.source ?? 'Not set';
    const row = bySource.get(key) ?? { source: key, deals: 0, won: 0, wonValue: 0 };
    row.deals++;
    if (d.stage.kind === CrmStageKind.WON) {
      row.won++;
      row.wonValue += d.value;
    }
    bySource.set(key, row);
  }
  const sourceRows = [...bySource.values()].sort((a, b) => b.deals - a.deals);

  // The team's standings this month: won, pipeline and overdue tasks per person.
  let leaderboard: { id: string; name: string; wonValue: number; wonCount: number; openValue: number; overdueTasks: number }[] = [];
  if (!mine) {
    const [teamOpen, teamWon, overdue] = await Promise.all([
      prismaUnscoped.crmDeal.groupBy({ by: ['assigneeId'], where: { deletedAt: null, stage: { kind: CrmStageKind.OPEN } }, _sum: { value: true } }),
      prismaUnscoped.crmDeal.groupBy({ by: ['assigneeId'], where: { deletedAt: null, stage: { kind: CrmStageKind.WON }, wonAt: { gte: thisMonth } }, _sum: { value: true }, _count: { _all: true } }),
      prismaUnscoped.crmTask.groupBy({ by: ['assigneeId'], where: { done: false, dueAt: { lt: now }, OR: [{ dealId: null }, { deal: { deletedAt: null } }] }, _count: { _all: true } }),
    ]);
    leaderboard = people
      .map((p) => ({
        id: p.id,
        name: p.name,
        wonValue: teamWon.find((g) => g.assigneeId === p.id)?._sum.value ?? 0,
        wonCount: teamWon.find((g) => g.assigneeId === p.id)?._count._all ?? 0,
        openValue: teamOpen.find((g) => g.assigneeId === p.id)?._sum.value ?? 0,
        overdueTasks: overdue.find((g) => g.assigneeId === p.id)?._count._all ?? 0,
      }))
      .filter((r) => r.wonValue || r.openValue || r.overdueTasks)
      .sort((a, b) => b.wonValue - a.wonValue || b.openValue - a.openValue);
  }

  const late = (d: Date | null) => !!d && d < today;
  const myWork = [
    ...tasks.map((t) => ({ kind: 'task' as const, id: t.id, title: t.title, sub: t.deal ? dealRef(t.deal.number) : null, dealId: t.deal?.id ?? null, contactId: null, at: t.dueAt, overdue: late(t.dueAt), who: t.assignee?.name ?? null })),
    ...followDeals.map((d) => ({ kind: 'deal' as const, id: d.id, title: d.nextStep ?? `Next action on ${dealRef(d.number)}`, sub: `${dealRef(d.number)} · ${d.title}`, dealId: d.id, contactId: null, at: d.nextActionAt, overdue: late(d.nextActionAt), who: null })),
    ...followContacts.map((c) => ({ kind: 'contact' as const, id: c.id, title: `Follow up with ${fullName(c)}`, sub: c.companyName, dealId: null, contactId: c.id, at: c.nextFollowUpAt, overdue: late(c.nextFollowUpAt), who: null })),
  ].sort((a, b) => (a.at?.getTime() ?? 0) - (b.at?.getTime() ?? 0));

  const wonThisValue = wonThis.reduce((s, d) => s + d.value, 0);
  const wonLastValue = wonLast.reduce((s, d) => s + d.value, 0);
  return {
    scope,
    pipeline: {
      openCount: open.length,
      openValue: open.reduce((s, d) => s + d.value, 0),
      weighted: Math.round(open.reduce((s, d) => s + weighted(d), 0)),
      closingThisMonth: open.filter((d) => d.expectedCloseDate && d.expectedCloseDate >= thisMonth && d.expectedCloseDate < nextMonth).length,
      closeDatePassed: open.filter((d) => d.expectedCloseDate && d.expectedCloseDate < today).length,
    },
    won: {
      thisMonth: { count: wonThis.length, value: wonThisValue },
      lastMonth: { count: wonLast.length, value: wonLastValue },
      change: pct(wonThisValue, wonLastValue),
      winRate90: won90.length + lostRecent ? Math.round((won90.length / (won90.length + lostRecent)) * 100) : null,
      avgDealSize90: won90.length ? Math.round(won90.reduce((s, d) => s + d.value, 0) / won90.length) : null,
      avgDaysToClose90: won90.length ? Math.round(won90.reduce((s, d) => s + (d.wonAt!.getTime() - d.createdAt.getTime()) / DAY, 0) / won90.length) : null,
    },
    contacts: {
      newThisWeek: contactsNew.filter((c) => c.createdAt >= new Date(today.getTime() - 6 * DAY)).length,
      newThisMonth: contactsNew.filter((c) => c.createdAt >= thisMonth).length,
      newLastMonth: contactsNew.filter((c) => c.createdAt < thisMonth).length,
    },
    followUps: {
      dueToday: myWork.filter((w) => !w.overdue).length,
      overdue: myWork.filter((w) => w.overdue).length,
    },
    stale: { count: stale.length, deals: stale.slice(0, 8) },
    funnel,
    trend,
    sources: sourceRows,
    leaderboard,
    myWork: myWork.slice(0, 15),
  };
}

