'use client'

import { useEffect, useState } from 'react'
import { formatCurrency } from '@rentaldrivego/types'
import { API_BASE, apiFetch, EMPLOYEE_TOKEN_KEY } from '@/lib/api'

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'

const periodLabels: Record<ReportPeriod, string> = {
  WEEKLY: 'Weekly',
  MONTHLY: 'Monthly',
  QUARTERLY: 'Quarterly',
  ANNUAL: 'Annual',
}

export default function ReportsPage() {
  const [period, setPeriod] = useState<ReportPeriod>('MONTHLY')
  const [report, setReport] = useState<ReportData | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [exporting, setExporting] = useState(false)

  useEffect(() => {
    apiFetch<ReportData>(`/analytics/report?period=${period}`)
      .then(setReport)
      .catch((err) => setError(err.message))
  }, [period])

  async function exportCsv() {
    setExporting(true)
    setError(null)
    try {
      const token = window.localStorage.getItem(EMPLOYEE_TOKEN_KEY)
      const res = await fetch(`${API_BASE}/analytics/report?period=${period}&format=CSV`, {
        headers: token ? { Authorization: `Bearer ${token}` } : {},
      })
      if (!res.ok) {
        const json = await res.json().catch(() => null)
        throw new Error(json?.message ?? 'Export failed')
      }
      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 ?? 'Export failed')
    } finally {
      setExporting(false)
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
        <div>
          <h2 className="text-xl font-semibold text-slate-900">Reports</h2>
          <p className="mt-1 text-sm text-slate-500">Accountant-ready exports with insurance, additional-driver, and pricing-rule totals.</p>
        </div>
        <div className="flex flex-wrap gap-2">
          {(Object.keys(periodLabels) as ReportPeriod[]).map((option) => (
            <button
              key={option}
              onClick={() => setPeriod(option)}
              className={`rounded-full px-4 py-2 text-sm font-semibold ${period === option ? 'bg-slate-900 text-white' : 'border border-slate-300 text-slate-700'}`}
            >
              {periodLabels[option]}
            </button>
          ))}
          <button onClick={exportCsv} disabled={exporting} className="rounded-full border border-slate-900 px-4 py-2 text-sm font-semibold text-slate-900">
            {exporting ? 'Exporting…' : 'Export CSV'}
          </button>
        </div>
      </div>

      {error && <div className="card p-6 text-sm text-red-600">{error}</div>}

      {report && (
        <div className="grid grid-cols-2 gap-4 lg:grid-cols-6">
          <div className="card p-5"><p className="text-sm text-slate-500">Bookings</p><p className="mt-1 text-2xl font-bold text-slate-900">{report.summary.totalReservations}</p></div>
          <div className="card p-5"><p className="text-sm text-slate-500">Rental</p><p className="mt-1 text-2xl font-bold text-slate-900">{formatCurrency(report.summary.totalRentalRevenue, 'MAD')}</p></div>
          <div className="card p-5"><p className="text-sm text-slate-500">Insurance</p><p className="mt-1 text-2xl font-bold text-slate-900">{formatCurrency(report.summary.totalInsurance, 'MAD')}</p></div>
          <div className="card p-5"><p className="text-sm text-slate-500">Drivers</p><p className="mt-1 text-2xl font-bold text-slate-900">{formatCurrency(report.summary.totalAdditionalDrivers, 'MAD')}</p></div>
          <div className="card p-5"><p className="text-sm text-slate-500">Discounts</p><p className="mt-1 text-2xl font-bold text-slate-900">{formatCurrency(report.summary.totalDiscounts, 'MAD')}</p></div>
          <div className="card p-5"><p className="text-sm text-slate-500">Collected</p><p className="mt-1 text-2xl font-bold text-slate-900">{formatCurrency(report.summary.totalCollected, 'MAD')}</p></div>
        </div>
      )}

      <div className="card overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-slate-200 bg-slate-50">
                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wide text-slate-500">Reservation</th>
                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wide text-slate-500">Vehicle</th>
                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wide text-slate-500">Period</th>
                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wide text-slate-500">Source</th>
                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wide text-slate-500">Payment</th>
                <th className="px-6 py-3 text-right text-xs font-medium uppercase tracking-wide text-slate-500">Total</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {(report?.rows ?? []).map((row) => (
                <tr key={row.reservationId}>
                  <td className="px-6 py-4 text-sm text-slate-700">{row.customerName}</td>
                  <td className="px-6 py-4 text-sm text-slate-700">{row.vehicle}</td>
                  <td className="px-6 py-4 text-sm text-slate-500">{row.startDate} - {row.endDate}</td>
                  <td className="px-6 py-4 text-sm text-slate-700">{row.source}</td>
                  <td className="px-6 py-4"><span className="badge-gray">{row.paymentStatus}</span></td>
                  <td className="px-6 py-4 text-right text-sm font-semibold text-slate-900">{formatCurrency(row.totalAmount, 'MAD')}</td>
                </tr>
              ))}
              {(report?.rows.length ?? 0) === 0 && (
                <tr>
                  <td colSpan={6} className="px-6 py-10 text-center text-sm text-slate-400">No report rows available for this period.</td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  )
}
