// Báo cáo chấm công tháng + OT quy đổi — Phase 11 P11-E (S?? 2026-06-08).
// fe-admin ONLY: endpoint /attendances/report* là [Authorize(Roles=Admin)] → fe-user KHÔNG có page này.
// Filter Năm/Tháng/Phòng ban → TanStack Query → Table + footer Tổng. Xuất Excel qua api.get responseType:'blob'
// (api instance đã inject JWT qua interceptor + hỗ trợ refresh-token retry — chuẩn hơn raw fetch).
//
// Re-skin S69 (2026-06-17): áp PURO layout + visual language Hồ sơ Nhân sự — CHỈ trình bày,
// KHÔNG đổi logic. ui/PageHeader (icon-chip + actions) · KpiCard hàng tổng hợp · .card-accent
// cho bộ lọc + bảng · .label-eyebrow nhãn lọc · text-brand-800 cho số quan trọng. Mọi query /
// mutation / queryKey / endpoint / handler giữ NGUYÊN (attendance-report, /attendances/report,
// /attendances/report/excel, departments-all-attendance-report).
import { useState } from 'react'
import { useMutation, useQuery } from '@tanstack/react-query'
import { Download, ClipboardList, CalendarCheck, Users, Clock, Hourglass } from 'lucide-react'
import { toast } from 'sonner'
import { PageHeader } from '@/components/ui/PageHeader'
import { KpiCard } from '@/components/ui/KpiCard'
import { Button } from '@/components/ui/Button'
import { Input } from '@/components/ui/Input'
import { Select } from '@/components/ui/Select'
import { api } from '@/lib/api'
import { getErrorMessage } from '@/lib/apiError'
import type { Paged, Department } from '@/types/master'
import type { AttendanceReportDto } from '@/types/workflowApps'

// Format decimal gọn: bỏ trailing zero, tối đa 2 chữ số thập phân (vd 8 / 8.5 / 7.25).
function fmtNum(n: number): string {
  return Number(n.toFixed(2)).toLocaleString('vi-VN', { maximumFractionDigits: 2 })
}

const MONTHS = Array.from({ length: 12 }, (_, i) => i + 1)

export function AttendanceReportPage() {
  const now = new Date()
  const [year, setYear] = useState(now.getFullYear())
  const [month, setMonth] = useState(now.getMonth() + 1)
  const [deptId, setDeptId] = useState('')

  const departments = useQuery({
    queryKey: ['departments-all-attendance-report'],
    queryFn: async () =>
      (await api.get<Paged<Department>>('/departments', { params: { page: 1, pageSize: 200 } })).data.items,
  })

  const report = useQuery({
    queryKey: ['attendance-report', year, month, deptId],
    queryFn: async () => {
      const res = await api.get<AttendanceReportDto>('/attendances/report', {
        params: { year, month, departmentId: deptId || undefined },
      })
      return res.data
    },
  })

  const exportExcel = useMutation({
    mutationFn: async () => {
      const res = await api.get('/attendances/report/excel', {
        params: { year, month, departmentId: deptId || undefined },
        responseType: 'blob',
      })
      const fallback = `BaoCao-ChamCong-${year}-${String(month).padStart(2, '0')}.xlsx`
      const filename =
        res.headers['content-disposition']?.match(/filename="?([^";]+)"?/)?.[1] ?? fallback
      return { blob: res.data as Blob, filename }
    },
    onSuccess: ({ blob, filename }) => {
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = filename
      a.click()
      URL.revokeObjectURL(url)
      toast.success('Đã tải file Excel')
    },
    onError: err => toast.error(getErrorMessage(err)),
  })

  const rows = report.data?.rows ?? []
  // Tổng hợp tô màu KpiCard — thuần dẫn xuất từ dữ liệu đã fetch (KHÔNG gọi API mới).
  const totalDaysPresent = rows.reduce((s, r) => s + r.daysPresent, 0)

  return (
    <div className="p-6">
      <PageHeader
        eyebrow="Văn phòng số"
        title="Báo cáo chấm công"
        subtitle="Tổng hợp ngày công + giờ làm + OT quy đổi theo tháng và phòng ban."
        icon={<CalendarCheck className="h-5 w-5" />}
        accent="brand"
        actions={
          <Button onClick={() => exportExcel.mutate()} disabled={exportExcel.isPending || report.isLoading}>
            <Download className="h-4 w-4" />
            {exportExcel.isPending ? 'Đang xuất…' : 'Xuất Excel'}
          </Button>
        }
      />

      {/* ===== Tổng hợp (KpiCard) — chỉ hiện khi có dữ liệu ===== */}
      {!report.isLoading && rows.length > 0 && report.data && (
        <div className="mb-4 grid grid-cols-2 gap-3 lg:grid-cols-4">
          <KpiCard
            label="Nhân sự"
            value={rows.length}
            icon={<Users className="h-4 w-4" />}
            accent="brand"
          />
          <KpiCard
            label="Tổng ngày công"
            value={fmtNum(totalDaysPresent)}
            icon={<CalendarCheck className="h-4 w-4" />}
            accent="teal"
          />
          <KpiCard
            label="Tổng giờ làm"
            value={fmtNum(report.data.grandTotalWorkHours)}
            icon={<Clock className="h-4 w-4" />}
            accent="violet"
          />
          <KpiCard
            label="Tổng OT quy đổi"
            value={fmtNum(report.data.grandTotalOtWeighted)}
            icon={<Hourglass className="h-4 w-4" />}
            accent="amberx"
          />
        </div>
      )}

      {/* ===== Bộ lọc ===== */}
      <div className="card-accent mb-4 flex flex-wrap items-end gap-3 p-4">
        <div className="w-28 space-y-1.5">
          <label className="label-eyebrow block">Năm</label>
          <Input
            type="number"
            min={2000}
            max={2100}
            value={year}
            onChange={e => setYear(Number(e.target.value) || now.getFullYear())}
          />
        </div>
        <div className="w-36 space-y-1.5">
          <label className="label-eyebrow block">Tháng</label>
          <Select value={month} onChange={e => setMonth(Number(e.target.value))}>
            {MONTHS.map(m => (
              <option key={m} value={m}>Tháng {m}</option>
            ))}
          </Select>
        </div>
        <div className="min-w-56 flex-1 space-y-1.5">
          <label className="label-eyebrow block">Phòng ban</label>
          <Select value={deptId} onChange={e => setDeptId(e.target.value)}>
            <option value="">Tất cả phòng ban</option>
            {(departments.data ?? []).map(d => (
              <option key={d.id} value={d.id}>{d.name}</option>
            ))}
          </Select>
        </div>
      </div>

      {/* ===== Bảng kết quả ===== card-accent + header bar brand-tint */}
      <section className="card-accent flex min-w-0 flex-col overflow-hidden">
        <header className="flex items-center gap-2 border-b border-slate-100 bg-brand-50 px-4 py-2.5">
          <span
            className="icon-chip"
            style={{ height: '1.75rem', width: '1.75rem', ['--chip-bg' as string]: 'var(--color-brand-100)', ['--chip-fg' as string]: 'var(--color-brand-600)' }}
            aria-hidden
          >
            <ClipboardList className="h-4 w-4" />
          </span>
          <h3 className="text-sm font-semibold tracking-tight text-brand-800">Bảng tổng hợp chấm công</h3>
          {rows.length > 0 && (
            <span className="rounded-full bg-white px-1.5 py-0.5 text-[10px] font-semibold tabular-nums text-brand-700">
              {rows.length}
            </span>
          )}
        </header>
        <div className="overflow-auto">
          <table className="w-full text-sm">
            <thead className="sticky top-0 border-b border-slate-200 bg-slate-50 text-xs uppercase tracking-wide text-slate-500">
              <tr>
                <th className="px-3 py-2 text-left font-semibold">STT</th>
                <th className="px-3 py-2 text-left font-semibold">Họ tên</th>
                <th className="px-3 py-2 text-left font-semibold">Phòng ban</th>
                <th className="px-3 py-2 text-right font-semibold">Ngày công</th>
                <th className="px-3 py-2 text-right font-semibold">Tổng giờ làm</th>
                <th className="px-3 py-2 text-right font-semibold">OT thường</th>
                <th className="px-3 py-2 text-right font-semibold">OT cuối tuần</th>
                <th className="px-3 py-2 text-right font-semibold">OT lễ</th>
                <th className="px-3 py-2 text-right font-semibold">OT quy đổi</th>
              </tr>
            </thead>
            <tbody>
              {report.isLoading && (
                <tr><td colSpan={9} className="px-3 py-8 text-center text-slate-500">Đang tải…</td></tr>
              )}
              {!report.isLoading && rows.length === 0 && (
                <tr><td colSpan={9} className="px-3 py-10 text-center text-slate-500">
                  <ClipboardList className="mx-auto mb-2 h-8 w-8 opacity-50" />
                  Không có dữ liệu chấm công cho kỳ đã chọn.
                </td></tr>
              )}
              {rows.map((r, i) => (
                <tr key={r.userId} className="border-b border-slate-100 hover:bg-brand-50/40">
                  <td className="px-3 py-2 text-slate-500">{i + 1}</td>
                  <td className="px-3 py-2 font-medium text-brand-800">{r.fullName}</td>
                  <td className="px-3 py-2 text-slate-600">{r.departmentName ?? '—'}</td>
                  <td className="px-3 py-2 text-right tabular-nums text-slate-700">{r.daysPresent}</td>
                  <td className="px-3 py-2 text-right tabular-nums text-slate-700">{fmtNum(r.totalWorkHours)}</td>
                  <td className="px-3 py-2 text-right tabular-nums text-slate-600">{fmtNum(r.otWeekday)}</td>
                  <td className="px-3 py-2 text-right tabular-nums text-slate-600">{fmtNum(r.otWeekend)}</td>
                  <td className="px-3 py-2 text-right tabular-nums text-slate-600">{fmtNum(r.otHoliday)}</td>
                  <td className="px-3 py-2 text-right font-semibold tabular-nums text-brand-800">{fmtNum(r.otWeighted)}</td>
                </tr>
              ))}
            </tbody>
            {!report.isLoading && rows.length > 0 && report.data && (
              <tfoot className="border-t-2 border-brand-200 bg-brand-50 font-semibold text-brand-800">
                <tr>
                  <td className="px-3 py-2.5 text-right" colSpan={4}>Tổng</td>
                  <td className="px-3 py-2.5 text-right tabular-nums">{fmtNum(report.data.grandTotalWorkHours)}</td>
                  <td className="px-3 py-2.5" colSpan={3}></td>
                  <td className="px-3 py-2.5 text-right tabular-nums">{fmtNum(report.data.grandTotalOtWeighted)}</td>
                </tr>
              </tfoot>
            )}
          </table>
        </div>
      </section>
    </div>
  )
}
