"use client"

import { useState } from "react"
import { toast } from "sonner"
import { useRouter } from "next/navigation"
import { Check, X } from "lucide-react"

import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/components/ui/table"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/shared/components/ui/dialog"
import { Textarea } from "@/shared/components/ui/textarea"
import { Label } from "@/shared/components/ui/label"
import { formatDate } from "@/shared/lib/utils"

import { approveScheduleChangeAction, rejectScheduleChangeAction } from "../actions"
import {
  SCHEDULE_CHANGE_STATUS_COLORS,
  SCHEDULE_CHANGE_STATUS_LABELS,
  type ScheduleChangeListItem,
} from "../types"

interface ScheduleChangeListProps {
  items: ScheduleChangeListItem[]
  canApprove?: boolean
}

export function ScheduleChangeList({ items, canApprove = false }: ScheduleChangeListProps) {
  const router = useRouter()
  const [approveId, setApproveId] = useState<string | null>(null)
  const [rejectId, setRejectId] = useState<string | null>(null)
  const [rejectReason, setRejectReason] = useState("")
  const [acting, setActing] = useState(false)

  const handleApprove = async () => {
    if (!approveId) return
    setActing(true)
    try {
      const res = await approveScheduleChangeAction(approveId)
      if (res.success) {
        toast.success(res.message)
        setApproveId(null)
        router.refresh()
      } else {
        toast.error(res.message || "Failed to approve")
      }
    } catch {
      toast.error("Failed to approve")
    } finally {
      setActing(false)
    }
  }

  const handleReject = async () => {
    if (!rejectId) return
    setActing(true)
    try {
      const res = await rejectScheduleChangeAction(rejectId, rejectReason || undefined)
      if (res.success) {
        toast.success(res.message)
        setRejectId(null)
        setRejectReason("")
        router.refresh()
      } else {
        toast.error(res.message || "Failed to reject")
      }
    } catch {
      toast.error("Failed to reject")
    } finally {
      setActing(false)
    }
  }

  if (items.length === 0) {
    return (
      <div className="rounded-md border bg-card p-8 text-center text-sm text-muted-foreground">
        No schedule change requests found.
      </div>
    )
  }

  return (
    <>
      <div className="rounded-md border bg-card">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Class</TableHead>
              <TableHead>Original Teacher</TableHead>
              <TableHead>Substitute</TableHead>
              <TableHead>Original Date</TableHead>
              <TableHead>New Date</TableHead>
              <TableHead>New Time</TableHead>
              <TableHead>Reason</TableHead>
              <TableHead>Status</TableHead>
              <TableHead>Requested By</TableHead>
              <TableHead>Created</TableHead>
              {canApprove && <TableHead className="w-32">Actions</TableHead>}
            </TableRow>
          </TableHeader>
          <TableBody>
            {items.map((r) => (
              <TableRow key={r.id}>
                <TableCell className="font-medium">{r.className}</TableCell>
                <TableCell>{r.originalTeacherName ?? "-"}</TableCell>
                <TableCell>{r.substituteTeacherName ?? "-"}</TableCell>
                <TableCell>{r.originalDate ?? "-"}</TableCell>
                <TableCell>{r.newDate ?? "-"}</TableCell>
                <TableCell>
                  {r.newStartTime && r.newEndTime ? `${r.newStartTime}-${r.newEndTime}` : "-"}
                </TableCell>
                <TableCell className="max-w-[200px] truncate text-muted-foreground">
                  {r.reason ?? "-"}
                </TableCell>
                <TableCell>
                  <Badge variant={SCHEDULE_CHANGE_STATUS_COLORS[r.status]}>
                    {SCHEDULE_CHANGE_STATUS_LABELS[r.status]}
                  </Badge>
                </TableCell>
                <TableCell className="text-muted-foreground">{r.requesterName}</TableCell>
                <TableCell className="text-muted-foreground">{formatDate(r.createdAt)}</TableCell>
                {canApprove && (
                  <TableCell>
                    {r.status === "pending" ? (
                      <div className="flex gap-1">
                        <Button
                          size="icon"
                          variant="ghost"
                          className="h-8 w-8 text-primary"
                          onClick={() => setApproveId(r.id)}
                          aria-label="Approve"
                        >
                          <Check className="h-4 w-4" />
                        </Button>
                        <Button
                          size="icon"
                          variant="ghost"
                          className="h-8 w-8 text-destructive"
                          onClick={() => setRejectId(r.id)}
                          aria-label="Reject"
                        >
                          <X className="h-4 w-4" />
                        </Button>
                      </div>
                    ) : (
                      <span className="text-muted-foreground text-xs">—</span>
                    )}
                  </TableCell>
                )}
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>

      <Dialog open={approveId !== null} onOpenChange={(open) => !open && setApproveId(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Approve Schedule Change</DialogTitle>
            <DialogDescription>
              Are you sure you want to approve this schedule change request?
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setApproveId(null)} disabled={acting}>
              Cancel
            </Button>
            <Button onClick={handleApprove} disabled={acting}>
              {acting ? "Approving..." : "Approve"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={rejectId !== null} onOpenChange={(open) => !open && setRejectId(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Reject Schedule Change</DialogTitle>
            <DialogDescription>
              Please provide a reason for rejecting this request (optional).
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-2 py-2">
            <Label htmlFor="rejectReason">Reason</Label>
            <Textarea
              id="rejectReason"
              value={rejectReason}
              onChange={(e) => setRejectReason(e.target.value)}
              placeholder="Reason for rejection..."
              rows={3}
            />
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setRejectId(null)} disabled={acting}>
              Cancel
            </Button>
            <Button variant="destructive" onClick={handleReject} disabled={acting}>
              {acting ? "Rejecting..." : "Reject"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  )
}
