import { useMemo, useState } from 'react'
import { useApp } from '../context/AppContext'
import { formatRupiah } from '../utils/formatRupiah'
import {
  TrendingUp, TrendingDown, FileText, Users,
  BarChart2, Package, Anchor, RefreshCw,
  ArrowUp, ArrowDown, Minus,
} from 'lucide-react'

/**
 * Dashboard Manajemen — Read-only, Mobile-friendly
 * Untuk owner/direktur: pantau KPI utama dari HP
 * Tidak ada tombol input/hapus — hanya lihat
 */

const BULAN = ['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Agu','Sep','Okt','Nov','Des']

function fmtRingkas(n) {
  if (n >= 1_000_000_000) return `${(n / 1_000_000_000).toFixed(1)}M`
  if (n >= 1_000_000)     return `${(n / 1_000_000).toFixed(1)}Jt`
  if (n >= 1_000)         return `${(n / 1_000).toFixed(0)}Rb`
  return String(n)
}

function KpiCard({ label, value, sub, trend, trendVal, color, icon: Icon }) {
  const isUp   = trend === 'up'
  const isDown = trend === 'down'
  return (
    <div style={{
      background: 'white', borderRadius: 16, padding: '18px 20px',
      boxShadow: '0 2px 12px rgba(0,0,0,0.06)',
      border: '1px solid #e2e8f0',
    }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 12 }}>
        <div style={{ width: 40, height: 40, borderRadius: 10, background: `${color}18`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon size={19} color={color} />
        </div>
        {trendVal != null && (
          <div style={{
            display: 'flex', alignItems: 'center', gap: 3,
            padding: '3px 8px', borderRadius: 20, fontSize: 11, fontWeight: 700,
            background: isUp ? '#ecfdf5' : isDown ? '#fff1f2' : '#f1f5f9',
            color: isUp ? '#059669' : isDown ? '#dc2626' : '#64748b',
          }}>
            {isUp ? <ArrowUp size={10} /> : isDown ? <ArrowDown size={10} /> : <Minus size={10} />}
            {trendVal}
          </div>
        )}
      </div>
      <div style={{ fontSize: 24, fontWeight: 900, color: '#0f172a', lineHeight: 1 }}>{value}</div>
      <div style={{ fontSize: 12, color: '#64748b', marginTop: 4 }}>{label}</div>
      {sub && <div style={{ fontSize: 11, color: '#94a3b8', marginTop: 3 }}>{sub}</div>}
    </div>
  )
}

function BarChart({ data, maxVal, color }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, height: 80 }}>
      {data.map((d, i) => {
        const pct = maxVal > 0 ? (d.val / maxVal) * 100 : 0
        const isLast = i === data.length - 1
        return (
          <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
            <div style={{ fontSize: 9, color: isLast ? color : '#94a3b8', fontWeight: isLast ? 700 : 400 }}>
              {d.val > 0 ? fmtRingkas(d.val) : ''}
            </div>
            <div style={{
              width: '100%', borderRadius: '4px 4px 0 0',
              height: `${Math.max(pct, 3)}%`,
              background: isLast ? color : `${color}40`,
              transition: 'height 0.5s ease',
              minHeight: d.val > 0 ? 4 : 0,
            }} />
            <div style={{ fontSize: 9, color: isLast ? '#0f172a' : '#94a3b8', fontWeight: isLast ? 700 : 400 }}>
              {d.label}
            </div>
          </div>
        )
      })}
    </div>
  )
}

export default function DashboardManajemen() {
  const { invoiceList, btdList, bdnList, gudangList, klienList } = useApp()
  const [lastRefresh] = useState(new Date())
  const now = new Date()

  const stats = useMemo(() => {
    // ── Bulan ini & lalu ────────────────────────────────────────────────────
    const bulanIni  = now.getMonth()
    const tahunIni  = now.getFullYear()
    const bulanLalu = bulanIni === 0 ? 11 : bulanIni - 1
    const tahunLalu = bulanIni === 0 ? tahunIni - 1 : tahunIni

    const invBulanIni  = invoiceList.filter(inv => { const d = new Date(inv.tanggalInvoice); return d.getMonth() === bulanIni  && d.getFullYear() === tahunIni  })
    const invBulanLalu = invoiceList.filter(inv => { const d = new Date(inv.tanggalInvoice); return d.getMonth() === bulanLalu && d.getFullYear() === tahunLalu })

    const pendapatanBulanIni  = invBulanIni.reduce((s, inv)  => s + (inv.detail?.kalkulasi?.grandTotal || inv.detail?.kalkulasi?.grand || inv.grandTotal || 0), 0)
    const pendapatanBulanLalu = invBulanLalu.reduce((s, inv) => s + (inv.detail?.kalkulasi?.grandTotal || inv.detail?.kalkulasi?.grand || inv.grandTotal || 0), 0)
    const pctPendapatan = pendapatanBulanLalu > 0
      ? ((pendapatanBulanIni - pendapatanBulanLalu) / pendapatanBulanLalu * 100).toFixed(1)
      : null

    // ── 6 bulan terakhir untuk chart ────────────────────────────────────────
    const enamBulan = Array.from({ length: 6 }, (_, i) => {
      const d = new Date(tahunIni, bulanIni - (5 - i), 1)
      const bln = d.getMonth(), thn = d.getFullYear()
      const val = invoiceList
        .filter(inv => { const di = new Date(inv.tanggalInvoice); return di.getMonth() === bln && di.getFullYear() === thn })
        .reduce((s, inv) => s + (inv.detail?.kalkulasi?.grandTotal || inv.detail?.kalkulasi?.grand || inv.grandTotal || 0), 0)
      return { label: BULAN[bln], val }
    })

    // ── Top 5 klien ─────────────────────────────────────────────────────────
    const klienMap = {}
    invoiceList.forEach(inv => {
      const nama = inv.consignee || 'Lainnya'
      if (!klienMap[nama]) klienMap[nama] = { count: 0, total: 0 }
      klienMap[nama].count++
      klienMap[nama].total += inv.detail?.kalkulasi?.grandTotal || inv.detail?.kalkulasi?.grand || inv.grandTotal || 0
    })
    const topKlien = Object.entries(klienMap)
      .sort((a, b) => b[1].total - a[1].total)
      .slice(0, 5)

    // ── Per jenis layanan bulan ini ─────────────────────────────────────────
    const jenisMap = {}
    invBulanIni.forEach(inv => {
      const j = inv.jenisLayanan || 'Lainnya'
      if (!jenisMap[j]) jenisMap[j] = 0
      jenisMap[j] += inv.detail?.kalkulasi?.grandTotal || inv.detail?.kalkulasi?.grand || inv.grandTotal || 0
    })

    // ── Dokumen pending ──────────────────────────────────────────────────────
    const totalPending = [...btdList, ...bdnList, ...gudangList].filter(d => d.status === 'Terbuka').length
    const totalDokumen = btdList.length + bdnList.length + gudangList.length

    return {
      totalInvoice: invoiceList.length,
      invBulanIni: invBulanIni.length,
      invBulanLalu: invBulanLalu.length,
      pendapatanBulanIni, pendapatanBulanLalu,
      pctPendapatan,
      pendapatanTotal: invoiceList.reduce((s, inv) => s + (inv.detail?.kalkulasi?.grandTotal || inv.detail?.kalkulasi?.grand || inv.grandTotal || 0), 0),
      enamBulan,
      maxEnamBulan: Math.max(...enamBulan.map(d => d.val), 1),
      topKlien,
      jenisMap,
      totalPending,
      totalDokumen,
      totalKlien: klienList.length,
    }
  }, [invoiceList, btdList, bdnList, gudangList, klienList])

  const JENIS_COLORS = {
    'FCL TPP': '#0ea5e9', 'LCL TPP': '#8b5cf6',
    'Gudang Umum FCL': '#10b981', 'Gudang Umum LCL': '#34d399',
    'Lainnya': '#94a3b8',
  }

  const getJenisColor = (jenis) => {
    for (const [k, v] of Object.entries(JENIS_COLORS)) if (jenis?.includes(k)) return v
    return '#94a3b8'
  }

  return (
    <div style={{
      minHeight: '100vh',
      background: 'linear-gradient(180deg, #0a1628 0%, #0f1f3d 100%)',
      padding: '0 0 40px',
    }}>
      {/* Header */}
      <div style={{ padding: '24px 20px 20px', borderBottom: '1px solid rgba(255,255,255,0.07)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 4 }}>
          <div style={{ width: 36, height: 36, borderRadius: 10, background: 'linear-gradient(135deg,#0ea5e9,#0369a1)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Anchor size={18} color="white" strokeWidth={2.5} />
          </div>
          <div>
            <div style={{ fontFamily: "'DM Serif Display', serif", fontSize: 17, color: 'white' }}>Sarana Gemilang</div>
            <div style={{ fontSize: 10, color: 'rgba(255,255,255,0.4)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>Dashboard Manajemen</div>
          </div>
        </div>
        <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.35)', marginTop: 8, display: 'flex', alignItems: 'center', gap: 6 }}>
          <RefreshCw size={11} />
          Update: {lastRefresh.toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' })} ·
          {now.toLocaleDateString('id-ID', { day: 'numeric', month: 'long', year: 'numeric' })}
        </div>
      </div>

      <div style={{ padding: '20px 16px', display: 'flex', flexDirection: 'column', gap: 20 }}>

        {/* KPI Cards */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <KpiCard
            label={`Pendapatan ${BULAN[now.getMonth()]}`}
            value={fmtRingkas(stats.pendapatanBulanIni)}
            sub={`Bulan lalu: ${fmtRingkas(stats.pendapatanBulanLalu)}`}
            trend={stats.pctPendapatan > 0 ? 'up' : stats.pctPendapatan < 0 ? 'down' : 'flat'}
            trendVal={stats.pctPendapatan != null ? `${Math.abs(stats.pctPendapatan)}%` : null}
            color="#10b981" icon={TrendingUp}
          />
          <KpiCard
            label={`Invoice ${BULAN[now.getMonth()]}`}
            value={stats.invBulanIni}
            sub={`Bulan lalu: ${stats.invBulanLalu}`}
            trend={stats.invBulanIni > stats.invBulanLalu ? 'up' : stats.invBulanIni < stats.invBulanLalu ? 'down' : 'flat'}
            trendVal={stats.invBulanLalu > 0 ? `${Math.abs(((stats.invBulanIni - stats.invBulanLalu) / stats.invBulanLalu) * 100).toFixed(0)}%` : null}
            color="#0ea5e9" icon={FileText}
          />
          <KpiCard
            label="Total Pendapatan"
            value={fmtRingkas(stats.pendapatanTotal)}
            sub={`${stats.totalInvoice} invoice total`}
            color="#8b5cf6" icon={BarChart2}
          />
          <KpiCard
            label="Dokumen Pending"
            value={stats.totalPending}
            sub={`dari ${stats.totalDokumen} total dokumen`}
            trend={stats.totalPending > 5 ? 'down' : 'up'}
            trendVal={null}
            color={stats.totalPending > 5 ? '#f97316' : '#10b981'} icon={Package}
          />
        </div>

        {/* Chart 6 bulan */}
        <div style={{ background: 'white', borderRadius: 16, padding: '18px 20px', boxShadow: '0 2px 12px rgba(0,0,0,0.06)' }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: '#0f172a', marginBottom: 16 }}>
            Pendapatan 6 Bulan Terakhir
          </div>
          <BarChart data={stats.enamBulan} maxVal={stats.maxEnamBulan} color="#0ea5e9" />
        </div>

        {/* Top Klien */}
        <div style={{ background: 'white', borderRadius: 16, padding: '18px 20px', boxShadow: '0 2px 12px rgba(0,0,0,0.06)' }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: '#0f172a', marginBottom: 14 }}>
            Top Klien — All Time
          </div>
          {stats.topKlien.length === 0 ? (
            <div style={{ textAlign: 'center', color: '#94a3b8', fontSize: 13, padding: '16px 0' }}>Belum ada data</div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {stats.topKlien.map(([nama, data], idx) => {
                const totalAll = stats.pendapatanTotal || 1
                const pct = Math.round(data.total / totalAll * 100)
                const rankColor = ['#f59e0b','#94a3b8','#cd7c2f'][idx] || '#e2e8f0'
                return (
                  <div key={nama}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 5 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <span style={{ width: 22, height: 22, borderRadius: 6, background: `${rankColor}20`, color: rankColor, fontSize: 11, fontWeight: 800, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                          {idx + 1}
                        </span>
                        <span style={{ fontSize: 12.5, fontWeight: 600, color: '#374151', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 180 }}>{nama}</span>
                      </div>
                      <div style={{ textAlign: 'right', flexShrink: 0 }}>
                        <div style={{ fontSize: 12.5, fontWeight: 800, color: '#0f172a' }}>{fmtRingkas(data.total)}</div>
                        <div style={{ fontSize: 10.5, color: '#94a3b8' }}>{data.count} invoice</div>
                      </div>
                    </div>
                    <div style={{ height: 5, borderRadius: 99, background: '#f1f5f9', overflow: 'hidden' }}>
                      <div style={{ height: '100%', width: `${pct}%`, background: '#0ea5e9', borderRadius: 99, transition: 'width 0.5s ease' }} />
                    </div>
                  </div>
                )
              })}
            </div>
          )}
        </div>

        {/* Breakdown jenis bulan ini */}
        {Object.keys(stats.jenisMap).length > 0 && (
          <div style={{ background: 'white', borderRadius: 16, padding: '18px 20px', boxShadow: '0 2px 12px rgba(0,0,0,0.06)' }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: '#0f172a', marginBottom: 14 }}>
              Jenis Layanan — {BULAN[now.getMonth()]} {now.getFullYear()}
            </div>
            {Object.entries(stats.jenisMap)
              .sort((a, b) => b[1] - a[1])
              .map(([jenis, total]) => {
                const color = getJenisColor(jenis)
                const pct   = Math.round(total / (stats.pendapatanBulanIni || 1) * 100)
                return (
                  <div key={jenis} style={{ marginBottom: 12 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                      <span style={{ fontSize: 12, color: '#374151', fontWeight: 600 }}>{jenis}</span>
                      <span style={{ fontSize: 12, fontWeight: 700, color: '#0f172a' }}>{fmtRingkas(total)} ({pct}%)</span>
                    </div>
                    <div style={{ height: 6, borderRadius: 99, background: '#f1f5f9', overflow: 'hidden' }}>
                      <div style={{ height: '100%', width: `${pct}%`, background: color, borderRadius: 99, transition: 'width 0.5s ease' }} />
                    </div>
                  </div>
                )
              })
            }
          </div>
        )}

        {/* Footer */}
        <div style={{ textAlign: 'center', fontSize: 11, color: 'rgba(255,255,255,0.2)', paddingTop: 8 }}>
          PT. Sarana Gemilang · Belawan, Medan · Read-only view
        </div>
      </div>
    </div>
  )
}
