"use client"

import { useActionState, useEffect, useRef, useState } from "react"
import { useFormStatus } from "react-dom"
import { useTranslations } from "next-intl"
import { Check, Loader2, X } from "lucide-react"
import { toast } from "sonner"

import { Button } from "@/shared/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/shared/components/ui/dialog"
import { Label } from "@/shared/components/ui/label"
import { Textarea } from "@/shared/components/ui/textarea"
import { reviewLeaveRequestAction } from "../actions"
import type { ActionState } from "@/shared/types/action-state"
import type { LeaveRequestListItem } from "../types"

function ReviewSubmitButton({ label }: { label: string }) {
  const { pending } = useFormStatus()
  return (
    <Button type="submit" disabled={pending}>
      {pending ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Check className="mr-2 h-4 w-4" />}
      {label}
    </Button>
  )
}

/**
 * 请假审批对话框。
 *
 * 教师在审批列表中点击「批准」/「拒绝」按钮打开此对话框。
 * 拒绝时审批意见必填；批准时可选。
 * 提交成功后关闭对话框并调用 onReviewed 回调（父组件刷新列表）。
 */
export function LeaveReviewDialog({
  leaveRequest,
  open,
  onOpenChange,
  onReviewed,
}: {
  leaveRequest: LeaveRequestListItem | null
  open: boolean
  onOpenChange: (open: boolean) => void
  onReviewed?: () => void
}) {
  const t = useTranslations("leave")
  const [decision, setDecision] = useState<"approved" | "rejected">("approved")
  const formRef = useRef<HTMLFormElement>(null)

  const reviewActionWithId = async (
    _prevState: ActionState<string> | null,
    formData: FormData,
  ): Promise<ActionState<string>> => {
    if (!leaveRequest) {
      return { success: false, message: t("errors.notFound") }
    }
    formData.set("status", decision)
    return reviewLeaveRequestAction(leaveRequest.id, _prevState, formData)
  }

  const [state, formAction] = useActionState<ActionState<string>, FormData>(
    reviewActionWithId,
    { success: false },
  )

  useEffect(() => {
    if (state.success) {
      toast.success(state.message)
      onOpenChange(false)
      formRef.current?.reset()
      onReviewed?.()
    } else if (state.message) {
      toast.error(state.message)
    }
  }, [state, onOpenChange, onReviewed])

  if (!leaveRequest) return null

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[480px]">
        <DialogHeader>
          <DialogTitle>{t("review.title")}</DialogTitle>
          <DialogDescription>
            {t("review.description", {
              name: leaveRequest.studentName,
              className: leaveRequest.className,
              dateRange: `${leaveRequest.startDate} ~ ${leaveRequest.endDate}`,
            })}
          </DialogDescription>
        </DialogHeader>

        <div className="rounded-md bg-muted/40 p-3 text-sm space-y-1">
          <div>
            <span className="text-muted-foreground">{t("list.reason")}：</span>
            <span>{leaveRequest.reason}</span>
          </div>
          <div>
            <span className="text-muted-foreground">{t("form.leaveType")}：</span>
            <span>{t("types." + leaveRequest.leaveType)}</span>
          </div>
        </div>

        <form ref={formRef} action={formAction} className="space-y-4">
          <div className="flex gap-2">
            <Button
              type="button"
              variant={decision === "approved" ? "default" : "outline"}
              size="sm"
              onClick={() => setDecision("approved")}
              className="flex-1"
            >
              <Check className="mr-2 h-4 w-4" />
              {t("review.approve")}
            </Button>
            <Button
              type="button"
              variant={decision === "rejected" ? "destructive" : "outline"}
              size="sm"
              onClick={() => setDecision("rejected")}
              className="flex-1"
            >
              <X className="mr-2 h-4 w-4" />
              {t("review.reject")}
            </Button>
          </div>

          <div className="space-y-2">
            <Label htmlFor="reviewComment">
              {t("review.commentLabel")}
              {decision === "rejected" && <span className="ml-1 text-destructive">*</span>}
            </Label>
            <Textarea
              id="reviewComment"
              name="reviewComment"
              rows={3}
              maxLength={500}
              placeholder={t("review.commentPlaceholder")}
              required={decision === "rejected"}
            />
          </div>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
              {t("review.cancel")}
            </Button>
            <ReviewSubmitButton
              label={decision === "approved" ? t("review.approve") : t("review.reject")}
            />
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  )
}
