import { and, count, desc, eq, inArray, isNull, sql } from 'drizzle-orm';

import { db } from '@/lib/db';
import { clients } from '@/lib/db/schema/clients';
import { yachts } from '@/lib/db/schema/yachts';
import { companies } from '@/lib/db/schema/companies';
import { interests, interestBerths } from '@/lib/db/schema/interests';
import { berths } from '@/lib/db/schema/berths';
import { invoices, expenses } from '@/lib/db/schema/financial';
import { documents } from '@/lib/db/schema/documents';
import { reminders } from '@/lib/db/schema/operations';
import { systemSettings, auditLogs } from '@/lib/db/schema/system';
import { PIPELINE_STAGES, STAGE_WEIGHTS } from '@/lib/constants';

const DEFAULT_PIPELINE_WEIGHTS: Record<string, number> = STAGE_WEIGHTS;

// "Active" = not archived AND not closed as lost/cancelled. Won interests are
// still counted because they represent revenue. Used everywhere KPIs say
// "active interests" or "pipeline value".
const isActiveInterest = sql`(${interests.outcome} IS NULL OR ${interests.outcome} = 'won')`;

// ─── KPIs ─────────────────────────────────────────────────────────────────────

export async function getKpis(portId: string) {
  const [totalClientsRow] = await db
    .select({ value: count() })
    .from(clients)
    .where(and(eq(clients.portId, portId), isNull(clients.archivedAt)));

  const [activeInterestsRow] = await db
    .select({ value: count() })
    .from(interests)
    .where(and(eq(interests.portId, portId), isNull(interests.archivedAt), isActiveInterest));

  // Pipeline value: SUM each berth's price ONCE regardless of how many active
  // interests reference it. A berth with multiple interests would otherwise be
  // counted multiple times, inflating the total. Reads the primary-berth link
  // via interest_berths (plan §3.4).
  const pipelineRows = await db
    .selectDistinct({ berthId: interestBerths.berthId, price: berths.price })
    .from(interests)
    .innerJoin(
      interestBerths,
      and(eq(interestBerths.interestId, interests.id), eq(interestBerths.isPrimary, true)),
    )
    .innerJoin(berths, eq(interestBerths.berthId, berths.id))
    .where(and(eq(interests.portId, portId), isNull(interests.archivedAt), isActiveInterest));

  const pipelineValueUsd = pipelineRows.reduce((acc, row) => {
    return acc + (row.price ? parseFloat(String(row.price)) : 0);
  }, 0);

  // Occupancy rate: (sold + under_offer) / total * 100
  const allBerthsRows = await db
    .select({ status: berths.status })
    .from(berths)
    .where(eq(berths.portId, portId));

  const totalBerths = allBerthsRows.length;
  const occupiedBerths = allBerthsRows.filter(
    (b) => b.status === 'sold' || b.status === 'under_offer',
  ).length;
  const occupancyRate = totalBerths > 0 ? (occupiedBerths / totalBerths) * 100 : 0;

  return {
    totalClients: totalClientsRow?.value ?? 0,
    activeInterests: activeInterestsRow?.value ?? 0,
    pipelineValueUsd,
    occupancyRate,
  };
}

// ─── Pipeline Counts ──────────────────────────────────────────────────────────

export async function getPipelineCounts(portId: string) {
  const rows = await db
    .select({
      stage: interests.pipelineStage,
      count: sql<number>`count(*)::int`,
    })
    .from(interests)
    .where(and(eq(interests.portId, portId), isNull(interests.archivedAt), isActiveInterest))
    .groupBy(interests.pipelineStage);

  const countsByStage = Object.fromEntries(rows.map((r) => [r.stage, r.count]));

  return PIPELINE_STAGES.map((stage) => ({
    stage,
    count: countsByStage[stage] ?? 0,
  }));
}

// ─── Revenue Forecast ─────────────────────────────────────────────────────────

export async function getRevenueForecast(portId: string) {
  // Load weights from systemSettings
  let weights: Record<string, number> = DEFAULT_PIPELINE_WEIGHTS;
  let weightsSource: 'db' | 'default' = 'default';

  const settingRow = await db.query.systemSettings.findFirst({
    where: and(eq(systemSettings.key, 'pipeline_weights'), eq(systemSettings.portId, portId)),
  });

  if (settingRow?.value) {
    try {
      const parsed = settingRow.value as Record<string, number>;
      if (typeof parsed === 'object' && parsed !== null) {
        weights = parsed;
        weightsSource = 'db';
      }
    } catch {
      // Fall through to defaults
    }
  }

  // Forecast excludes lost/cancelled - only currently-active or won-out
  // interests should affect the weighted pipeline value. Reads the
  // primary-berth link via interest_berths (plan §3.4).
  const interestRows = await db
    .select({
      id: interests.id,
      pipelineStage: interests.pipelineStage,
      berthPrice: berths.price,
    })
    .from(interests)
    .innerJoin(
      interestBerths,
      and(eq(interestBerths.interestId, interests.id), eq(interestBerths.isPrimary, true)),
    )
    .innerJoin(berths, eq(interestBerths.berthId, berths.id))
    .where(and(eq(interests.portId, portId), isNull(interests.archivedAt), isActiveInterest));

  // Build stageBreakdown
  const stageMap: Record<string, { count: number; weightedValue: number }> = {};

  for (const row of interestRows) {
    const stage = row.pipelineStage ?? 'open';
    const price = row.berthPrice ? parseFloat(String(row.berthPrice)) : 0;
    const weight = weights[stage] ?? 0;
    const weighted = price * weight;

    if (!stageMap[stage]) {
      stageMap[stage] = { count: 0, weightedValue: 0 };
    }
    stageMap[stage]!.count += 1;
    stageMap[stage]!.weightedValue += weighted;
  }

  const stageBreakdown = PIPELINE_STAGES.map((stage) => ({
    stage,
    count: stageMap[stage]?.count ?? 0,
    weightedValue: stageMap[stage]?.weightedValue ?? 0,
  }));

  const totalWeightedValue = stageBreakdown.reduce((acc, s) => acc + s.weightedValue, 0);

  return {
    totalWeightedValue,
    stageBreakdown,
    weightsSource,
  };
}

// ─── Compact widget queries ───────────────────────────────────────────────────

/**
 * Berth status split for the donut widget. Returns counts plus the total
 * so the chart can show "12 of 47 sold" alongside the segment percentage.
 */
export async function getBerthStatusDistribution(portId: string) {
  const rows = await db
    .select({ status: berths.status, c: sql<number>`count(*)::int` })
    .from(berths)
    .where(eq(berths.portId, portId))
    .groupBy(berths.status);

  const counts: Record<string, number> = {};
  for (const r of rows) counts[r.status] = r.c;
  const total = Object.values(counts).reduce((a, b) => a + b, 0);

  return {
    total,
    available: counts['available'] ?? 0,
    underOffer: counts['under_offer'] ?? 0,
    sold: counts['sold'] ?? 0,
    maintenance: counts['maintenance'] ?? 0,
  };
}

/**
 * Top 5 active interests closest to closing — ranked by pipeline stage
 * (further = closer to closing) with most-recent activity as a
 * tiebreaker. Surfaces the deals reps should actually be chasing on the
 * dashboard without making them open the pipeline board.
 */
export async function getHotDeals(portId: string, limit = 5) {
  // Stage rank: bigger = closer to closing.
  // Reporting audit caught two stage-name typos: 'in_comms' and
  // 'deposit_10' don't exist in the DB enum — canonical values are
  // 'in_communication' and 'deposit_10pct'. Those two stages were
  // silently collapsing to the ELSE 0 branch.
  const rank = sql<number>`CASE ${interests.pipelineStage}
    WHEN 'completed' THEN 8
    WHEN 'contract_signed' THEN 7
    WHEN 'contract_sent' THEN 6
    WHEN 'deposit_10pct' THEN 5
    WHEN 'eoi_signed' THEN 4
    WHEN 'eoi_sent' THEN 3
    WHEN 'in_communication' THEN 2
    WHEN 'details_sent' THEN 1
    ELSE 0
  END`;

  const rows = await db
    .select({
      id: interests.id,
      stage: interests.pipelineStage,
      clientName: clients.fullName,
      mooring: berths.mooringNumber,
      lastContact: interests.dateLastContact,
      updatedAt: interests.updatedAt,
      rank,
    })
    .from(interests)
    .innerJoin(clients, eq(interests.clientId, clients.id))
    .leftJoin(
      interestBerths,
      and(eq(interestBerths.interestId, interests.id), eq(interestBerths.isPrimary, true)),
    )
    .leftJoin(berths, eq(interestBerths.berthId, berths.id))
    .where(
      and(
        eq(interests.portId, portId),
        isNull(interests.archivedAt),
        isNull(interests.outcome), // exclude won/lost — they're not "closing"
      ),
    )
    .orderBy(desc(rank), desc(interests.updatedAt))
    .limit(limit);

  return rows.map((r) => ({
    id: r.id,
    stage: r.stage,
    clientName: r.clientName,
    mooringNumber: r.mooring,
    lastContact: r.lastContact ? r.lastContact.toISOString() : null,
  }));
}

/**
 * Source-conversion breakdown for the marketing widget. Returns per-
 * source totals (active + won + lost) and a derived conversion rate so
 * reps see which channels deliver buyers vs tire-kickers — orthogonal
 * to the existing "lead source attribution" chart which only counts
 * inbound volume.
 */
export async function getSourceConversion(portId: string) {
  const rows = await db
    .select({
      source: interests.source,
      total: sql<number>`count(*)::int`,
      won: sql<number>`sum(case when ${interests.outcome} = 'won' then 1 else 0 end)::int`,
      lost: sql<number>`sum(case when ${interests.outcome} = 'lost' then 1 else 0 end)::int`,
    })
    .from(interests)
    .where(and(eq(interests.portId, portId), isNull(interests.archivedAt)))
    .groupBy(interests.source);

  return rows
    .filter((r) => r.source)
    .map((r) => ({
      source: r.source!,
      total: r.total,
      won: r.won,
      lost: r.lost,
      conversionRate: r.total > 0 ? r.won / r.total : 0,
    }))
    .sort((a, b) => b.total - a.total);
}

// ─── Recent Activity ──────────────────────────────────────────────────────────

export async function getRecentActivity(portId: string, limit = 20) {
  const rows = await db
    .select({
      id: auditLogs.id,
      action: auditLogs.action,
      entityType: auditLogs.entityType,
      entityId: auditLogs.entityId,
      userId: auditLogs.userId,
      fieldChanged: auditLogs.fieldChanged,
      oldValue: auditLogs.oldValue,
      newValue: auditLogs.newValue,
      metadata: auditLogs.metadata,
      createdAt: auditLogs.createdAt,
    })
    .from(auditLogs)
    .where(eq(auditLogs.portId, portId))
    .orderBy(desc(auditLogs.createdAt))
    .limit(limit);

  // Resolve a human label per row (client name, yacht name, invoice number,
  // …). The dashboard widget previously rendered the bare UUID prefix which
  // told reps nothing about which entity was touched. We batch one SELECT
  // per entityType, capping at the row set's natural size (<= `limit`).
  const byType = new Map<string, Set<string>>();
  for (const r of rows) {
    if (!r.entityId) continue;
    if (!byType.has(r.entityType)) byType.set(r.entityType, new Set());
    byType.get(r.entityType)!.add(r.entityId);
  }

  const labels = new Map<string, string>(); // `${type}:${id}` → label

  async function loadLabels<T extends { id: string }>(
    type: string,
    fetcher: (ids: string[]) => Promise<T[]>,
    pick: (row: T) => string,
  ) {
    const ids = Array.from(byType.get(type) ?? []);
    if (ids.length === 0) return;
    const fetched = await fetcher(ids);
    for (const row of fetched) labels.set(`${type}:${row.id}`, pick(row));
  }

  await Promise.all([
    loadLabels(
      'client',
      (ids) =>
        db
          .select({ id: clients.id, name: clients.fullName })
          .from(clients)
          .where(and(eq(clients.portId, portId), inArray(clients.id, ids))),
      (r) => r.name,
    ),
    loadLabels(
      'yacht',
      (ids) =>
        db
          .select({ id: yachts.id, name: yachts.name })
          .from(yachts)
          .where(and(eq(yachts.portId, portId), inArray(yachts.id, ids))),
      (r) => r.name,
    ),
    loadLabels(
      'company',
      (ids) =>
        db
          .select({ id: companies.id, name: companies.name })
          .from(companies)
          .where(and(eq(companies.portId, portId), inArray(companies.id, ids))),
      (r) => r.name,
    ),
    loadLabels(
      'interest',
      (ids) =>
        db
          .select({ id: interests.id, clientName: clients.fullName })
          .from(interests)
          .innerJoin(clients, eq(interests.clientId, clients.id))
          .where(and(eq(interests.portId, portId), inArray(interests.id, ids))),
      (r) => r.clientName,
    ),
    loadLabels(
      'berth',
      (ids) =>
        db
          .select({ id: berths.id, mooring: berths.mooringNumber })
          .from(berths)
          .where(and(eq(berths.portId, portId), inArray(berths.id, ids))),
      (r) => `Berth ${r.mooring}`,
    ),
    loadLabels(
      'invoice',
      (ids) =>
        db
          .select({ id: invoices.id, num: invoices.invoiceNumber })
          .from(invoices)
          .where(and(eq(invoices.portId, portId), inArray(invoices.id, ids))),
      (r) => r.num,
    ),
    loadLabels(
      'expense',
      (ids) =>
        db
          .select({
            id: expenses.id,
            desc: expenses.description,
            vendor: expenses.establishmentName,
          })
          .from(expenses)
          .where(and(eq(expenses.portId, portId), inArray(expenses.id, ids))),
      (r) => r.desc ?? r.vendor ?? 'Expense',
    ),
    loadLabels(
      'document',
      (ids) =>
        db
          .select({ id: documents.id, title: documents.title })
          .from(documents)
          .where(and(eq(documents.portId, portId), inArray(documents.id, ids))),
      (r) => r.title,
    ),
    loadLabels(
      'reminder',
      (ids) =>
        db
          .select({ id: reminders.id, title: reminders.title })
          .from(reminders)
          .where(and(eq(reminders.portId, portId), inArray(reminders.id, ids))),
      (r) => r.title,
    ),
  ]);

  return rows.map((r) => ({
    ...r,
    label: r.entityId ? (labels.get(`${r.entityType}:${r.entityId}`) ?? null) : null,
  }));
}
