"use client"

import { useState, useMemo } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Dropdown } from "@/components/ui/dropdown"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Badge } from "@/components/ui/badge"

// ─── Types ────────────────────────────────────────────────────────────────────

type LeaveApprovalSummary = {
  approverName: string
  role: string
  status: "pending" | "approved" | "rejected"
  reason?: string | null
}

type LeaveRequest = {
  id: string
  employeeName: string
  leaveTypeName: string
  startDate: string | Date
  endDate: string | Date
  duration: number
  status: "pending" | "approved" | "rejected"
  createdAt: string | Date
  branchName?: string | null
  departmentName?: string | null
  approvalTotal?: number
  approvalApproved?: number
  approvalRejected?: number
  approvalPending?: number
  myApprovalStatus?: "pending" | "approved" | "rejected" | null
  approvals?: LeaveApprovalSummary[]
}

type Branch = { id: string; name: string }

type LeaveRequestListProps = {
  requests: LeaveRequest[]
  branches?: Branch[]
  canProcessLeave?: boolean
}

// ─── Constants ────────────────────────────────────────────────────────────────

const STATUS_OPTIONS = [
  { value: "", label: "All statuses" },
  { value: "pending", label: "Pending" },
  { value: "approved", label: "Approved" },
  { value: "rejected", label: "Rejected" },
]

const STATUS_COLORS: Record<string, string> = {
  pending: "bg-amber-50 text-amber-700 border-amber-200",
  approved: "bg-emerald-50 text-emerald-700 border-emerald-200",
  rejected: "bg-red-50 text-red-700 border-red-200",
}

const LEAVE_TYPE_COLORS: Record<string, { bar: string; label: string }> = {
  Annual:     { bar: "#E24B4A", label: "Annual" },
  Sick:       { bar: "#1D9E75", label: "Sick" },
  "Comp Off": { bar: "#7F77DD", label: "Comp off" },
  Maternity:  { bar: "#D4537E", label: "Maternity" },
  Paternity:  { bar: "#378ADD", label: "Paternity" },
  Unpaid:     { bar: "#888780", label: "Unpaid" },
}

const DEFAULT_BAR_COLOR = "#888780"

const AVATAR_COLORS = [
  { bg: "bg-blue-100",    text: "text-blue-700" },
  { bg: "bg-emerald-100", text: "text-emerald-700" },
  { bg: "bg-orange-100",  text: "text-orange-700" },
  { bg: "bg-pink-100",    text: "text-pink-700" },
  { bg: "bg-amber-100",   text: "text-amber-700" },
  { bg: "bg-violet-100",  text: "text-violet-700" },
]

// ─── Helpers ──────────────────────────────────────────────────────────────────

function parseDate(s: string | Date): Date {
  if (s instanceof Date) {
    const d = new Date(s)
    d.setHours(0, 0, 0, 0)
    return d
  }
  const datePart = s.includes("T") ? s.split("T")[0] : s
  const [y, m, d] = datePart.split("-").map(Number)
  return new Date(y, m - 1, d)
}

function fmtShort(d: Date): string {
  return d.toLocaleDateString("en-GB", { day: "2-digit", month: "short" })
}

function daysInMonth(year: number, month: number): number {
  return new Date(year, month + 1, 0).getDate()
}

function getInitials(name: string): string {
  return name.split(" ").slice(0, 2).map((w) => w[0]).join("").toUpperCase()
}

function avatarColor(name: string) {
  const idx =
    name.split("").reduce((acc, c) => acc + c.charCodeAt(0), 0) %
    AVATAR_COLORS.length
  return AVATAR_COLORS[idx]
}

function isOnLeaveToday(request: LeaveRequest): boolean {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  const start = parseDate(request.startDate)
  const end = parseDate(request.endDate)
  return request.status === "approved" && start <= today && end >= today
}

function getBarColor(leaveTypeName: string): string {
  const key = Object.keys(LEAVE_TYPE_COLORS).find((k) =>
    leaveTypeName.toLowerCase().includes(k.toLowerCase())
  )
  return key ? LEAVE_TYPE_COLORS[key].bar : DEFAULT_BAR_COLOR
}

function ApprovalProgress({ request }: { request: LeaveRequest }) {
  const total = request.approvalTotal ?? 0
  const approved = request.approvalApproved ?? 0
  const rejected = request.approvalRejected ?? 0

  if (total === 0) return null

  return (
    <div className="mt-1.5 space-y-1">
      <div className="flex items-center gap-2 text-[10px] text-slate-500">
        <span>{approved}/{total} approved</span>
        {rejected > 0 && (
          <span className="text-red-600 font-semibold">{rejected} rejected</span>
        )}
      </div>
      {request.approvals && request.approvals.length > 0 && (
        <div className="flex flex-wrap gap-1">
          {request.approvals.map((a) => (
            <span
              key={`${a.approverName}-${a.role}`}
              title={`${a.approverName} (${a.role})`}
              className={`inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-medium ${
                a.status === "approved"
                  ? "bg-emerald-100 text-emerald-700"
                  : a.status === "rejected"
                  ? "bg-red-100 text-red-700"
                  : "bg-amber-100 text-amber-700"
              }`}
            >
              {a.role}
            </span>
          ))}
        </div>
      )}
    </div>
  )
}

// ─── Stat Card ────────────────────────────────────────────────────────────────

function StatCard({
  label,
  value,
  valueClass = "",
}: {
  label: string
  value: number
  valueClass?: string
}) {
  return (
    <div className="rounded-lg bg-gradient-to-br from-slate-50 to-slate-100/50 px-4 py-4 border border-slate-200/50 backdrop-blur-sm">
      <p className={`text-3xl font-bold tracking-tight ${valueClass}`}>{value}</p>
      <p className="mt-1 text-xs font-medium text-slate-600">{label}</p>
    </div>
  )
}

// ─── Calendar View ────────────────────────────────────────────────────────────

function CalendarView({
  requests,
  branches,
}: {
  requests: LeaveRequest[]
  branches: Branch[]
}) {
  const today = useMemo(() => {
    const d = new Date()
    d.setHours(0, 0, 0, 0)
    return d
  }, [])

  const [year, setYear] = useState(today.getFullYear())
  const [month, setMonth] = useState(today.getMonth())
  const [tooltip, setTooltip] = useState<{
    x: number
    y: number
    req: LeaveRequest
  } | null>(null)

  const totalDays = daysInMonth(year, month)
  const dayNums = Array.from({ length: totalDays }, (_, i) => i + 1)

  const monthLabel = new Date(year, month, 1).toLocaleDateString("en-GB", {
    month: "long",
    year: "numeric",
  })

  const groupedByDept = useMemo(() => {
    const map = new Map<string, LeaveRequest[]>()
    for (const r of requests) {
      const key = r.departmentName ?? "—"
      if (!map.has(key)) map.set(key, [])
      map.get(key)!.push(r)
    }
    return map
  }, [requests])

  function shiftMonth(delta: number) {
    let nm = month + delta
    let ny = year
    if (nm < 0) { nm = 11; ny-- }
    if (nm > 11) { nm = 0; ny++ }
    setMonth(nm)
    setYear(ny)
  }

  return (
    <div className="relative">
      {/* Controls */}
      <div className="flex flex-wrap items-center justify-between gap-3 mb-4">
        <div className="flex items-center gap-2">
          <button
            onClick={() => shiftMonth(-1)}
            className="h-8 w-8 rounded-lg border border-slate-200 text-sm font-medium flex items-center justify-center hover:bg-slate-100 transition-colors"
          >
            ‹
          </button>
          <span className="text-sm font-semibold min-w-[120px] text-center text-slate-900">
            {monthLabel}
          </span>
          <button
            onClick={() => shiftMonth(1)}
            className="h-8 w-8 rounded-lg border border-slate-200 text-sm font-medium flex items-center justify-center hover:bg-slate-100 transition-colors"
          >
            ›
          </button>
          <button
            onClick={() => setYear((y) => y - 1)}
            className="h-8 w-8 rounded-lg border border-slate-200 text-xs font-medium flex items-center justify-center hover:bg-slate-100 transition-colors ml-2"
          >
            ‹‹
          </button>
          <span className="text-sm font-semibold min-w-[40px] text-center text-slate-900">{year}</span>
          <button
            onClick={() => setYear((y) => y + 1)}
            className="h-8 w-8 rounded-lg border border-slate-200 text-xs font-medium flex items-center justify-center hover:bg-slate-100 transition-colors"
          >
            ››
          </button>
        </div>
      </div>

      {/* Gantt table */}
      <div className="rounded-xl border border-slate-200 overflow-hidden shadow-sm">
        <table className="text-xs border-collapse w-full" style={{ minWidth: 900 }}>
          <thead>
            <tr className="bg-gradient-to-r from-slate-50 to-slate-100 border-b border-slate-200">
              <th className="sticky left-0 z-20 bg-gradient-to-r from-slate-50 to-slate-100 px-4 py-3 text-left font-semibold text-slate-900 border-b border-r border-slate-200 min-w-[170px]">
                Name / Department
              </th>
              <th className="px-4 py-3 text-left font-semibold text-slate-900 border-b border-r border-slate-200 min-w-[64px]">Start</th>
              <th className="px-4 py-3 text-left font-semibold text-slate-900 border-b border-r border-slate-200 min-w-[64px]">End</th>
              <th className="px-4 py-3 text-left font-semibold text-slate-900 border-b border-r border-slate-200 min-w-[36px]">Days</th>
              {dayNums.map((d) => {
                const dt = new Date(year, month, d)
                const isToday = dt.getTime() === today.getTime()
                const dow = dt.getDay()
                const isWknd = dow === 0 || dow === 6
                return (
                  <th
                    key={d}
                    className={`px-2 py-3 text-center font-semibold border-b border-r border-slate-200 min-w-[32px] transition-colors ${
                      isToday
                        ? "bg-blue-50 text-blue-600 font-bold"
                        : isWknd
                        ? "bg-slate-50 text-slate-400"
                        : "text-slate-700"
                    }`}
                  >
                    {d}
                  </th>
                )
              })}
            </tr>
          </thead>
          <tbody>
            {[...groupedByDept.entries()].map(([dept, deptReqs]) => {
              const emps = [...new Set(deptReqs.map((r) => r.employeeName))]
              const deptStarts = deptReqs.map((r) => parseDate(r.startDate)).sort((a, b) => +a - +b)
              const deptEnds = deptReqs.map((r) => parseDate(r.endDate)).sort((a, b) => +b - +a)
              const deptTotalDays = deptReqs.reduce((s, r) => s + r.duration, 0)

              return [
                <tr key={`dept-${dept}`} className="bg-slate-100/40 border-b border-slate-200 hover:bg-slate-100/60 transition-colors">
                  <td className="sticky left-0 z-10 bg-slate-100/40 px-4 py-2 font-bold uppercase tracking-wide text-[11px] text-slate-700 border-b border-r border-slate-200">
                    {dept}
                  </td>
                  <td className="px-4 py-2 text-slate-600 border-b border-r border-slate-200 text-xs">
                    {deptStarts.length ? fmtShort(deptStarts[0]) : "—"}
                  </td>
                  <td className="px-4 py-2 text-slate-600 border-b border-r border-slate-200 text-xs">
                    {deptEnds.length ? fmtShort(deptEnds[0]) : "—"}
                  </td>
                  <td className="px-4 py-2 font-bold text-slate-900 border-b border-r border-slate-200">{deptTotalDays}</td>
                  {dayNums.map((d) => {
                    const dt = new Date(year, month, d)
                    const hit = deptReqs.some((r) => {
                      const s = parseDate(r.startDate)
                      const e = parseDate(r.endDate)
                      return dt >= s && dt <= e
                    })
                    return (
                      <td
                        key={d}
                        className="border-b border-r border-slate-200 p-0 transition-colors"
                        style={{
                          background: hit ? "rgba(59, 130, 246, 0.08)" : undefined,
                          height: 32,
                        }}
                      />
                    )
                  })}
                </tr>,

                ...emps.map((emp) => {
                  const empReqs = deptReqs.filter((r) => r.employeeName === emp)
                  const empStarts = empReqs.map((r) => parseDate(r.startDate)).sort((a, b) => +a - +b)
                  const empEnds = empReqs.map((r) => parseDate(r.endDate)).sort((a, b) => +b - +a)
                  const empTotalDays = empReqs.reduce((s, r) => s + r.duration, 0)
                  const av = avatarColor(emp)
                  const onLeave = empReqs.some(isOnLeaveToday)

                  return (
                    <tr key={`${dept}-${emp}`} className="border-b border-slate-200 hover:bg-slate-50/60 transition-colors">
                      <td className="sticky left-0 z-10 bg-white px-4 py-3 border-b border-r border-slate-200">
                        <div className="flex items-center gap-3">
                          <div
                            className={`flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-[10px] font-bold ${av.bg} ${av.text} shadow-sm`}
                          >
                            {getInitials(emp)}
                          </div>
                          <div className="min-w-0">
                            <p className="truncate font-semibold leading-none text-[13px] text-slate-900 max-w-[120px]">{emp}</p>
                            {onLeave && (
                              <span className="text-[10px] font-bold text-emerald-600 mt-0.5">● on leave</span>
                            )}
                          </div>
                        </div>
                      </td>
                      <td className="px-4 py-3 text-slate-600 border-b border-r border-slate-200 whitespace-nowrap text-xs">
                        {empStarts.length ? fmtShort(empStarts[0]) : "—"}
                      </td>
                      <td className="px-4 py-3 text-slate-600 border-b border-r border-slate-200 whitespace-nowrap text-xs">
                        {empEnds.length ? fmtShort(empEnds[0]) : "—"}
                      </td>
                      <td className="px-4 py-3 font-bold text-slate-900 border-b border-r border-slate-200">{empTotalDays}</td>

                      {dayNums.map((d) => {
                        const dt = new Date(year, month, d)
                        const isToday = dt.getTime() === today.getTime()
                        const dow = dt.getDay()
                        const isWknd = dow === 0 || dow === 6

                        const startingLeave = empReqs.find((r) => {
                          const s = parseDate(r.startDate)
                          return s.getTime() === dt.getTime()
                        })

                        const coveringLeave = empReqs.find((r) => {
                          const s = parseDate(r.startDate)
                          const e = parseDate(r.endDate)
                          return dt > s && dt <= e
                        })

                        let bg = "transparent"
                        if (isToday) bg = "#EFF6FF"
                        else if (isWknd) bg = "rgba(15, 23, 42, 0.03)"

                        return (
                          <td
                            key={d}
                            className="border-b border-r border-slate-200 p-0 relative transition-colors"
                            style={{ height: 36, background: bg }}
                          >
                            {startingLeave && (() => {
                              const s = parseDate(startingLeave.startDate)
                              const e = parseDate(startingLeave.endDate)
                              const endDay = Math.min(e.getDate(), totalDays)
                              const endInMonth =
                                e.getFullYear() === year && e.getMonth() === month
                              const spanDays = endInMonth ? endDay - d + 1 : totalDays - d + 1
                              const color = getBarColor(startingLeave.leaveTypeName)
                              const showLabel = spanDays >= 3

                              return (
                                <div
                                  className="absolute top-1.5 z-10 flex items-center overflow-hidden rounded-md cursor-pointer hover:shadow-md transition-shadow"
                                  style={{
                                    left: 2,
                                    height: 24,
                                    width: `calc(${spanDays * 100}% - 4px)`,
                                    background: color,
                                    color: "#fff",
                                    fontSize: 11,
                                    fontWeight: 600,
                                    paddingLeft: 6,
                                    whiteSpace: "nowrap",
                                  }}
                                  onMouseEnter={(ev) =>
                                    setTooltip({ x: ev.clientX, y: ev.clientY, req: startingLeave })
                                  }
                                  onMouseLeave={() => setTooltip(null)}
                                >
                                  {showLabel ? `${startingLeave.employeeName} (${startingLeave.leaveTypeName})` : ""}
                                </div>
                              )
                            })()}
                          </td>
                        )
                      })}
                    </tr>
                  )
                }),
              ]
            })}
          </tbody>
        </table>
      </div>

      {/* Tooltip */}
      {tooltip && (
        <div
          className="fixed z-50 pointer-events-none rounded-lg border border-slate-200 bg-white px-4 py-3 text-xs shadow-lg backdrop-blur-sm"
          style={{ left: tooltip.x + 12, top: tooltip.y - 10 }}
        >
          <p className="font-bold text-sm mb-2 text-slate-900">{tooltip.req.employeeName}</p>
          <p className="text-slate-600 mb-1">Type: <span className="font-semibold text-slate-900">{tooltip.req.leaveTypeName}</span></p>
          <p className="text-slate-600 mb-1">
            {fmtShort(parseDate(tooltip.req.startDate))} →{" "}
            {fmtShort(parseDate(tooltip.req.endDate))}
          </p>
          <p className="text-slate-600 mb-2">
            <span className="font-semibold text-slate-900">{tooltip.req.duration}</span> day{tooltip.req.duration !== 1 ? "s" : ""}
          </p>
          <span
            className={`inline-flex items-center rounded-full px-3 py-1 text-[10px] font-bold border ${STATUS_COLORS[tooltip.req.status]}`}
          >
            {tooltip.req.status.charAt(0).toUpperCase() + tooltip.req.status.slice(1)}
          </span>
        </div>
      )}
    </div>
  )
}

// ─── Main Component ───────────────────────────────────────────────────────────

export default function LeaveRequestList({
  requests,
  branches = [],
  canProcessLeave = false,
}: LeaveRequestListProps) {
  const router = useRouter()

  const [view, setView] = useState<"list" | "calendar">("list")
  const [branchFilter, setBranchFilter] = useState("")
  const [statusFilter, setStatusFilter] = useState("")
  const [search, setSearch] = useState("")
  const [loading, setLoading] = useState<string | null>(null)
  const [dialogOpen, setDialogOpen] = useState(false)
  const [dialogAction, setDialogAction] = useState<"approve" | "reject" | null>(null)
  const [selectedRequest, setSelectedRequest] = useState<LeaveRequest | null>(null)
  const [reason, setReason] = useState("")
  const [error, setError] = useState("")

  const branchOptions = useMemo(
    () => [
      { value: "", label: "All Companies" },
      ...branches.map((b) => ({ value: b.name, label: b.name })),
    ],
    [branches]
  )

  const filtered = useMemo(() => {
    const q = search.toLowerCase()
    return requests.filter((r) => {
      if (branchFilter && r.branchName !== branchFilter) return false
      if (statusFilter && r.status !== statusFilter) return false
      if (
        q &&
        !r.employeeName.toLowerCase().includes(q) &&
        !r.departmentName?.toLowerCase().includes(q) &&
        !r.leaveTypeName.toLowerCase().includes(q)
      )
        return false
      return true
    })
  }, [requests, branchFilter, statusFilter, search])

  const stats = useMemo(() => {
    const pending = requests.filter((r) => r.status === "pending").length
    const onLeave = requests.filter(isOnLeaveToday).length
    const approvedDays = requests
      .filter((r) => r.status === "approved")
      .reduce((sum, r) => sum + r.duration, 0)
    return { total: requests.length, pending, onLeave, approvedDays }
  }, [requests])

  const filteredDays = useMemo(
    () => filtered.reduce((sum, r) => sum + r.duration, 0),
    [filtered]
  )

  const hasFilters = !!(branchFilter || statusFilter || search)

  function openDialog(request: LeaveRequest, action: "approve" | "reject") {
    setSelectedRequest(request)
    setDialogAction(action)
    setReason("")
    setError("")
    setDialogOpen(true)
  }

  async function handleAction() {
    if (!selectedRequest || !dialogAction) return
    setLoading(selectedRequest.id)
    setError("")
    try {
      const res = await fetch(`/api/leave-requests/${selectedRequest.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: dialogAction,
          reason: dialogAction === "reject" ? reason : undefined,
        }),
      })
      if (!res.ok) {
        const data = await res.json().catch(() => null)
        throw new Error(data?.error || `Failed to ${dialogAction} request`)
      }
      setDialogOpen(false)
      router.refresh()
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to process request")
    } finally {
      setLoading(null)
    }
  }

  return (
    <>
      {/* Stats row */}
      <div className="grid grid-cols-2 gap-3 sm:grid-cols-4 mb-6">
        <StatCard label="Total requests" value={stats.total} />
        <StatCard label="Pending approval" value={stats.pending} valueClass="text-amber-600" />
        <StatCard label="On leave today" value={stats.onLeave} valueClass="text-emerald-600" />
        <StatCard label="Approved days" value={stats.approvedDays} />
      </div>

      <div className="space-y-4">
        {/* ── Tab Bar — matches LeaveTabView style exactly ── */}
        <div className="inline-flex items-center rounded-lg border border-border bg-muted p-1 gap-1">
          <button
            onClick={() => setView("list")}
            className={`inline-flex items-center gap-2 rounded-md px-4 py-2 text-sm font-medium transition-all duration-150 ${
              view === "list"
                ? "bg-background text-foreground shadow-sm"
                : "text-muted-foreground hover:text-foreground"
            }`}
          >
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <line x1="8" y1="6" x2="21" y2="6" /><line x1="8" y1="12" x2="21" y2="12" /><line x1="8" y1="18" x2="21" y2="18" />
              <line x1="3" y1="6" x2="3.01" y2="6" /><line x1="3" y1="12" x2="3.01" y2="12" /><line x1="3" y1="18" x2="3.01" y2="18" />
            </svg>
            List
          </button>
          <button
            onClick={() => setView("calendar")}
            className={`inline-flex items-center gap-2 rounded-md px-4 py-2 text-sm font-medium transition-all duration-150 ${
              view === "calendar"
                ? "bg-background text-foreground shadow-sm"
                : "text-muted-foreground hover:text-foreground"
            }`}
          >
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <rect x="3" y="4" width="18" height="18" rx="2" ry="2" /><line x1="16" y1="2" x2="16" y2="6" /><line x1="8" y1="2" x2="8" y2="6" /><line x1="3" y1="10" x2="21" y2="10" />
            </svg>
            Timeline
          </button>
        </div>

        {/* ── Timeline View ── */}
        {view === "calendar" && (
          <CalendarView requests={requests} branches={branches} />
        )}

        {/* ── List View ── */}
        {view === "list" && (
          <Card className="border-slate-200 shadow-sm">
            {/* Filter bar */}
            <div className="flex flex-wrap items-center gap-3 px-6 py-4 border-b border-slate-200 bg-gradient-to-r from-slate-50 to-white">
              <span className="text-xs font-bold uppercase tracking-widest text-slate-600 mr-2">
                Filters
              </span>

              <div className="w-44">
                <Dropdown
                  placeholder="All Companies"
                  searchPlaceholder="Search branches…"
                  options={branchOptions}
                  value={branchFilter}
                  onChange={setBranchFilter}
                />
              </div>

              <div className="w-36">
                <Dropdown
                  placeholder="All statuses"
                  searchPlaceholder="Search status…"
                  options={STATUS_OPTIONS}
                  value={statusFilter}
                  onChange={setStatusFilter}
                />
              </div>

              <Input
                className="h-9 w-48 text-sm border-slate-200"
                placeholder="Search employee / dept…"
                value={search}
                onChange={(e) => setSearch(e.target.value)}
              />

              {hasFilters && (
                <Button
                  variant="ghost"
                  size="sm"
                  className="h-9 text-xs text-slate-600 hover:text-slate-900 hover:bg-slate-100"
                  onClick={() => {
                    setBranchFilter("")
                    setStatusFilter("")
                    setSearch("")
                  }}
                >
                  Clear filters
                </Button>
              )}
            </div>

            <CardContent className="p-0">
              {filtered.length === 0 ? (
                <div className="py-16 text-center text-sm text-slate-500">
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="32"
                    height="32"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="1.5"
                    className="mx-auto mb-3 text-slate-300"
                  >
                    <path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z" />
                    <polyline points="17 21 17 13 7 13 7 21" />
                    <polyline points="7 3 7 8 15 8" />
                  </svg>
                  <p className="font-medium">No leave requests match your filters</p>
                </div>
              ) : (
                <div className="overflow-x-auto">
                  <table className="w-full text-sm">
                    <thead className="border-b bg-gradient-to-r from-slate-50 to-white">
                      <tr>
                        <th className="px-6 py-4 text-left font-bold text-slate-900 text-xs uppercase tracking-wider">Employee</th>
                        <th className="px-6 py-4 text-left font-bold text-slate-900 text-xs uppercase tracking-wider">Company</th>
                        <th className="px-6 py-4 text-left font-bold text-slate-900 text-xs uppercase tracking-wider">Department</th>
                        <th className="px-6 py-4 text-left font-bold text-slate-900 text-xs uppercase tracking-wider">Leave type</th>
                        <th className="px-6 py-4 text-left font-bold text-slate-900 text-xs uppercase tracking-wider">Dates</th>
                        <th className="px-6 py-4 text-left font-bold text-slate-900 text-xs uppercase tracking-wider">Days</th>
                        <th className="px-6 py-4 text-left font-bold text-slate-900 text-xs uppercase tracking-wider">Status</th>
                        <th className="px-6 py-4 text-left font-bold text-slate-900 text-xs uppercase tracking-wider">Requested on</th>
                        <th className="px-6 py-4 text-left font-bold text-slate-900 text-xs uppercase tracking-wider">Actions</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-200">
                      {filtered.map((request) => {
                        const av = avatarColor(request.employeeName)
                        const todayLeave = isOnLeaveToday(request)
                        return (
                          <tr key={request.id} className="hover:bg-blue-50/30 transition-colors">
                            <td className="px-6 py-4">
                              <div className="flex items-center gap-3">
                                <div
                                  className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-xs font-bold ${av.bg} ${av.text} shadow-sm`}
                                >
                                  {getInitials(request.employeeName)}
                                </div>
                                <div className="min-w-0">
                                  <p className="truncate font-semibold leading-none text-slate-900">
                                    {request.employeeName}
                                  </p>
                                  {todayLeave && (
                                    <span className="text-xs font-bold text-emerald-600 mt-1">● on leave now</span>
                                  )}
                                </div>
                              </div>
                            </td>

                            <td className="px-6 py-4">
                              {request.branchName ? (
                                <span className="inline-flex items-center rounded-full bg-blue-100 px-3 py-1 text-xs font-bold text-blue-700">
                                  {request.branchName}
                                </span>
                              ) : (
                                <span className="text-slate-400">—</span>
                              )}
                            </td>

                            <td className="px-6 py-4 text-slate-600 text-sm">
                              {request.departmentName ?? "—"}
                            </td>

                            <td className="px-6 py-4">
                              <span className="flex items-center gap-2">
                                <span
                                  className="inline-block w-2.5 h-2.5 rounded shrink-0"
                                  style={{ background: getBarColor(request.leaveTypeName) }}
                                />
                                <span className="font-medium text-slate-900">{request.leaveTypeName}</span>
                              </span>
                            </td>

                            <td className="px-6 py-4 whitespace-nowrap text-xs text-slate-600">
                              {fmtShort(parseDate(request.startDate))} →{" "}
                              {fmtShort(parseDate(request.endDate))}
                            </td>

                            <td className="px-6 py-4">
                              <span className="font-bold text-slate-900">{request.duration}</span>
                              <span className="text-slate-400"> d</span>
                            </td>

                            <td className="px-6 py-4">
                              <Badge
                                variant="outline"
                                className={`${STATUS_COLORS[request.status]} border rounded-full font-bold text-xs`}
                              >
                                {request.status.charAt(0).toUpperCase() + request.status.slice(1)}
                              </Badge>
                              {request.status === "pending" && (
                                <ApprovalProgress request={request} />
                              )}
                            </td>

                            <td className="px-6 py-4 text-xs text-slate-600 whitespace-nowrap">
                              {parseDate(request.createdAt).toLocaleDateString("en-GB", {
                                day: "2-digit",
                                month: "short",
                                year: "numeric",
                              })}
                            </td>

                            <td className="px-6 py-4">
                              {canProcessLeave &&
                                request.status === "pending" &&
                                request.myApprovalStatus === "pending" && (
                                <div className="flex gap-2">
                                  <Button
                                    size="sm"
                                    className="h-8 bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-bold shadow-sm rounded-lg"
                                    onClick={() => openDialog(request, "approve")}
                                    disabled={loading === request.id}
                                  >
                                    Approve
                                  </Button>
                                  <Button
                                    size="sm"
                                    variant="outline"
                                    className="h-8 border-red-300 text-red-600 hover:bg-red-50 text-xs font-bold"
                                    onClick={() => openDialog(request, "reject")}
                                    disabled={loading === request.id}
                                  >
                                    Reject
                                  </Button>
                                </div>
                              )}
                              {canProcessLeave &&
                                request.status === "pending" &&
                                request.myApprovalStatus === "approved" && (
                                <span className="text-xs font-semibold text-emerald-600">
                                  You approved
                                </span>
                              )}
                              {canProcessLeave &&
                                request.status === "pending" &&
                                request.myApprovalStatus === "rejected" && (
                                <span className="text-xs font-semibold text-red-600">
                                  You rejected
                                </span>
                              )}
                            </td>
                          </tr>
                        )
                      })}
                    </tbody>
                  </table>
                </div>
              )}

              <div className="flex items-center justify-between border-t border-slate-200 px-6 py-3 bg-gradient-to-r from-slate-50 to-white text-xs text-slate-600 font-medium">
                <span>
                  {filtered.length} request{filtered.length !== 1 ? "s" : ""}
                  {hasFilters && ` (filtered from ${requests.length})`}
                </span>
                <span className="text-slate-900 font-bold">{filteredDays} total days</span>
              </div>
            </CardContent>
          </Card>
        )}
      </div>

      {/* Approve / Reject dialog */}
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="border-slate-200 shadow-lg">
          <DialogHeader>
            <DialogTitle className="text-lg font-bold text-slate-900">
              {dialogAction === "approve" ? "Approve leave request" : "Reject leave request"}
            </DialogTitle>
            <DialogDescription className="text-slate-600">
              {selectedRequest && (
                <>
                  <span className="font-semibold text-slate-900">{selectedRequest.employeeName}</span>{" "}
                  — {selectedRequest.leaveTypeName} ({selectedRequest.duration} days)
                </>
              )}
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 py-4">
            {dialogAction === "reject" && (
              <div className="space-y-2">
                <Label htmlFor="reason" className="text-sm font-bold text-slate-900">
                  Rejection reason
                </Label>
                <Input
                  id="reason"
                  placeholder="Enter reason for rejection"
                  value={reason}
                  onChange={(e) => setReason(e.target.value)}
                  className="border-slate-200"
                />
              </div>
            )}
            {dialogAction === "approve" && (
              <p className="text-sm text-slate-600">
                Your approval will be recorded. The request is fully approved only after
                all assigned approvers have approved.
              </p>
            )}
            {error && <p className="text-sm text-red-600 font-medium">{error}</p>}
          </div>

          <DialogFooter className="gap-2">
            <Button variant="outline" onClick={() => setDialogOpen(false)} className="border-slate-200">
              Cancel
            </Button>
            <Button
              onClick={handleAction}
              disabled={
                loading === selectedRequest?.id ||
                (dialogAction === "reject" && !reason.trim())
              }
              className={
                dialogAction === "approve"
                  ? "bg-emerald-600 hover:bg-emerald-700 text-white font-bold"
                  : "bg-red-600 hover:bg-red-700 text-white font-bold"
              }
            >
              {dialogAction === "approve" ? "Approve" : "Reject"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  )
}