'use client'
import { usePolling } from '@/hooks/usePolling'
import { FileText, Table2 } from 'lucide-react'
import styles from './page.module.css'
import jsPDF from 'jspdf'
import autoTable from 'jspdf-autotable'
import * as XLSX from 'xlsx'

interface RevData {
  revenueByMonth: { label: string; value: number }[]
  bookingByMonth: { label: string; value: number }[]
  topServices: { name: string; count: number; revenue: number }[]
  topTherapists: { name: string; sessions: number; rating: number }[]
}

function fmtRp(n: number) {
  if (n >= 1_000_000) return `Rp ${(n / 1_000_000).toFixed(1)} Jt`
  if (n >= 1_000) return `Rp ${(n / 1_000).toFixed(0)} Rb`
  return `Rp ${n.toLocaleString('id-ID')}`
}

function fmtRpFull(n: number) {
  return `Rp ${n.toLocaleString('id-ID')}`
}

export default function ReportsPage() {
  const { data, loading } = usePolling<RevData>('/api/admin/revenue', 30000)

  const maxRev = data ? Math.max(...data.revenueByMonth.map(r => r.value), 1) : 1
  const maxBook = data ? Math.max(...data.bookingByMonth.map(r => r.value), 1) : 1
  const maxSvc = data ? Math.max(...(data.topServices?.map(s => s.count) ?? [1]), 1) : 1
  const totalRevenue = data ? data.revenueByMonth.reduce((s, r) => s + r.value, 0) : 0

  // ── Export PDF ──────────────────────────────────────────
  function exportPDF() {
    if (!data) return
    const doc = new jsPDF()
    const now = new Date().toLocaleString('id-ID')

    // Header
    doc.setFontSize(18)
    doc.setTextColor(113, 131, 85)
    doc.text('KEMBALI SPA', 14, 16)
    doc.setFontSize(14)
    doc.setTextColor(26, 42, 20)
    doc.text('Laporan Revenue & Analitik', 14, 24)
    doc.setFontSize(9)
    doc.setTextColor(135, 135, 135)
    doc.text(`Dicetak: ${now}`, 14, 30)

    // Summary
    doc.setFontSize(10)
    doc.setTextColor(26, 42, 20)
    doc.text(`Total Revenue 6 Bulan: ${fmtRpFull(totalRevenue)}`, 14, 40)

    // Revenue Table
    doc.setFontSize(12)
    doc.setTextColor(113, 131, 85)
    doc.text('Revenue Bulanan', 14, 52)

    const revenueData = data.revenueByMonth.map(r => [r.label, fmtRpFull(r.value)])
    autoTable(doc, {
      startY: 56,
      head: [['Bulan', 'Revenue']],
      body: revenueData,
      theme: 'striped',
      headStyles: { fillColor: [113, 131, 85] },
      margin: { left: 14, right: 14 },
    })

    // Booking Table
    const yAfterRevenue = (doc as any).lastAutoTable.finalY + 10
    doc.setFontSize(12)
    doc.setTextColor(113, 131, 85)
    doc.text('Volume Booking', 14, yAfterRevenue)

    const bookingData = data.bookingByMonth.map(r => [r.label, r.value.toString()])
    autoTable(doc, {
      startY: yAfterRevenue + 4,
      head: [['Bulan', 'Total Booking']],
      body: bookingData,
      theme: 'striped',
      headStyles: { fillColor: [113, 131, 85] },
      margin: { left: 14, right: 14 },
    })

    // Top Services Table
    const yAfterBooking = (doc as any).lastAutoTable.finalY + 10
    doc.setFontSize(12)
    doc.setTextColor(113, 131, 85)
    doc.text('Top Layanan', 14, yAfterBooking)

    const servicesData = (data.topServices || []).map((s, i) => [
      `#${i + 1}`, s.name, `${s.count}x`, fmtRpFull(s.revenue)
    ])
    autoTable(doc, {
      startY: yAfterBooking + 4,
      head: [['Rank', 'Layanan', 'Jumlah', 'Revenue']],
      body: servicesData,
      theme: 'striped',
      headStyles: { fillColor: [113, 131, 85] },
      margin: { left: 14, right: 14 },
    })

    // Top Therapists Table
    const yAfterServices = (doc as any).lastAutoTable.finalY + 10
    doc.setFontSize(12)
    doc.setTextColor(113, 131, 85)
    doc.text('Top Terapis', 14, yAfterServices)

    const therapistsData = (data.topTherapists || []).map((t, i) => [
      `#${i + 1}`, t.name, `${t.sessions} sesi`, `★ ${t.rating.toFixed(2)}`
    ])
    autoTable(doc, {
      startY: yAfterServices + 4,
      head: [['Rank', 'Nama', 'Total Sesi', 'Rating']],
      body: therapistsData,
      theme: 'striped',
      headStyles: { fillColor: [113, 131, 85] },
      margin: { left: 14, right: 14 },
    })

    doc.save(`kembali-spa-report-${new Date().toISOString().split('T')[0]}.pdf`)
  }

  // ── Export Excel ─────────────────────────────────────────
  function exportExcel() {
    if (!data) return

    const wb = XLSX.utils.book_new()

    // Summary Sheet
    const summaryData = [
      ['KEMBALI SPA - Laporan Revenue & Analitik'],
      ['Dicetak:', new Date().toLocaleString('id-ID')],
      [],
      ['Total Revenue 6 Bulan:', fmtRpFull(totalRevenue)],
      [],
      ['REVENUE BULANAN'],
      ['Bulan', 'Revenue'],
      ...data.revenueByMonth.map(r => [r.label, r.value]),
      [],
      ['VOLUME BOOKING'],
      ['Bulan', 'Total Booking'],
      ...data.bookingByMonth.map(r => [r.label, r.value]),
      [],
      ['TOP LAYANAN'],
      ['Rank', 'Layanan', 'Jumlah', 'Revenue'],
      ...(data.topServices || []).map((s, i) => [`#${i + 1}`, s.name, s.count, s.revenue]),
      [],
      ['TOP TERAPIS'],
      ['Rank', 'Nama', 'Total Sesi', 'Rating'],
      ...(data.topTherapists || []).map((t, i) => [`#${i + 1}`, t.name, t.sessions, t.rating]),
    ]

    const ws = XLSX.utils.aoa_to_sheet(summaryData)
    XLSX.utils.book_append_sheet(wb, ws, 'Laporan')

    XLSX.writeFile(wb, `kembali-spa-report-${new Date().toISOString().split('T')[0]}.xlsx`)
  }

  return (
    <div className={styles.page}>
      <div className={styles.topBar}>
        <div>
          <h1 className={styles.pageTitle}>Laporan & Analitik</h1>
          <p className={styles.pageSub}>6 bulan terakhir</p>
        </div>
        <div className={styles.topRight}>
          <div className={styles.totalRevCard}>
            <span className={styles.totalRevLabel}>Total Revenue 6 Bulan</span>
            <span className={styles.totalRevValue}>{fmtRp(totalRevenue)}</span>
          </div>
          {data && (
            <div className={styles.exportButtons}>
              <button className={styles.exportBtn} onClick={exportPDF} title="Export PDF">
                <FileText size={16} />
                <span>PDF</span>
              </button>
              <button className={styles.exportBtn} onClick={exportExcel} title="Export Excel">
                <Table2 size={16} />
                <span>Excel</span>
              </button>
            </div>
          )}
        </div>
      </div>

      {loading ? <div className={styles.loading}>Memuat laporan...</div> : (
        <>
          <div className={styles.gridTwo}>
            {/* Revenue Chart */}
            <div className={styles.card}>
              <h3 className={styles.cardTitle}>Revenue Bulanan</h3>
              <div className={styles.barChart}>
                {data?.revenueByMonth.map((r, i) => (
                  <div key={i} className={styles.barCol}>
                    <span className={styles.barVal}>{fmtRp(r.value)}</span>
                    <div className={styles.barWrap}>
                      <div className={styles.bar} ref={el => { el?.style.setProperty('--bar-h', `${Math.round((r.value / maxRev) * 100)}%`) }} />
                    </div>
                    <span className={styles.barLabel}>{r.label}</span>
                  </div>
                ))}
              </div>
            </div>

            {/* Booking Volume */}
            <div className={styles.card}>
              <h3 className={styles.cardTitle}>Volume Booking</h3>
              <div className={styles.barChart}>
                {data?.bookingByMonth.map((r, i) => (
                  <div key={i} className={styles.barCol}>
                    <span className={styles.barVal}>{r.value}</span>
                    <div className={styles.barWrap}>
                      <div className={`${styles.bar} ${styles.barBlue}`} ref={el => { el?.style.setProperty('--bar-h', `${Math.round((r.value / maxBook) * 100)}%`) }} />
                    </div>
                    <span className={styles.barLabel}>{r.label}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>

          <div className={styles.gridTwo}>
            {/* Top Services */}
            <div className={styles.card}>
              <h3 className={styles.cardTitle}>Top Layanan</h3>
              {data?.topServices?.map((s, i) => (
                <div key={i} className={styles.topRow}>
                  <span className={styles.rank}>#{i + 1}</span>
                  <span className={styles.topName}>{s.name}</span>
                  <div className={styles.progressBar}>
                    <div className={styles.progressFill} ref={el => { el?.style.setProperty('--fill-w', `${Math.round((s.count / maxSvc) * 100)}%`) }} />
                  </div>
                  <span className={styles.topCount}>{s.count}x</span>
                  <span className={styles.topRevenue}>{fmtRp(s.revenue)}</span>
                </div>
              ))}
              {!data?.topServices?.length && <p className={styles.empty}>Belum ada data</p>}
            </div>

            {/* Top Therapists */}
            <div className={styles.card}>
              <h3 className={styles.cardTitle}>Top Terapis</h3>
              {data?.topTherapists?.map((t, i) => (
                <div key={i} className={styles.therapistRow}>
                  <div className={styles.therapistRank}>{i + 1}</div>
                  <div className={styles.therapistAvatar}>{t.name[0]}</div>
                  <div className={styles.therapistInfo}>
                    <div className={styles.therapistName}>{t.name}</div>
                    <div className={styles.therapistSub}>{t.sessions} sesi · ★ {t.rating.toFixed(2)}</div>
                  </div>
                </div>
              ))}
              {!data?.topTherapists?.length && <p className={styles.empty}>Belum ada data</p>}
            </div>
          </div>
        </>
      )}
    </div>
  )
}
