"use client"

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

import { workShiftsApi } from "@/lib/api/hrm-masters"
import { errorMessage } from "@/lib/error-map"
import { cn } from "@/lib/utils"
import { PaginationMeta } from "@/types/common"
import { WorkShift } from "@/types/hrm"

import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Checkbox } from "@/components/ui/checkbox"
import { Field, FieldError, 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 DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]

export default function WorkShiftsPage() {
  const [items, setItems] = useState<WorkShift[] | 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 [code, setCode] = useState("")
  const [name, setName] = useState("")
  const [startTime, setStartTime] = useState("08:00")
  const [endTime, setEndTime] = useState("17:00")
  const [isOvernight, setIsOvernight] = useState(false)
  const [graceMinutes, setGraceMinutes] = useState(15)
  const [breakMinutes, setBreakMinutes] = useState(60)
  const [standardWorkingMinutes, setStandardWorkingMinutes] = useState(480)
  const [otMultiplier, setOtMultiplier] = useState(1.5)
  const [workingDays, setWorkingDays] = useState<boolean[]>([true, true, true, true, true, false, false])
  const [errors, setErrors] = useState<Record<string, string>>({})
  const [submitting, setSubmitting] = useState(false)

  function load() {
    workShiftsApi
      .list({ page, pageSize: PAGE_SIZE })
      .then((res) => {
        setItems(res.items)
        setPagination(res.pagination)
      })
      .catch((err) => setError(errorMessage(err)))
  }

  useEffect(load, [page])

  async function handleCreate() {
    const nextErrors: Record<string, string> = {}
    if (!code.trim()) nextErrors.code = "Code is required"
    if (!name.trim()) nextErrors.name = "Name is required"
    setErrors(nextErrors)
    if (Object.keys(nextErrors).length > 0) return

    const mask = workingDays.reduce((m, on, i) => (on ? m | (1 << i) : m), 0)
    setSubmitting(true)
    try {
      await workShiftsApi.create({
        code: code.trim(),
        name: name.trim(),
        startTime: `${startTime}:00`,
        endTime: `${endTime}:00`,
        isOvernight,
        graceMinutes,
        breakMinutes,
        standardWorkingMinutes,
        otMultiplier,
        workingDaysMask: mask,
      })
      toast.success("Work shift created")
      setOpen(false)
      setCode("")
      setName("")
      load()
    } catch (err) {
      toast.error("Could not create work shift", errorMessage(err))
    } finally {
      setSubmitting(false)
    }
  }

  async function toggleStatus(item: WorkShift) {
    try {
      await workShiftsApi.updateStatus(item.workShiftId, item.status === "Active" ? "Inactive" : "Active")
      load()
    } catch (err) {
      toast.error("Could not update status", 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">Work Shifts</h1>
          <p className="text-base text-muted-foreground">The baseline Attendance computes Late/Early/OT against.</p>
        </div>
        <Dialog open={open} onOpenChange={setOpen}>
          <DialogTrigger render={<Button size="lg"><Plus className="size-5" />New Shift</Button>} />
          <DialogContent className="sm:max-w-md">
            <DialogHeader className="items-center text-center">
              <DialogTitle>New Work Shift</DialogTitle>
              <DialogDescription>Standard hours, grace period, and working days for this shift.</DialogDescription>
            </DialogHeader>
            <FieldGroup>
              <Field data-invalid={!!errors.code}>
                <FieldLabel htmlFor="w-code">Code</FieldLabel>
                <Input id="w-code" value={code} onChange={(e) => setCode(e.target.value)} aria-invalid={!!errors.code} />
                <FieldError errors={[errors.code ? { message: errors.code } : undefined]} />
              </Field>
              <Field data-invalid={!!errors.name}>
                <FieldLabel htmlFor="w-name">Name</FieldLabel>
                <Input id="w-name" value={name} onChange={(e) => setName(e.target.value)} aria-invalid={!!errors.name} />
                <FieldError errors={[errors.name ? { message: errors.name } : undefined]} />
              </Field>
              <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                <Field>
                  <FieldLabel htmlFor="w-start">Start time</FieldLabel>
                  <Input id="w-start" type="time" value={startTime} onChange={(e) => setStartTime(e.target.value)} />
                </Field>
                <Field>
                  <FieldLabel htmlFor="w-end">End time</FieldLabel>
                  <Input id="w-end" type="time" value={endTime} onChange={(e) => setEndTime(e.target.value)} />
                </Field>
              </div>
              <Field orientation="horizontal">
                <Checkbox id="w-overnight" checked={isOvernight} onCheckedChange={(v) => setIsOvernight(v === true)} />
                <FieldLabel htmlFor="w-overnight">Overnight shift (end time rolls past midnight)</FieldLabel>
              </Field>
              <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                <Field>
                  <FieldLabel htmlFor="w-grace">Grace (minutes)</FieldLabel>
                  <Input id="w-grace" type="number" min={0} value={graceMinutes} onChange={(e) => setGraceMinutes(Number(e.target.value))} />
                </Field>
                <Field>
                  <FieldLabel htmlFor="w-break">Break (minutes)</FieldLabel>
                  <Input id="w-break" type="number" min={0} value={breakMinutes} onChange={(e) => setBreakMinutes(Number(e.target.value))} />
                </Field>
                <Field>
                  <FieldLabel htmlFor="w-standard">Standard working minutes</FieldLabel>
                  <Input id="w-standard" type="number" min={1} value={standardWorkingMinutes} onChange={(e) => setStandardWorkingMinutes(Number(e.target.value))} />
                </Field>
                <Field>
                  <FieldLabel htmlFor="w-ot">OT multiplier</FieldLabel>
                  <Input id="w-ot" type="number" step="0.1" min={1} value={otMultiplier} onChange={(e) => setOtMultiplier(Number(e.target.value))} />
                </Field>
              </div>
              <Field>
                <FieldLabel>Working days</FieldLabel>
                <div className="flex flex-wrap gap-3 pt-1">
                  {DAYS.map((d, i) => (
                    <label key={d} className="flex items-center gap-1.5 text-sm">
                      <Checkbox checked={workingDays[i]} onCheckedChange={(v) => setWorkingDays((prev) => prev.map((p, idx) => (idx === i ? v === true : p)))} />
                      {d}
                    </label>
                  ))}
                </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={() => setOpen(false)} disabled={submitting}>Cancel</Button>
              <Button className="w-full sm:w-auto sm:min-w-32" onClick={handleCreate} disabled={submitting}>{submitting ? "Creating…" : "Create"}</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 && items === null && <div className="flex flex-col gap-3">{Array.from({ length: 4 }).map((_, i) => <Skeleton key={i} className="h-14 w-full" />)}</div>}
      {!error && items !== null && items.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 work shifts yet.</p></div>
      )}
      {!error && items !== null && items.length > 0 && (
        <Table className="text-base">
          <TableHeader>
            <TableRow>
              <TableHead className="h-12 px-3 text-sm">Code</TableHead>
              <TableHead className="h-12 px-3 text-sm">Name</TableHead>
              <TableHead className="h-12 px-3 text-sm">Hours</TableHead>
              <TableHead className="h-12 px-3 text-sm">Status</TableHead>
              <TableHead className="h-12 px-3 text-sm">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {items.map((w) => (
              <TableRow key={w.workShiftId}>
                <TableCell className="px-3 py-3.5 font-medium">{w.code}</TableCell>
                <TableCell className="px-3 py-3.5">{w.name}</TableCell>
                <TableCell className="px-3 py-3.5">{w.startTime.slice(0, 5)}–{w.endTime.slice(0, 5)}</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", w.status === "Active" ? "bg-success/10 text-success" : "bg-muted text-muted-foreground")}>{w.status}</Badge>
                </TableCell>
                <TableCell className="px-3 py-3.5">
                  <Button variant="ghost" size="sm" onClick={() => toggleStatus(w)}>{w.status === "Active" ? "Deactivate" : "Activate"}</Button>
                </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>
  )
}
