"use client"

import { useState } from "react"

import { hrReportsApi } from "@/lib/api/hr-reports"
import { errorMessage } from "@/lib/error-map"
import {
  AttendanceSummaryRow,
  DocumentExpiryReportRow,
  LateArrivalReportRow,
  LeaveBalanceReportRow,
  OvertimeReportRow,
  PayrollRegisterRow,
  SalaryHistoryRow,
} from "@/types/hrm"

import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { toast } from "@/components/ui/toast"

const REPORTS = [
  "Attendance Summary",
  "Overtime",
  "Late Arrivals",
  "Payroll Register",
  "Salary History",
  "Leave Balances",
  "Document Expiry",
] as const
type ReportName = (typeof REPORTS)[number]

const now = new Date()

export default function HrReportsPage() {
  const [report, setReport] = useState<ReportName>("Attendance Summary")
  const [periodYear, setPeriodYear] = useState(now.getFullYear())
  const [periodMonth, setPeriodMonth] = useState(now.getMonth() + 1)
  const [payrollRunId, setPayrollRunId] = useState("")
  const [employeeId, setEmployeeId] = useState("")
  const [year, setYear] = useState(now.getFullYear())
  const [withinDays, setWithinDays] = useState(30)
  const [loading, setLoading] = useState(false)

  const [attendanceRows, setAttendanceRows] = useState<AttendanceSummaryRow[]>([])
  const [otRows, setOtRows] = useState<OvertimeReportRow[]>([])
  const [lateRows, setLateRows] = useState<LateArrivalReportRow[]>([])
  const [payrollRows, setPayrollRows] = useState<PayrollRegisterRow[]>([])
  const [salaryRows, setSalaryRows] = useState<SalaryHistoryRow[]>([])
  const [leaveRows, setLeaveRows] = useState<LeaveBalanceReportRow[]>([])
  const [expiryRows, setExpiryRows] = useState<DocumentExpiryReportRow[]>([])

  async function run() {
    setLoading(true)
    try {
      switch (report) {
        case "Attendance Summary": setAttendanceRows(await hrReportsApi.attendanceSummary(periodYear, periodMonth)); break
        case "Overtime": setOtRows(await hrReportsApi.overtime(periodYear, periodMonth)); break
        case "Late Arrivals": setLateRows(await hrReportsApi.lateArrivals(periodYear, periodMonth)); break
        case "Payroll Register": setPayrollRows(await hrReportsApi.payrollRegister(Number(payrollRunId))); break
        case "Salary History": setSalaryRows(await hrReportsApi.salaryHistory(Number(employeeId))); break
        case "Leave Balances": setLeaveRows(await hrReportsApi.leaveBalances(year)); break
        case "Document Expiry": setExpiryRows(await hrReportsApi.documentExpiry(withinDays)); break
      }
    } catch (err) {
      toast.error("Could not load report", errorMessage(err))
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="flex flex-col gap-6">
      <div>
        <h1 className="text-2xl font-bold text-foreground">Reports</h1>
        <p className="text-base text-muted-foreground">Read-only views over Attendance, Payroll, Leave, and Documents.</p>
      </div>

      <div className="flex flex-wrap items-end gap-3">
        <div className="flex flex-col gap-1.5">
          <label className="text-sm font-medium">Report</label>
          <Select value={report} onValueChange={(v) => setReport((v as ReportName) ?? "Attendance Summary")}>
            <SelectTrigger className="w-56"><SelectValue /></SelectTrigger>
            <SelectContent>{REPORTS.map((r) => <SelectItem key={r} value={r}>{r}</SelectItem>)}</SelectContent>
          </Select>
        </div>

        {(report === "Attendance Summary" || report === "Overtime" || report === "Late Arrivals") && (
          <>
            <div className="flex flex-col gap-1.5"><label className="text-sm font-medium">Year</label><Input type="number" className="w-28" value={periodYear} onChange={(e) => setPeriodYear(Number(e.target.value))} /></div>
            <div className="flex flex-col gap-1.5"><label className="text-sm font-medium">Month</label><Input type="number" min={1} max={12} className="w-24" value={periodMonth} onChange={(e) => setPeriodMonth(Number(e.target.value))} /></div>
          </>
        )}
        {report === "Payroll Register" && (
          <div className="flex flex-col gap-1.5"><label className="text-sm font-medium">Payroll run ID</label><Input className="w-32" value={payrollRunId} onChange={(e) => setPayrollRunId(e.target.value)} /></div>
        )}
        {report === "Salary History" && (
          <div className="flex flex-col gap-1.5"><label className="text-sm font-medium">Employee ID</label><Input className="w-32" value={employeeId} onChange={(e) => setEmployeeId(e.target.value)} /></div>
        )}
        {report === "Leave Balances" && (
          <div className="flex flex-col gap-1.5"><label className="text-sm font-medium">Year</label><Input type="number" className="w-28" value={year} onChange={(e) => setYear(Number(e.target.value))} /></div>
        )}
        {report === "Document Expiry" && (
          <div className="flex flex-col gap-1.5"><label className="text-sm font-medium">Within days</label><Input type="number" className="w-28" value={withinDays} onChange={(e) => setWithinDays(Number(e.target.value))} /></div>
        )}

        <Button onClick={run} disabled={loading}>{loading ? "Loading…" : "Run"}</Button>
      </div>

      {report === "Attendance Summary" && (
        <Table className="text-base">
          <TableHeader><TableRow><TableHead className="h-12 px-3 text-sm">Employee</TableHead><TableHead className="h-12 px-3 text-sm">Dept</TableHead><TableHead className="h-12 px-3 text-sm">Present</TableHead><TableHead className="h-12 px-3 text-sm">Absent</TableHead><TableHead className="h-12 px-3 text-sm">Leave</TableHead><TableHead className="h-12 px-3 text-sm">OT (min)</TableHead><TableHead className="h-12 px-3 text-sm">Late (min)</TableHead></TableRow></TableHeader>
          <TableBody>{attendanceRows.map((r) => (
            <TableRow key={r.employeeId}><TableCell className="px-3 py-3">{r.employeeName} ({r.employeeCode})</TableCell><TableCell className="px-3 py-3">{r.departmentName ?? "—"}</TableCell><TableCell className="px-3 py-3">{r.presentDays}</TableCell><TableCell className="px-3 py-3">{r.absentDays}</TableCell><TableCell className="px-3 py-3">{r.leaveDays}</TableCell><TableCell className="px-3 py-3">{r.otMinutesTotal}</TableCell><TableCell className="px-3 py-3">{r.lateMinutesTotal}</TableCell></TableRow>
          ))}</TableBody>
        </Table>
      )}

      {report === "Overtime" && (
        <Table className="text-base">
          <TableHeader><TableRow><TableHead className="h-12 px-3 text-sm">Employee</TableHead><TableHead className="h-12 px-3 text-sm">Date</TableHead><TableHead className="h-12 px-3 text-sm">OT (min)</TableHead></TableRow></TableHeader>
          <TableBody>{otRows.map((r, i) => (
            <TableRow key={i}><TableCell className="px-3 py-3">{r.employeeName} ({r.employeeCode})</TableCell><TableCell className="px-3 py-3">{new Date(r.attendanceDate).toLocaleDateString()}</TableCell><TableCell className="px-3 py-3">{r.overtimeMinutes}</TableCell></TableRow>
          ))}</TableBody>
        </Table>
      )}

      {report === "Late Arrivals" && (
        <Table className="text-base">
          <TableHeader><TableRow><TableHead className="h-12 px-3 text-sm">Employee</TableHead><TableHead className="h-12 px-3 text-sm">Date</TableHead><TableHead className="h-12 px-3 text-sm">Late (min)</TableHead></TableRow></TableHeader>
          <TableBody>{lateRows.map((r, i) => (
            <TableRow key={i}><TableCell className="px-3 py-3">{r.employeeName} ({r.employeeCode})</TableCell><TableCell className="px-3 py-3">{new Date(r.attendanceDate).toLocaleDateString()}</TableCell><TableCell className="px-3 py-3">{r.lateMinutes}</TableCell></TableRow>
          ))}</TableBody>
        </Table>
      )}

      {report === "Payroll Register" && (
        <Table className="text-base">
          <TableHeader><TableRow><TableHead className="h-12 px-3 text-sm">Employee</TableHead><TableHead className="h-12 px-3 text-sm">Gross</TableHead><TableHead className="h-12 px-3 text-sm">Deductions</TableHead><TableHead className="h-12 px-3 text-sm">Net</TableHead></TableRow></TableHeader>
          <TableBody>{payrollRows.map((r) => (
            <TableRow key={r.payrollLineId}><TableCell className="px-3 py-3">{r.employeeName} ({r.employeeCode})</TableCell><TableCell className="px-3 py-3">{r.grossSalary.toFixed(2)}</TableCell><TableCell className="px-3 py-3">{r.totalDeductions.toFixed(2)}</TableCell><TableCell className="px-3 py-3">{r.netSalary.toFixed(2)}</TableCell></TableRow>
          ))}</TableBody>
        </Table>
      )}

      {report === "Salary History" && (
        <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>{salaryRows.map((r) => (
            <TableRow key={r.employeeSalaryStructureId}><TableCell className="px-3 py-3">{new Date(r.effectiveFrom).toLocaleDateString()}</TableCell><TableCell className="px-3 py-3">{r.effectiveTo ? new Date(r.effectiveTo).toLocaleDateString() : "Current"}</TableCell><TableCell className="px-3 py-3">{r.basicSalary.toFixed(2)}</TableCell><TableCell className="px-3 py-3">{r.status}</TableCell></TableRow>
          ))}</TableBody>
        </Table>
      )}

      {report === "Leave Balances" && (
        <Table className="text-base">
          <TableHeader><TableRow><TableHead className="h-12 px-3 text-sm">Employee</TableHead><TableHead className="h-12 px-3 text-sm">Leave type</TableHead><TableHead className="h-12 px-3 text-sm">Entitled</TableHead><TableHead className="h-12 px-3 text-sm">Taken</TableHead><TableHead className="h-12 px-3 text-sm">Remaining</TableHead></TableRow></TableHeader>
          <TableBody>{leaveRows.map((r, i) => (
            <TableRow key={i}><TableCell className="px-3 py-3">{r.employeeName} ({r.employeeCode})</TableCell><TableCell className="px-3 py-3">{r.leaveTypeName}</TableCell><TableCell className="px-3 py-3">{r.entitledDays}</TableCell><TableCell className="px-3 py-3">{r.takenDays}</TableCell><TableCell className="px-3 py-3">{r.remainingDays}</TableCell></TableRow>
          ))}</TableBody>
        </Table>
      )}

      {report === "Document Expiry" && (
        <Table className="text-base">
          <TableHeader><TableRow><TableHead className="h-12 px-3 text-sm">Employee</TableHead><TableHead className="h-12 px-3 text-sm">Document type</TableHead><TableHead className="h-12 px-3 text-sm">Expiry date</TableHead><TableHead className="h-12 px-3 text-sm">Days left</TableHead></TableRow></TableHeader>
          <TableBody>{expiryRows.map((r) => (
            <TableRow key={r.employeeDocumentId}><TableCell className="px-3 py-3">{r.employeeName} ({r.employeeCode})</TableCell><TableCell className="px-3 py-3">{r.documentTypeName}</TableCell><TableCell className="px-3 py-3">{new Date(r.expiryDate).toLocaleDateString()}</TableCell><TableCell className="px-3 py-3">{r.daysUntilExpiry}</TableCell></TableRow>
          ))}</TableBody>
        </Table>
      )}
    </div>
  )
}
