"use client"

import { useEffect, useState } from "react"
import { useParams } from "next/navigation"
import { Link2, Plus, Upload } from "lucide-react"

import { CreateEmployeeLoanRequest, CreateSalaryStructureRequest, employeesApi } from "@/lib/api/employees"
import { departmentsApi, designationsApi, employmentTypesApi, hrDocumentTypesApi, salaryComponentsApi, workShiftsApi } from "@/lib/api/hrm-masters"
import { errorMessage } from "@/lib/error-map"
import { cn } from "@/lib/utils"
import {
  Department,
  Designation,
  EmployeeBankDetail,
  EmployeeDetail,
  EmployeeDocument,
  EmployeeLoan,
  EmployeeSalaryStructure,
  EmploymentType,
  HrDocumentType,
  LoanKind,
  SalaryComponent,
  WorkShift,
} from "@/types/hrm"

import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
import { Field, FieldGroup, FieldLabel } from "@/components/ui/field"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Skeleton } from "@/components/ui/skeleton"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { toast } from "@/components/ui/toast"

const TABS = ["Overview", "Bank Details", "Documents", "Salary & Loans"] as const
type Tab = (typeof TABS)[number]

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

export default function EmployeeDetailPage() {
  const params = useParams<{ id: string }>()
  const employeeId = Number(params.id)

  const [tab, setTab] = useState<Tab>("Overview")
  const [employee, setEmployee] = useState<EmployeeDetail | null>(null)
  const [etag, setEtag] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)

  const [departments, setDepartments] = useState<Department[]>([])
  const [designations, setDesignations] = useState<Designation[]>([])
  const [employmentTypes, setEmploymentTypes] = useState<EmploymentType[]>([])
  const [workShifts, setWorkShifts] = useState<WorkShift[]>([])
  const [saving, setSaving] = useState(false)

  const [bankDetails, setBankDetails] = useState<EmployeeBankDetail[]>([])
  const [documents, setDocuments] = useState<EmployeeDocument[]>([])
  const [documentTypes, setDocumentTypes] = useState<HrDocumentType[]>([])
  const [uploadTypeId, setUploadTypeId] = useState<string>("")

  const [salaryStructures, setSalaryStructures] = useState<EmployeeSalaryStructure[]>([])
  const [salaryComponents, setSalaryComponents] = useState<SalaryComponent[]>([])
  const [loans, setLoans] = useState<EmployeeLoan[]>([])

  const [structureOpen, setStructureOpen] = useState(false)
  const [structureEffectiveFrom, setStructureEffectiveFrom] = useState("")
  const [structureBasic, setStructureBasic] = useState(0)
  const [structureLines, setStructureLines] = useState<{ salaryComponentId: string; amount: number }[]>([])

  const [loanOpen, setLoanOpen] = useState(false)
  const [loanKind, setLoanKind] = useState<LoanKind>("Loan")
  const [loanPrincipal, setLoanPrincipal] = useState(0)
  const [loanInstallmentAmount, setLoanInstallmentAmount] = useState(0)
  const [loanCount, setLoanCount] = useState(1)
  const now = new Date()
  const [loanStartYear, setLoanStartYear] = useState(now.getFullYear())
  const [loanStartMonth, setLoanStartMonth] = useState(now.getMonth() + 1)
  const [busy, setBusy] = useState(false)

  function load() {
    employeesApi.get(employeeId)
      .then((res) => { setEmployee(res.data); setEtag(res.etag) })
      .catch((err) => setError(errorMessage(err)))
  }
  useEffect(load, [employeeId])

  useEffect(() => {
    departmentsApi.list({ pageSize: 200, status: "Active" }).then((r) => setDepartments(r.items)).catch(() => setDepartments([]))
    designationsApi.list({ pageSize: 200, status: "Active" }).then((r) => setDesignations(r.items)).catch(() => setDesignations([]))
    employmentTypesApi.list({ pageSize: 200, status: "Active" }).then((r) => setEmploymentTypes(r.items)).catch(() => setEmploymentTypes([]))
    workShiftsApi.list({ pageSize: 200, status: "Active" }).then((r) => setWorkShifts(r.items)).catch(() => setWorkShifts([]))
    hrDocumentTypesApi.list({ pageSize: 200, status: "Active" }).then((r) => setDocumentTypes(r.items)).catch(() => setDocumentTypes([]))
  }, [])

  useEffect(() => {
    if (tab === "Bank Details") employeesApi.listBankDetails(employeeId).then(setBankDetails).catch((err) => toast.error("Could not load bank details", errorMessage(err)))
    if (tab === "Documents") employeesApi.listDocuments(employeeId).then(setDocuments).catch((err) => toast.error("Could not load documents", errorMessage(err)))
    if (tab === "Salary & Loans") {
      employeesApi.salaryStructureHistory(employeeId).then(setSalaryStructures).catch((err) => toast.error("Could not load salary history", errorMessage(err)))
      employeesApi.listLoans(employeeId).then(setLoans).catch((err) => toast.error("Could not load loans", errorMessage(err)))
      salaryComponentsApi.list({ pageSize: 200, status: "Active" }).then((r) => setSalaryComponents(r.items)).catch(() => setSalaryComponents([]))
    }
  }, [tab, employeeId])

  function addStructureLine() {
    setStructureLines((prev) => [...prev, { salaryComponentId: "", amount: 0 }])
  }

  async function createStructure() {
    if (!structureEffectiveFrom) { toast.error("Effective date is required"); return }
    const lines = structureLines.filter((l) => l.salaryComponentId).map((l) => ({ salaryComponentId: Number(l.salaryComponentId), amount: l.amount }))
    const request: CreateSalaryStructureRequest = { effectiveFrom: structureEffectiveFrom, basicSalary: structureBasic, lines }
    setBusy(true)
    try {
      await employeesApi.createSalaryStructure(employeeId, request)
      toast.success("Salary structure saved")
      setStructureOpen(false)
      setStructureEffectiveFrom("")
      setStructureBasic(0)
      setStructureLines([])
      employeesApi.salaryStructureHistory(employeeId).then(setSalaryStructures)
    } catch (err) {
      toast.error("Could not save salary structure", errorMessage(err))
    } finally {
      setBusy(false)
    }
  }

  async function createLoan() {
    if (loanPrincipal <= 0 || loanInstallmentAmount <= 0 || loanCount <= 0) { toast.error("Principal, installment amount, and count must be positive"); return }
    const request: CreateEmployeeLoanRequest = {
      loanKind, principalAmount: loanPrincipal, interestRate: 0, installmentAmount: loanInstallmentAmount,
      numberOfInstallments: loanCount, startYear: loanStartYear, startMonth: loanStartMonth,
    }
    setBusy(true)
    try {
      await employeesApi.createLoan(employeeId, request)
      toast.success("Loan created")
      setLoanOpen(false)
      setLoanPrincipal(0)
      setLoanInstallmentAmount(0)
      setLoanCount(1)
      employeesApi.listLoans(employeeId).then(setLoans)
    } catch (err) {
      toast.error("Could not create loan", errorMessage(err))
    } finally {
      setBusy(false)
    }
  }

  async function handleSave() {
    if (!employee || !etag) return
    setSaving(true)
    try {
      const res = await employeesApi.update(employeeId, {
        fullName: employee.fullName,
        nic: employee.nic,
        dateOfBirth: employee.dateOfBirth,
        gender: employee.gender,
        nationality: employee.nationality,
        email: employee.email,
        personalMobile: employee.personalMobile,
        addressLine1: employee.addressLine1,
        addressLine2: employee.addressLine2,
        city: employee.city,
        postalCode: employee.postalCode,
        country: employee.country,
        emergencyContactName: employee.emergencyContactName,
        emergencyContactRelationship: employee.emergencyContactRelationship,
        emergencyContactPhone: employee.emergencyContactPhone,
        hireDate: employee.hireDate,
        confirmationDate: employee.confirmationDate,
        lastWorkingDate: employee.lastWorkingDate,
        departmentId: employee.departmentId,
        designationId: employee.designationId,
        employmentTypeId: employee.employmentTypeId,
        branchId: employee.branchId,
        workShiftId: employee.workShiftId,
        reportingManagerId: employee.reportingManagerId,
        epfNumber: employee.epfNumber,
        etfNumber: employee.etfNumber,
        taxIdentificationNumber: employee.taxIdentificationNumber,
      }, etag)
      setEmployee(res.data)
      setEtag(res.etag)
      toast.success("Employee updated")
    } catch (err) {
      toast.error("Could not save", errorMessage(err))
    } finally {
      setSaving(false)
    }
  }

  async function handleUpload(file: File) {
    if (!uploadTypeId) { toast.error("Select a document type first"); return }
    try {
      const doc = await employeesApi.uploadDocument(employeeId, file, { hrDocumentTypeId: Number(uploadTypeId) })
      setDocuments((prev) => [doc, ...prev])
      toast.success("Document uploaded")
    } catch (err) {
      toast.error("Could not upload document", errorMessage(err))
    }
  }

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

  return (
    <div className="flex flex-col gap-6">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground">{employee.fullName}</h1>
          <p className="text-base text-muted-foreground">
            {employee.employeeCode}
            {employee.userId ? (
              <span className="ml-2 inline-flex items-center gap-1 text-primary"><Link2 className="size-3.5" />Linked to a system user</span>
            ) : (
              <span className="ml-2 text-muted-foreground">No system login</span>
            )}
          </p>
        </div>
        <Badge variant="outline" className={cn("h-7 px-3 text-sm", employee.status === "Active" ? "bg-success/10 text-success" : "bg-muted text-muted-foreground")}>{employee.status}</Badge>
      </div>

      <div className="flex gap-1 rounded-xl bg-muted p-1 w-fit">
        {TABS.map((t) => (
          <button
            key={t}
            onClick={() => setTab(t)}
            className={cn("rounded-lg px-4 py-2 text-sm font-medium transition-colors", tab === t ? "bg-card shadow-sm text-foreground" : "text-muted-foreground hover:text-foreground")}
          >
            {t}
          </button>
        ))}
      </div>

      {tab === "Overview" && (
        <FieldGroup className="max-w-2xl">
          <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
            <Field><FieldLabel>Full name</FieldLabel><Input value={employee.fullName} onChange={(e) => setEmployee({ ...employee, fullName: e.target.value })} /></Field>
            <Field><FieldLabel>Email</FieldLabel><Input type="email" value={employee.email ?? ""} onChange={(e) => setEmployee({ ...employee, email: e.target.value })} /></Field>
            <Field><FieldLabel>NIC</FieldLabel><Input value={employee.nic ?? ""} onChange={(e) => setEmployee({ ...employee, nic: e.target.value })} /></Field>
            <Field><FieldLabel>Personal mobile</FieldLabel><Input value={employee.personalMobile ?? ""} onChange={(e) => setEmployee({ ...employee, personalMobile: e.target.value })} /></Field>
            <Field>
              <FieldLabel>Department</FieldLabel>
              <Select value={String(employee.departmentId)} onValueChange={(v) => setEmployee({ ...employee, departmentId: Number(v) })}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>{departments.map((d) => <SelectItem key={d.departmentId} value={String(d.departmentId)}>{d.name}</SelectItem>)}</SelectContent>
              </Select>
            </Field>
            <Field>
              <FieldLabel>Designation</FieldLabel>
              <Select value={String(employee.designationId)} onValueChange={(v) => setEmployee({ ...employee, designationId: Number(v) })}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>{designations.map((d) => <SelectItem key={d.designationId} value={String(d.designationId)}>{d.name}</SelectItem>)}</SelectContent>
              </Select>
            </Field>
            <Field>
              <FieldLabel>Employment type</FieldLabel>
              <Select value={String(employee.employmentTypeId)} onValueChange={(v) => setEmployee({ ...employee, employmentTypeId: Number(v) })}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>{employmentTypes.map((t) => <SelectItem key={t.employmentTypeId} value={String(t.employmentTypeId)}>{t.name}</SelectItem>)}</SelectContent>
              </Select>
            </Field>
            <Field>
              <FieldLabel>Work shift</FieldLabel>
              <Select value={String(employee.workShiftId)} onValueChange={(v) => setEmployee({ ...employee, workShiftId: Number(v) })}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>{workShifts.map((w) => <SelectItem key={w.workShiftId} value={String(w.workShiftId)}>{w.name}</SelectItem>)}</SelectContent>
              </Select>
            </Field>
            <Field><FieldLabel>EPF number</FieldLabel><Input value={employee.epfNumber ?? ""} onChange={(e) => setEmployee({ ...employee, epfNumber: e.target.value })} /></Field>
            <Field><FieldLabel>ETF number</FieldLabel><Input value={employee.etfNumber ?? ""} onChange={(e) => setEmployee({ ...employee, etfNumber: e.target.value })} /></Field>
          </div>
          <div className="flex justify-end pt-2">
            <Button onClick={handleSave} disabled={saving}>{saving ? "Saving…" : "Save changes"}</Button>
          </div>
        </FieldGroup>
      )}

      {tab === "Bank Details" && (
        <div className="flex flex-col gap-4">
          <Table className="text-base">
            <TableHeader>
              <TableRow>
                <TableHead className="h-12 px-3 text-sm">Bank</TableHead>
                <TableHead className="h-12 px-3 text-sm">Branch</TableHead>
                <TableHead className="h-12 px-3 text-sm">Account</TableHead>
                <TableHead className="h-12 px-3 text-sm">Primary</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {bankDetails.map((b, i) => (
                <TableRow key={b.employeeBankDetailId ?? i}>
                  <TableCell className="px-3 py-3.5">{b.bankName}</TableCell>
                  <TableCell className="px-3 py-3.5">{b.branchName}</TableCell>
                  <TableCell className="px-3 py-3.5">{b.accountNumber}</TableCell>
                  <TableCell className="px-3 py-3.5">{b.isPrimary ? "Yes" : "—"}</TableCell>
                </TableRow>
              ))}
              {bankDetails.length === 0 && (
                <TableRow><TableCell colSpan={4} className="px-3 py-8 text-center text-muted-foreground">No bank details on file.</TableCell></TableRow>
              )}
            </TableBody>
          </Table>
        </div>
      )}

      {tab === "Documents" && (
        <div className="flex flex-col gap-4">
          <div className="flex items-center gap-3">
            <Select value={uploadTypeId} onValueChange={(v) => setUploadTypeId(v ?? "")}>
              <SelectTrigger className="w-56"><SelectValue placeholder="Document type" /></SelectTrigger>
              <SelectContent>{documentTypes.map((t) => <SelectItem key={t.hrDocumentTypeId} value={String(t.hrDocumentTypeId)}>{t.name}</SelectItem>)}</SelectContent>
            </Select>
            <label className={cn("inline-flex cursor-pointer items-center gap-2 rounded-lg border px-4 py-2 text-sm font-medium hover:bg-muted")}>
              <Upload className="size-4" />
              Upload
              <input type="file" className="hidden" accept=".pdf,.jpg,.jpeg,.png,.docx" onChange={(e) => { const f = e.target.files?.[0]; if (f) handleUpload(f); e.target.value = "" }} />
            </label>
          </div>
          <Table className="text-base">
            <TableHeader>
              <TableRow>
                <TableHead className="h-12 px-3 text-sm">File</TableHead>
                <TableHead className="h-12 px-3 text-sm">Type</TableHead>
                <TableHead className="h-12 px-3 text-sm">Uploaded</TableHead>
                <TableHead className="h-12 px-3 text-sm">Status</TableHead>
                <TableHead className="h-12 px-3 text-sm">Download</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {documents.map((d) => (
                <TableRow key={d.employeeDocumentId}>
                  <TableCell className="px-3 py-3.5">{d.originalFileName}</TableCell>
                  <TableCell className="px-3 py-3.5">{d.hrDocumentTypeName ?? "—"}</TableCell>
                  <TableCell className="px-3 py-3.5">{new Date(d.uploadedAt).toLocaleDateString()}</TableCell>
                  <TableCell className="px-3 py-3.5">{d.status}</TableCell>
                  <TableCell className="px-3 py-3.5">
                    <a href={employeesApi.documentDownloadUrl(employeeId, d.employeeDocumentId)} className="text-primary underline underline-offset-2" target="_blank" rel="noreferrer">Download</a>
                  </TableCell>
                </TableRow>
              ))}
              {documents.length === 0 && (
                <TableRow><TableCell colSpan={5} className="px-3 py-8 text-center text-muted-foreground">No documents uploaded yet.</TableCell></TableRow>
              )}
            </TableBody>
          </Table>
        </div>
      )}

      {tab === "Salary & Loans" && (
        <div className="flex flex-col gap-8">
          <section className="flex flex-col gap-4">
            <div className="flex items-center justify-between">
              <h2 className="text-lg font-semibold text-foreground">Salary Structure</h2>
              <Dialog open={structureOpen} onOpenChange={(v) => { setStructureOpen(v); if (v && structureLines.length === 0) addStructureLine() }}>
                <DialogTrigger render={<Button size="sm"><Plus className="size-4" />New Structure</Button>} />
                <DialogContent className="sm:max-w-md">
                  <DialogHeader className="items-center text-center">
                    <DialogTitle>New Salary Structure</DialogTitle>
                    <DialogDescription>Supersedes the current open-ended structure from this date.</DialogDescription>
                  </DialogHeader>
                  <FieldGroup>
                    <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                      <Field><FieldLabel>Effective from</FieldLabel><Input type="date" value={structureEffectiveFrom} onChange={(e) => setStructureEffectiveFrom(e.target.value)} /></Field>
                      <Field><FieldLabel>Basic salary</FieldLabel><Input type="number" min={0} value={structureBasic} onChange={(e) => setStructureBasic(Number(e.target.value))} /></Field>
                    </div>
                    <Field>
                      <FieldLabel>Allowances / other deductions</FieldLabel>
                      <div className="flex flex-col gap-2">
                        {structureLines.map((line, i) => (
                          <div key={i} className="flex gap-2">
                            <Select value={line.salaryComponentId} onValueChange={(v) => setStructureLines((prev) => prev.map((l, idx) => (idx === i ? { ...l, salaryComponentId: v ?? "" } : l)))}>
                              <SelectTrigger className="flex-1"><SelectValue placeholder="Component" /></SelectTrigger>
                              <SelectContent>{salaryComponents.map((c) => <SelectItem key={c.salaryComponentId} value={String(c.salaryComponentId)}>{c.name} ({c.componentType})</SelectItem>)}</SelectContent>
                            </Select>
                            <Input type="number" className="w-28" value={line.amount} onChange={(e) => setStructureLines((prev) => prev.map((l, idx) => (idx === i ? { ...l, amount: Number(e.target.value) } : l)))} />
                          </div>
                        ))}
                        <Button type="button" variant="outline" size="sm" onClick={addStructureLine}>Add line</Button>
                      </div>
                    </Field>
                  </FieldGroup>
                  <div className="flex flex-col-reverse gap-3 pt-2 sm:flex-row sm:justify-center">
                    <Button variant="outline" className="w-full sm:w-auto sm:min-w-32" onClick={() => setStructureOpen(false)} disabled={busy}>Cancel</Button>
                    <Button className="w-full sm:w-auto sm:min-w-32" onClick={createStructure} disabled={busy}>{busy ? "Saving…" : "Save"}</Button>
                  </div>
                </DialogContent>
              </Dialog>
            </div>
            <Table className="text-base">
              <TableHeader>
                <TableRow>
                  <TableHead className="h-12 px-3 text-sm">Effective from</TableHead>
                  <TableHead className="h-12 px-3 text-sm">Effective to</TableHead>
                  <TableHead className="h-12 px-3 text-sm">Basic</TableHead>
                  <TableHead className="h-12 px-3 text-sm">Status</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {salaryStructures.map((s) => (
                  <TableRow key={s.employeeSalaryStructureId}>
                    <TableCell className="px-3 py-3.5">{new Date(s.effectiveFrom).toLocaleDateString()}</TableCell>
                    <TableCell className="px-3 py-3.5">{s.effectiveTo ? new Date(s.effectiveTo).toLocaleDateString() : "Current"}</TableCell>
                    <TableCell className="px-3 py-3.5">{money(s.basicSalary)}</TableCell>
                    <TableCell className="px-3 py-3.5">{s.status}</TableCell>
                  </TableRow>
                ))}
                {salaryStructures.length === 0 && (
                  <TableRow><TableCell colSpan={4} className="px-3 py-8 text-center text-muted-foreground">No salary structure set yet.</TableCell></TableRow>
                )}
              </TableBody>
            </Table>
          </section>

          <section className="flex flex-col gap-4">
            <div className="flex items-center justify-between">
              <h2 className="text-lg font-semibold text-foreground">Loans &amp; Advances</h2>
              <Dialog open={loanOpen} onOpenChange={setLoanOpen}>
                <DialogTrigger render={<Button size="sm"><Plus className="size-4" />New Loan</Button>} />
                <DialogContent className="sm:max-w-sm">
                  <DialogHeader className="items-center text-center">
                    <DialogTitle>New Loan / Advance</DialogTitle>
                    <DialogDescription>Generates the full installment schedule up front.</DialogDescription>
                  </DialogHeader>
                  <FieldGroup>
                    <Field>
                      <FieldLabel>Type</FieldLabel>
                      <Select value={loanKind} onValueChange={(v) => setLoanKind((v as LoanKind) ?? "Loan")}>
                        <SelectTrigger><SelectValue /></SelectTrigger>
                        <SelectContent><SelectItem value="Loan">Loan</SelectItem><SelectItem value="Advance">Advance</SelectItem></SelectContent>
                      </Select>
                    </Field>
                    <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                      <Field><FieldLabel>Principal</FieldLabel><Input type="number" min={0} value={loanPrincipal} onChange={(e) => setLoanPrincipal(Number(e.target.value))} /></Field>
                      <Field><FieldLabel>Installment amount</FieldLabel><Input type="number" min={0} value={loanInstallmentAmount} onChange={(e) => setLoanInstallmentAmount(Number(e.target.value))} /></Field>
                      <Field><FieldLabel># installments</FieldLabel><Input type="number" min={1} value={loanCount} onChange={(e) => setLoanCount(Number(e.target.value))} /></Field>
                      <Field><FieldLabel>Start year/month</FieldLabel>
                        <div className="flex gap-2">
                          <Input type="number" value={loanStartYear} onChange={(e) => setLoanStartYear(Number(e.target.value))} />
                          <Input type="number" min={1} max={12} value={loanStartMonth} onChange={(e) => setLoanStartMonth(Number(e.target.value))} />
                        </div>
                      </Field>
                    </div>
                  </FieldGroup>
                  <div className="flex flex-col-reverse gap-3 pt-2 sm:flex-row sm:justify-center">
                    <Button variant="outline" className="w-full sm:w-auto sm:min-w-32" onClick={() => setLoanOpen(false)} disabled={busy}>Cancel</Button>
                    <Button className="w-full sm:w-auto sm:min-w-32" onClick={createLoan} disabled={busy}>{busy ? "Creating…" : "Create"}</Button>
                  </div>
                </DialogContent>
              </Dialog>
            </div>
            <Table className="text-base">
              <TableHeader>
                <TableRow>
                  <TableHead className="h-12 px-3 text-sm">Doc No</TableHead>
                  <TableHead className="h-12 px-3 text-sm">Type</TableHead>
                  <TableHead className="h-12 px-3 text-sm">Principal</TableHead>
                  <TableHead className="h-12 px-3 text-sm">Outstanding</TableHead>
                  <TableHead className="h-12 px-3 text-sm">Status</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {loans.map((l) => (
                  <TableRow key={l.employeeLoanId}>
                    <TableCell className="px-3 py-3.5 font-medium">{l.docNo}</TableCell>
                    <TableCell className="px-3 py-3.5">{l.loanKind}</TableCell>
                    <TableCell className="px-3 py-3.5">{money(l.principalAmount)}</TableCell>
                    <TableCell className="px-3 py-3.5">{money(l.outstandingBalance)}</TableCell>
                    <TableCell className="px-3 py-3.5">{l.status}</TableCell>
                  </TableRow>
                ))}
                {loans.length === 0 && (
                  <TableRow><TableCell colSpan={5} className="px-3 py-8 text-center text-muted-foreground">No loans or advances on file.</TableCell></TableRow>
                )}
              </TableBody>
            </Table>
          </section>
        </div>
      )}
    </div>
  )
}
