import { useQuery } from '@tanstack/react-query'
import { FileText, CheckCircle2, AlertTriangle, TrendingUp, Coins, Pencil, Clock, Inbox } from 'lucide-react'
import { useNavigate } from 'react-router-dom'
import { PageHeader } from '@/components/PageHeader'
import { BarChart } from '@/components/BarChart'
import { PhaseBadge } from '@/components/PhaseBadge'
import { useAuth } from '@/contexts/AuthContext'
import { api } from '@/lib/api'
import { cn } from '@/lib/cn'
import type { DashboardStats } from '@/types/reports'

type MyDashboard = {
  draftsInProgress: number
  pendingMyApproval: number
  dueSoon: number
  overdue: number
  draftsTotalValue: number
}

const fmtMoney = (v: number) => {
  if (v >= 1_000_000_000) return (v / 1_000_000_000).toFixed(1) + ' tỷ'
  if (v >= 1_000_000) return (v / 1_000_000).toFixed(1) + ' tr'
  return v.toLocaleString('vi-VN')
}

// Tone → tinted icon chip (brand-led, semantic accents for warn/good).
const STAT_TONE: Record<'default' | 'warn' | 'good', { chip: string; icon: string; value: string }> = {
  default: { chip: 'bg-brand-50', icon: 'text-brand-600', value: 'text-slate-900' },
  warn: { chip: 'bg-amber-50', icon: 'text-amber-600', value: 'text-amber-700' },
  good: { chip: 'bg-emerald-50', icon: 'text-emerald-600', value: 'text-slate-900' },
}

function StatCard({ icon: Icon, label, value, hint, tone = 'default' }: {
  icon: React.ComponentType<{ className?: string }>
  label: string
  value: React.ReactNode
  hint?: string
  tone?: 'default' | 'warn' | 'good'
}) {
  const t = STAT_TONE[tone]
  return (
    <div className="rounded-lg border border-slate-200 bg-white p-4 transition-colors hover:border-slate-300">
      <div className="flex items-start justify-between gap-2">
        <div className="text-[11px] font-semibold uppercase tracking-wider text-slate-500">{label}</div>
        <span className={cn('flex h-7 w-7 shrink-0 items-center justify-center rounded-lg', t.chip)}>
          <Icon className={cn('h-4 w-4', t.icon)} />
        </span>
      </div>
      <div className={cn('mt-2.5 text-2xl font-semibold tabular-nums leading-none', t.value)}>{value}</div>
      {hint && <div className="mt-1.5 text-[11px] text-slate-400">{hint}</div>}
    </div>
  )
}

// Small section title with a brand tick — gives each band a clear, quiet anchor.
function SectionLabel({ children }: { children: React.ReactNode }) {
  return (
    <h2 className="mb-2.5 flex items-center gap-2 text-[11px] font-semibold uppercase tracking-wider text-slate-500">
      <span className="h-3 w-0.5 rounded-full bg-brand-500" />
      {children}
    </h2>
  )
}

function MyDashboardRow() {
  const navigate = useNavigate()
  const { user } = useAuth()
  const q = useQuery({
    queryKey: ['my-dashboard'],
    queryFn: async () => (await api.get<MyDashboard>('/reports/my-dashboard')).data,
    staleTime: 30_000,
  })
  const d = q.data
  if (!d) return null

  // Admin thấy everything nhưng card "Tôi đang soạn thảo" + "Chờ tôi duyệt"
  // thường = 0 cho admin. Chỉ show row nếu có ít nhất 1 card có giá trị.
  const anyValue = d.draftsInProgress + d.pendingMyApproval + d.dueSoon + d.overdue > 0
  if (!anyValue && user?.roles.includes('Admin')) return null

  return (
    <div className="mb-6">
      <SectionLabel>Của tôi</SectionLabel>
      <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
        <button
          onClick={() => navigate('/contracts?filter=my-drafts')}
          className="group rounded-lg border border-slate-200 bg-white p-4 text-left transition-colors hover:border-brand-300 hover:bg-brand-50/30"
        >
          <div className="flex items-start justify-between gap-2">
            <div className="text-[11px] font-semibold uppercase tracking-wider text-slate-500">Đang soạn thảo</div>
            <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-50">
              <Pencil className="h-4 w-4 text-brand-600" />
            </span>
          </div>
          <div className="mt-2.5 text-2xl font-semibold leading-none text-slate-900 tabular-nums">{d.draftsInProgress}</div>
          <div className="mt-1.5 text-[11px] text-slate-400">{fmtMoney(d.draftsTotalValue)} VND</div>
        </button>
        <button
          onClick={() => navigate('/contracts?filter=pending-me')}
          className="group rounded-lg border border-slate-200 bg-white p-4 text-left transition-colors hover:border-brand-300 hover:bg-brand-50/30"
        >
          <div className="flex items-start justify-between gap-2">
            <div className="text-[11px] font-semibold uppercase tracking-wider text-slate-500">Chờ tôi duyệt</div>
            <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-50">
              <Inbox className="h-4 w-4 text-brand-600" />
            </span>
          </div>
          <div className="mt-2.5 text-2xl font-semibold leading-none text-slate-900 tabular-nums">{d.pendingMyApproval}</div>
          <div className="mt-1.5 text-[11px] text-slate-400">Mở hộp thư duyệt</div>
        </button>
        <div className="rounded-lg border border-slate-200 bg-white p-4">
          <div className="flex items-start justify-between gap-2">
            <div className="text-[11px] font-semibold uppercase tracking-wider text-slate-500">Sắp quá hạn (24h)</div>
            <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-amber-50">
              <Clock className="h-4 w-4 text-amber-600" />
            </span>
          </div>
          <div className="mt-2.5 text-2xl font-semibold leading-none text-amber-700 tabular-nums">{d.dueSoon}</div>
        </div>
        <div className="rounded-lg border border-slate-200 bg-white p-4">
          <div className="flex items-start justify-between gap-2">
            <div className="text-[11px] font-semibold uppercase tracking-wider text-slate-500">Đã quá hạn</div>
            <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-red-50">
              <AlertTriangle className="h-4 w-4 text-red-600" />
            </span>
          </div>
          <div className="mt-2.5 text-2xl font-semibold leading-none text-red-600 tabular-nums">{d.overdue}</div>
        </div>
      </div>
    </div>
  )
}

export function DashboardPage() {
  const stats = useQuery({
    queryKey: ['dashboard-stats'],
    queryFn: async () => (await api.get<DashboardStats>('/reports/dashboard')).data,
    staleTime: 60_000,
  })

  if (stats.isLoading) {
    return (
      <div className="p-6">
        <PageHeader title="Tổng quan" description="Tình hình HĐ toàn hệ thống — cập nhật real-time khi refresh." />
        <div className="grid grid-cols-2 gap-4 md:grid-cols-5">
          {[1, 2, 3, 4, 5].map(i => (
            <div key={i} className="h-[88px] animate-pulse rounded-lg border border-slate-200 bg-slate-50" />
          ))}
        </div>
      </div>
    )
  }

  const d = stats.data
  if (!d) return null

  return (
    <div className="p-6">
      <PageHeader title="Tổng quan" description="Tình hình HĐ toàn hệ thống — cập nhật real-time khi refresh." />

      <MyDashboardRow />

      <SectionLabel>Toàn hệ thống</SectionLabel>
      {/* KPI Cards */}
      <div className="grid grid-cols-2 gap-4 md:grid-cols-5">
        <StatCard icon={FileText} label="Tổng HĐ" value={d.totalContracts} />
        <StatCard icon={TrendingUp} label="HĐ đang xử lý" value={d.activeContracts} tone="good" />
        <StatCard icon={AlertTriangle} label="HĐ quá hạn SLA" value={d.overdueContracts} tone="warn" hint="SLA đã trôi" />
        <StatCard icon={CheckCircle2} label="Phát hành tháng này" value={d.publishedThisMonth} tone="good" />
        <StatCard icon={Coins} label="Tổng giá trị active" value={fmtMoney(d.totalValueActive)} hint="VND" />
      </div>

      <div className="mt-6 grid grid-cols-1 gap-4 lg:grid-cols-2">
        {/* By Phase */}
        <section className="rounded-lg border border-slate-200 bg-white p-5">
          <h2 className="mb-4 text-[13px] font-semibold text-slate-800">HĐ theo phase</h2>
          <div className="space-y-2.5">
            {d.byPhase.length === 0 && <div className="py-6 text-center text-[13px] text-slate-400">Chưa có HĐ nào</div>}
            {d.byPhase
              .slice()
              .sort((a, b) => b.count - a.count)
              .map(p => {
                const total = d.byPhase.reduce((s, x) => s + x.count, 0) || 1
                const pct = (p.count / total) * 100
                return (
                  <div key={p.phase} className="flex items-center gap-3">
                    <div className="w-36">
                      <PhaseBadge phase={p.phase} />
                    </div>
                    <div className="h-1.5 flex-1 overflow-hidden rounded-full bg-slate-100">
                      <div className="h-full rounded-full bg-brand-500" style={{ width: `${pct}%` }} />
                    </div>
                    <div className="w-10 text-right text-xs font-medium text-slate-600 tabular-nums">{p.count}</div>
                  </div>
                )
              })}
          </div>
        </section>

        {/* Monthly value */}
        <section className="rounded-lg border border-slate-200 bg-white p-5">
          <h2 className="mb-4 text-[13px] font-semibold text-slate-800">Giá trị HĐ theo tháng <span className="font-normal text-slate-400">· 12 tháng gần nhất</span></h2>
          <BarChart
            data={d.monthlyValue.map(m => ({
              label: `${String(m.month).padStart(2, '0')}/${m.year}`,
              value: m.totalValue,
              sublabel: `${m.count} HĐ`,
            }))}
            formatValue={fmtMoney}
          />
        </section>

        {/* Top suppliers */}
        <section className="rounded-lg border border-slate-200 bg-white p-5">
          <h2 className="mb-4 text-[13px] font-semibold text-slate-800">Top NCC theo số HĐ</h2>
          <BarChart
            data={d.topSuppliers.map(s => ({
              label: s.supplierName,
              value: s.count,
              sublabel: `Tổng ${fmtMoney(s.totalValue)} VND`,
            }))}
          />
        </section>

        {/* Top projects */}
        <section className="rounded-lg border border-slate-200 bg-white p-5">
          <h2 className="mb-4 text-[13px] font-semibold text-slate-800">Top dự án theo số HĐ</h2>
          <BarChart
            data={d.topProjects.map(p => ({
              label: p.projectName,
              value: p.count,
              sublabel: `Tổng ${fmtMoney(p.totalValue)} VND`,
            }))}
          />
        </section>
      </div>
    </div>
  )
}
