"use client"

import { useEffect, useState } from "react"
import Link from "next/link"
import { Download, Eye, Plus, Upload } from "lucide-react"

import { attendanceApi, attendanceTemplateUrl } from "@/lib/api/attendance"
import { errorMessage } from "@/lib/error-map"
import { cn } from "@/lib/utils"
import { PaginationMeta } from "@/types/common"
import { AttendanceUploadBatch } from "@/types/hrm"

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

const PAGE_SIZE = 10

const STATUS_STYLE: Record<AttendanceUploadBatch["status"], string> = {
  Draft: "bg-muted text-muted-foreground",
  Validated: "bg-warning/10 text-warning",
  Confirmed: "bg-success/10 text-success",
  UsedInPayroll: "bg-primary/10 text-primary",
}

export default function AttendanceBatchesPage() {
  const [batches, setBatches] = useState<AttendanceUploadBatch[] | null>(null)
  const [pagination, setPagination] = useState<PaginationMeta | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [page, setPage] = useState(1)

  const [open, setOpen] = useState(false)
  const [periodStart, setPeriodStart] = useState("")
  const [periodEnd, setPeriodEnd] = useState("")
  const [file, setFile] = useState<File | null>(null)
  const [submitting, setSubmitting] = useState(false)

  function load() {
    attendanceApi
      .list({ page, pageSize: PAGE_SIZE })
      .then((res) => { setBatches(res.items); setPagination(res.pagination) })
      .catch((err) => setError(errorMessage(err)))
  }
  useEffect(load, [page])

  async function handleUpload() {
    if (!file) { toast.error("Choose an Excel or CSV file first"); return }
    if (!periodStart || !periodEnd) { toast.error("Period start/end are required"); return }
    setSubmitting(true)
    try {
      await attendanceApi.upload(file, periodStart, periodEnd)
      toast.success("Attendance uploaded", "Review the preview and confirm when ready.")
      setOpen(false)
      setFile(null)
      setPeriodStart("")
      setPeriodEnd("")
      load()
    } catch (err) {
      toast.error("Could not upload attendance", errorMessage(err))
    } finally {
      setSubmitting(false)
    }
  }

  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">Attendance</h1>
          <p className="text-base text-muted-foreground">Upload → Preview → Confirm. Once Confirmed, a batch becomes payroll&apos;s source of truth.</p>
        </div>
        <div className="flex gap-2">
          <a href={attendanceTemplateUrl()} className={cn(buttonVariants({ variant: "outline" }))}>
            <Download className="size-4" />Download template
          </a>
          <Dialog open={open} onOpenChange={setOpen}>
            <DialogTrigger render={<Button size="lg"><Plus className="size-5" />Upload</Button>} />
            <DialogContent className="sm:max-w-sm">
              <DialogHeader className="items-center text-center">
                <DialogTitle>Upload Attendance</DialogTitle>
                <DialogDescription>Columns: Employee Code, Date, Check In, Check Out.</DialogDescription>
              </DialogHeader>
              <FieldGroup>
                <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                  <Field><FieldLabel htmlFor="a-start">Period start</FieldLabel><Input id="a-start" type="date" value={periodStart} onChange={(e) => setPeriodStart(e.target.value)} /></Field>
                  <Field><FieldLabel htmlFor="a-end">Period end</FieldLabel><Input id="a-end" type="date" value={periodEnd} onChange={(e) => setPeriodEnd(e.target.value)} /></Field>
                </div>
                <Field>
                  <FieldLabel htmlFor="a-file">File (.xlsx or .csv)</FieldLabel>
                  <Input id="a-file" type="file" accept=".xlsx,.csv" onChange={(e) => setFile(e.target.files?.[0] ?? null)} />
                </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={() => setOpen(false)} disabled={submitting}>Cancel</Button>
                <Button className="w-full sm:w-auto sm:min-w-32" onClick={handleUpload} disabled={submitting}><Upload className="size-4" />{submitting ? "Uploading…" : "Upload"}</Button>
              </div>
            </DialogContent>
          </Dialog>
        </div>
      </div>

      {error && <div className="rounded-lg border border-destructive/30 bg-destructive/5 p-5 text-base text-destructive">{error}</div>}
      {!error && batches === null && <div className="flex flex-col gap-3">{Array.from({ length: 4 }).map((_, i) => <Skeleton key={i} className="h-14 w-full" />)}</div>}
      {!error && batches !== null && batches.length === 0 && (
        <div className="flex flex-col items-center gap-4 rounded-xl border border-dashed py-20 text-center"><p className="text-base text-muted-foreground">No attendance batches yet.</p></div>
      )}
      {!error && batches !== null && batches.length > 0 && (
        <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">Period</TableHead>
              <TableHead className="h-12 px-3 text-sm">Rows</TableHead>
              <TableHead className="h-12 px-3 text-sm">Duplicates/Errors</TableHead>
              <TableHead className="h-12 px-3 text-sm">Status</TableHead>
              <TableHead className="h-12 px-3 text-sm">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {batches.map((b) => (
              <TableRow key={b.attendanceUploadBatchId}>
                <TableCell className="px-3 py-3.5 font-medium">{b.docNo}</TableCell>
                <TableCell className="px-3 py-3.5">{new Date(b.periodStart).toLocaleDateString()} – {new Date(b.periodEnd).toLocaleDateString()}</TableCell>
                <TableCell className="px-3 py-3.5">{b.rowCountTotal}</TableCell>
                <TableCell className="px-3 py-3.5">{b.rowCountDuplicate} / {b.rowCountError}</TableCell>
                <TableCell className="px-3 py-3.5"><Badge variant="outline" className={cn("h-6 w-fit justify-center border-transparent px-2.5 text-sm", STATUS_STYLE[b.status])}>{b.status}</Badge></TableCell>
                <TableCell className="px-3 py-3.5">
                  <Link href={`/dashboard/hrm/attendance/${b.attendanceUploadBatchId}`} className={cn(buttonVariants({ variant: "ghost", size: "icon-sm" }))} aria-label="View"><Eye className="size-4" /></Link>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      )}
      {pagination && pagination.totalPages > 1 && (
        <div className="flex items-center justify-between">
          <p className="text-sm text-muted-foreground">Showing {(pagination.page - 1) * pagination.pageSize + 1}–{Math.min(pagination.page * pagination.pageSize, pagination.totalItems)} of {pagination.totalItems}</p>
          <div className="flex items-center gap-2">
            <Button type="button" variant="outline" size="sm" disabled={pagination.page <= 1} onClick={() => setPage((p) => Math.max(1, p - 1))}>Previous</Button>
            <span className="text-sm text-muted-foreground">Page {pagination.page} of {pagination.totalPages}</span>
            <Button type="button" variant="outline" size="sm" disabled={pagination.page >= pagination.totalPages} onClick={() => setPage((p) => Math.min(pagination.totalPages, p + 1))}>Next</Button>
          </div>
        </div>
      )}
    </div>
  )
}
