'use client' import { useEffect, useState } from 'react' import { formatCurrency } from '@rentaldrivego/types' import { API_BASE, apiFetch } from '@/lib/api' import { useDashboardI18n } from '@/components/I18nProvider' interface ReportRow { reservationId: string customerName: string vehicle: string startDate: string endDate: string totalAmount: number source: string paymentStatus: string } interface ReportData { summary: { totalReservations: number totalRentalRevenue: number totalDiscounts: number totalInsurance: number totalAdditionalDrivers: number totalCollected: number totalPricingRulesAdj?: number } rows: ReportRow[] } type ReportPeriod = 'WEEKLY' | 'MONTHLY' | 'QUARTERLY' | 'ANNUAL' export default function ReportsPage() { const { language } = useDashboardI18n() const [period, setPeriod] = useState('MONTHLY') const [report, setReport] = useState(null) const [error, setError] = useState(null) const [exporting, setExporting] = useState(false) const copy = { en: { title: 'Reports', subtitle: 'Accountant-ready exports with totals for insurance, additional drivers, and pricing rules.', exportCsv: 'Export CSV', exporting: 'Exporting…', bookings: 'Bookings', rental: 'Rental', insurance: 'Insurance', drivers: 'Drivers', discounts: 'Discounts', collected: 'Collected', reservation: 'Reservation', vehicle: 'Vehicle', period: 'Period', source: 'Source', payment: 'Payment', total: 'Total', emptyRows: 'No report rows available for this period.', periodLabels: { WEEKLY: 'Weekly', MONTHLY: 'Monthly', QUARTERLY: 'Quarterly', ANNUAL: 'Annual' } as Record, }, fr: { title: 'Rapports', subtitle: 'Exports prêts pour la comptabilité avec les totaux d’assurance, de conducteurs supplémentaires et de règles tarifaires.', exportCsv: 'Exporter en CSV', exporting: 'Export en cours…', bookings: 'Réservations', rental: 'Location', insurance: 'Assurance', drivers: 'Conducteurs', discounts: 'Remises', collected: 'Encaissé', reservation: 'Réservation', vehicle: 'Véhicule', period: 'Période', source: 'Source', payment: 'Paiement', total: 'Total', emptyRows: 'Aucune ligne de rapport pour cette période.', periodLabels: { WEEKLY: 'Hebdomadaire', MONTHLY: 'Mensuel', QUARTERLY: 'Trimestriel', ANNUAL: 'Annuel' } as Record, }, ar: { title: 'التقارير', subtitle: 'ملفات تصدير جاهزة للمحاسبة تشمل إجماليات التأمين والسائقين الإضافيين وقواعد التسعير.', exportCsv: 'تصدير CSV', exporting: 'جارٍ التصدير…', bookings: 'الحجوزات', rental: 'الإيجار', insurance: 'التأمين', drivers: 'السائقون', discounts: 'الخصومات', collected: 'المحصّل', reservation: 'الحجز', vehicle: 'المركبة', period: 'الفترة', source: 'المصدر', payment: 'الدفع', total: 'الإجمالي', emptyRows: 'لا توجد بيانات تقرير لهذه الفترة.', periodLabels: { WEEKLY: 'أسبوعي', MONTHLY: 'شهري', QUARTERLY: 'ربع سنوي', ANNUAL: 'سنوي' } as Record, }, }[language] useEffect(() => { apiFetch(`/analytics/report?period=${period}`) .then(setReport) .catch((err) => setError(err.message)) }, [period]) async function exportCsv() { setExporting(true) setError(null) try { const res = await fetch(`${API_BASE}/analytics/report?period=${period}&format=CSV`, { credentials: 'include', }) if (!res.ok) { const json = await res.json().catch(() => null) throw new Error(json?.message ?? copy.exportCsv) } const csv = await res.text() const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' }) const url = window.URL.createObjectURL(blob) const anchor = document.createElement('a') anchor.href = url anchor.download = `rentaldrivego-${period.toLowerCase()}-report.csv` anchor.click() window.URL.revokeObjectURL(url) } catch (err: any) { setError(err.message ?? copy.exportCsv) } finally { setExporting(false) } } return (

{copy.title}

{copy.subtitle}

{(Object.keys(copy.periodLabels) as ReportPeriod[]).map((option) => ( ))}
{error &&
{error}
} {report && (

{copy.bookings}

{report.summary.totalReservations}

{copy.rental}

{formatCurrency(report.summary.totalRentalRevenue, 'MAD')}

{copy.insurance}

{formatCurrency(report.summary.totalInsurance, 'MAD')}

{copy.drivers}

{formatCurrency(report.summary.totalAdditionalDrivers, 'MAD')}

{copy.discounts}

{formatCurrency(report.summary.totalDiscounts, 'MAD')}

{copy.collected}

{formatCurrency(report.summary.totalCollected, 'MAD')}

)}
{(report?.rows ?? []).map((row) => ( ))} {(report?.rows.length ?? 0) === 0 && ( )}
{copy.reservation} {copy.vehicle} {copy.period} {copy.source} {copy.payment} {copy.total}
{row.customerName} {row.vehicle} {row.startDate} - {row.endDate} {row.source} {row.paymentStatus} {formatCurrency(row.totalAmount, 'MAD')}
{copy.emptyRows}
) }