import { NextResponse } from 'next/server'
import {
  getMatters,
  getUpcomingHearings,
  getUnbilledTimeEntries,
  getClientFolders,
  getRetainerBalance,
} from '@/lib/legalApi'

export async function GET() {
  try {
    const [mattersRes, hearings, timeRes, clientsRes] = await Promise.all([
      getMatters({ status: 'open', limit: 20 }),
      getUpcomingHearings(14),
      getUnbilledTimeEntries(),
      getClientFolders({ status: 'active', limit: 50 }),
    ])

    // ── Stats ────────────────────────────────────────────────────
    const now = new Date()
    const weekEnd = new Date(now)
    weekEnd.setDate(now.getDate() + 7)

    const hearingsThisWeek = hearings.filter((h: any) => {
      const d = new Date(h.date)
      return d >= now && d <= weekEnd
    }).length

    const unbilledHours = timeRes.items.reduce((sum: number, e: any) => {
      return sum + (e.durationMinutes ?? 0) / 60
    }, 0)

    // ── Retainer alerts — check active clients with low balances ─
    const retainerAlerts: any[] = []
    for (const cf of clientsRes.items.slice(0, 10)) {
      try {
        const bal = await getRetainerBalance(cf._id)
        if (bal.isLow) {
          retainerAlerts.push({
            clientFolderId: cf._id,
            client: cf.displayName,
            balance: bal.balance,
            currency: 'THB',
            threshold: cf.retainerThreshold ?? 25000,
          })
        }
      } catch {
        // skip if retainer not set up
      }
    }

    // ── Alerts from data ─────────────────────────────────────────
    const alerts: any[] = []

    // Hearings within 2 days
    hearings.forEach((h: any) => {
      const daysUntil = Math.ceil(
        (new Date(h.date).getTime() - Date.now()) / 86400000,
      )
      if (daysUntil <= 2 && daysUntil >= 0) {
        alerts.push({
          id: `hearing-${h._id}`,
          severity: daysUntil === 0 ? 'urgent' : 'warning',
          type: 'hearing_soon',
          matter: h.matter?.title ?? 'Unknown matter',
          client: h.clientFolder?.displayName ?? '',
          message: `Hearing at ${h.court} — ${daysUntil === 0 ? 'today' : 'tomorrow'} ${h.time}`,
          daysUntil,
        })
      }
    })

    // Retainer low balance alerts
    retainerAlerts.forEach(ra => {
      alerts.push({
        id: `retainer-${ra.clientFolderId}`,
        severity: 'warning',
        type: 'retainer_low',
        matter: '',
        client: ra.client,
        message: `Retainer balance ฿${ra.balance.toLocaleString()} — below threshold`,
      })
    })

    // ── Shape matters for frontend types ────────────────────────
    const matters = mattersRes.items.map((m: any) => ({
      id: m._id,
      reference: m.matterNumber,
      client: m.clientFolder?.displayName ?? m.clientFolderId,
      practiceArea: m.practiceArea,
      nextAction: hearings.find((h: any) => h.matterId === m._id)
        ? 'Hearing'
        : 'Review',
      nextActionDate: hearings.find((h: any) => h.matterId === m._id)?.date
        ?? new Date(Date.now() + 7 * 86400000).toISOString().split('T')[0],
      nextActionType: hearings.find((h: any) => h.matterId === m._id)
        ? 'hearing'
        : 'review',
      status: m.status === 'open' ? 'active' : m.status,
    }))

    // ── Shape hearings for frontend types ───────────────────────
    const shapedHearings = hearings.map((h: any) => ({
      id: h._id,
      matterId: h.matterId,
      matter: h.matter?.title ?? 'Unknown matter',
      client: h.clientFolder?.displayName ?? '',
      court: h.court ?? '',
      room: h.room,
      judge: h.judge,
      date: h.date,
      time: h.time,
      status: h.status,
    }))

    return NextResponse.json({
      stats: {
        activeMatters: mattersRes.total,
        hearingsThisWeek,
        unbilledHours: Math.round(unbilledHours * 10) / 10,
        monthlyRevenue: 842000, // TODO: derive from billing data
        currency: 'THB',
      },
      hearings: shapedHearings,
      matters,
      alerts,
      billing: {
        monthlyRevenue: 842000,
        monthlyTarget: 1200000,
        outstanding: 234000,
        overdue: 48000,
        currency: 'THB',
        retainerAlerts,
      },
    })
  } catch (err: any) {
    console.error('Dashboard API error:', err.message)
    return NextResponse.json({ error: 'Failed to load dashboard data' }, { status: 502 })
  }
}
