"use client"

import { useEffect, useState } from "react"
import { useParams } from "next/navigation"

import { payrollRunsApi } from "@/lib/api/payroll"
import { errorMessage } from "@/lib/error-map"
import { PayrollLineDetail } from "@/types/hrm"

import { Skeleton } from "@/components/ui/skeleton"

function money(n: number): string {
  return n.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

export default function PayrollLineDetailPage() {
  const params = useParams<{ id: string; lineId: string }>()
  const runId = Number(params.id)
  const lineId = Number(params.lineId)

  const [detail, setDetail] = useState<PayrollLineDetail | null>(null)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    payrollRunsApi.getLine(runId, lineId).then(setDetail).catch((err) => setError(errorMessage(err)))
  }, [runId, lineId])

  if (error) return <div className="rounded-lg border border-destructive/30 bg-destructive/5 p-5 text-base text-destructive">{error}</div>
  if (!detail) return <div className="flex flex-col gap-3">{Array.from({ length: 6 }).map((_, i) => <Skeleton key={i} className="h-10 w-full" />)}</div>

  const { line, components } = detail
  const earnings = components.filter((c) => c.componentCategory === "Earning")
  const deductions = components.filter((c) => c.componentCategory === "Deduction")
  const employerContributions = components.filter((c) => c.componentCategory === "EmployerContribution")

  return (
    <div className="mx-auto flex max-w-lg flex-col gap-6">
      <div>
        <h1 className="text-2xl font-bold text-foreground">Salary Breakdown</h1>
        <p className="text-base text-muted-foreground">{line.employeeName} ({line.employeeCode})</p>
      </div>

      <div className="rounded-2xl border bg-card p-6 shadow-sm">
        <table className="w-full text-base">
          <tbody>
            {earnings.map((c, i) => (
              <tr key={i}><td className="py-1.5">{c.label}</td><td className="py-1.5 text-right">{money(c.amount)}</td></tr>
            ))}
            <tr className="border-t font-semibold"><td className="py-2">Gross Salary</td><td className="py-2 text-right">{money(line.grossSalary)}</td></tr>
            <tr><td className="pt-4 text-sm font-semibold text-muted-foreground" colSpan={2}>Deductions</td></tr>
            {deductions.map((c, i) => (
              <tr key={i}><td className="py-1.5">{c.label}</td><td className="py-1.5 text-right">{money(c.amount)}</td></tr>
            ))}
            <tr className="border-t font-bold"><td className="py-2">Net Salary</td><td className="py-2 text-right">{money(line.netSalary)}</td></tr>
            {employerContributions.length > 0 && (
              <>
                <tr><td className="pt-4 text-sm font-semibold text-muted-foreground" colSpan={2}>Employer Contributions (informational — not deducted)</td></tr>
                {employerContributions.map((c, i) => (
                  <tr key={i} className="text-muted-foreground"><td className="py-1.5">{c.label}</td><td className="py-1.5 text-right">{money(c.amount)}</td></tr>
                ))}
              </>
            )}
          </tbody>
        </table>
      </div>

      <div className="grid grid-cols-2 gap-3 text-sm text-muted-foreground sm:grid-cols-3">
        <div>Present days: {line.presentDays}</div>
        <div>Absent days: {line.absentDays}</div>
        <div>Leave days: {line.leaveDays}</div>
        <div>OT minutes: {line.otMinutesTotal}</div>
        <div>Late minutes: {line.lateMinutesTotal}</div>
      </div>
    </div>
  )
}
