"use client"

import { useEffect, useState } from "react"
import { Plus } from "lucide-react"

import { employeesApi } from "@/lib/api/employees"
import { leaveTypesApi } from "@/lib/api/hrm-masters"
import { leaveRequestsApi } from "@/lib/api/leave"
import { errorMessage } from "@/lib/error-map"
import { cn } from "@/lib/utils"
import { PaginationMeta } from "@/types/common"
import { EmployeeListItem, LeaveRequest, LeaveRequestStatus, LeaveType } from "@/types/hrm"

import { Button } 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 { 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 PAGE_SIZE = 10

const STATUS_STYLE: Record<LeaveRequestStatus, string> = {
  Draft: "bg-muted text-muted-foreground",
  Submitted: "bg-warning/10 text-warning",
  Approved: "bg-success/10 text-success",
  Rejected: "bg-destructive/10 text-destructive",
  Cancelled: "bg-muted text-muted-foreground",
}

export default function LeaveRequestsPage() {
  const [requests, setRequests] = useState<LeaveRequest[] | null>(null)
  const [pagination, setPagination] = useState<PaginationMeta | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [page, setPage] = useState(1)

  const [employees, setEmployees] = useState<EmployeeListItem[]>([])
  const [leaveTypes, setLeaveTypes] = useState<LeaveType[]>([])

  const [open, setOpen] = useState(false)
  const [employeeId, setEmployeeId] = useState("")
  const [leaveTypeId, setLeaveTypeId] = useState("")
  const [startDate, setStartDate] = useState("")
  const [endDate, setEndDate] = useState("")
  const [reason, setReason] = useState("")
  const [submitting, setSubmitting] = useState(false)

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

  useEffect(() => {
    employeesApi.list({ pageSize: 200, status: "Active" }).then((r) => setEmployees(r.items)).catch(() => setEmployees([]))
    leaveTypesApi.list({ pageSize: 200, status: "Active" }).then((r) => setLeaveTypes(r.items)).catch(() => setLeaveTypes([]))
  }, [])

  async function handleCreate() {
    if (!employeeId || !leaveTypeId || !startDate || !endDate) { toast.error("All fields except reason are required"); return }
    setSubmitting(true)
    try {
      const created = await leaveRequestsApi.create({ employeeId: Number(employeeId), leaveTypeId: Number(leaveTypeId), startDate, endDate, reason: reason || null })
      await leaveRequestsApi.submit(created.leaveRequestId)
      toast.success("Leave request submitted")
      setOpen(false)
      setEmployeeId(""); setLeaveTypeId(""); setStartDate(""); setEndDate(""); setReason("")
      load()
    } catch (err) {
      toast.error("Could not submit leave request", errorMessage(err))
    } finally {
      setSubmitting(false)
    }
  }

  async function approve(id: number) {
    try {
      await leaveRequestsApi.approve(id)
      toast.success("Leave approved")
      load()
    } catch (err) {
      toast.error("Could not approve", errorMessage(err))
    }
  }

  async function reject(id: number) {
    const reasonText = window.prompt("Reason for rejection:")
    if (!reasonText) return
    try {
      await leaveRequestsApi.reject(id, reasonText)
      toast.success("Leave rejected")
      load()
    } catch (err) {
      toast.error("Could not reject", errorMessage(err))
    }
  }

  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">Leave</h1>
          <p className="text-base text-muted-foreground">Approved leave feeds Attendance&apos;s OnLeave status and Payroll&apos;s No-Pay calculation.</p>
        </div>
        <Dialog open={open} onOpenChange={setOpen}>
          <DialogTrigger render={<Button size="lg"><Plus className="size-5" />New Request</Button>} />
          <DialogContent className="sm:max-w-sm">
            <DialogHeader className="items-center text-center">
              <DialogTitle>New Leave Request</DialogTitle>
              <DialogDescription>Submitted immediately for approval.</DialogDescription>
            </DialogHeader>
            <FieldGroup>
              <Field>
                <FieldLabel>Employee</FieldLabel>
                <Select value={employeeId} onValueChange={(v) => setEmployeeId(v ?? "")}>
                  <SelectTrigger><SelectValue placeholder="Select" /></SelectTrigger>
                  <SelectContent>{employees.map((e) => <SelectItem key={e.employeeId} value={String(e.employeeId)}>{e.fullName} ({e.employeeCode})</SelectItem>)}</SelectContent>
                </Select>
              </Field>
              <Field>
                <FieldLabel>Leave type</FieldLabel>
                <Select value={leaveTypeId} onValueChange={(v) => setLeaveTypeId(v ?? "")}>
                  <SelectTrigger><SelectValue placeholder="Select" /></SelectTrigger>
                  <SelectContent>{leaveTypes.map((t) => <SelectItem key={t.leaveTypeId} value={String(t.leaveTypeId)}>{t.name}</SelectItem>)}</SelectContent>
                </Select>
              </Field>
              <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                <Field><FieldLabel>Start date</FieldLabel><Input type="date" value={startDate} onChange={(e) => setStartDate(e.target.value)} /></Field>
                <Field><FieldLabel>End date</FieldLabel><Input type="date" value={endDate} onChange={(e) => setEndDate(e.target.value)} /></Field>
              </div>
              <Field><FieldLabel>Reason (optional)</FieldLabel><Input value={reason} onChange={(e) => setReason(e.target.value)} /></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={handleCreate} disabled={submitting}>{submitting ? "Submitting…" : "Submit"}</Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      {error && <div className="rounded-lg border border-destructive/30 bg-destructive/5 p-5 text-base text-destructive">{error}</div>}
      {!error && requests === null && <div className="flex flex-col gap-3">{Array.from({ length: 4 }).map((_, i) => <Skeleton key={i} className="h-14 w-full" />)}</div>}
      {!error && requests !== null && requests.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 leave requests yet.</p></div>
      )}
      {!error && requests !== null && requests.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">Employee</TableHead>
              <TableHead className="h-12 px-3 text-sm">Type</TableHead>
              <TableHead className="h-12 px-3 text-sm">Dates</TableHead>
              <TableHead className="h-12 px-3 text-sm">Days</TableHead>
              <TableHead className="h-12 px-3 text-sm">Status</TableHead>
              <TableHead className="h-12 px-3 text-sm">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {requests.map((r) => (
              <TableRow key={r.leaveRequestId}>
                <TableCell className="px-3 py-3.5 font-medium">{r.docNo}</TableCell>
                <TableCell className="px-3 py-3.5">{r.employeeName ?? "—"}</TableCell>
                <TableCell className="px-3 py-3.5">{r.leaveTypeName ?? "—"}</TableCell>
                <TableCell className="px-3 py-3.5">{new Date(r.startDate).toLocaleDateString()} – {new Date(r.endDate).toLocaleDateString()}</TableCell>
                <TableCell className="px-3 py-3.5">{r.daysCount}</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[r.status])}>{r.status}</Badge></TableCell>
                <TableCell className="px-3 py-3.5">
                  {r.status === "Submitted" && (
                    <div className="flex gap-1">
                      <Button variant="ghost" size="sm" onClick={() => approve(r.leaveRequestId)}>Approve</Button>
                      <Button variant="ghost" size="sm" onClick={() => reject(r.leaveRequestId)}>Reject</Button>
                    </div>
                  )}
                </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>
  )
}
