"use client"

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

import { Button } from "@/shared/components/ui/button"
import { Input } from "@/shared/components/ui/input"
import { Label } from "@/shared/components/ui/label"
import { Textarea } from "@/shared/components/ui/textarea"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select"
import { createLeaveRequestAction } from "../actions"
import type { ActionState } from "@/shared/types/action-state"

/** 子女选项（家长视角下选择为哪个孩子请假；学生视角可省略本字段） */
export interface ChildOption {
  id: string
  name: string
  classId: string
  className: string
}

function SubmitButton() {
  const { pending } = useFormStatus()
  const t = useTranslations("leave")
  return (
    <Button type="submit" disabled={pending}>
      {pending ? (
        <>
          <Loader2 className="mr-2 h-4 w-4 animate-spin" />
          {t("form.submitting")}
        </>
      ) : (
        <>
          <Send className="mr-2 h-4 w-4" />
          {t("form.submit")}
        </>
      )}
    </Button>
  )
}

/**
 * 请假申请表单。
 *
 * - 家长视角：childOptions 数组非空，下拉选择子女
 * - 学生视角：childOptions 省略，使用传入的 defaultStudentId/classId
 *
 * 通过 useActionState 调用 createLeaveRequestAction，提交成功后 toast 提示并调用 onSuccess。
 *
 * 注意：prop 名为 `childOptions` 而非 `children`，避免与 React 特殊 children prop 冲突
 * 触发 ESLint `react/no-children-prop` 规则。
 */
export function LeaveRequestForm({
  childOptions,
  defaultStudentId,
  defaultClassId,
  onSuccess,
}: {
  childOptions?: ChildOption[]
  defaultStudentId?: string
  defaultClassId?: string
  onSuccess?: () => void
}) {
  const t = useTranslations("leave")
  const [state, formAction] = useActionState<ActionState<string>, FormData>(
    createLeaveRequestAction,
    { success: false },
  )
  const formRef = useRef<HTMLFormElement>(null)

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

  const isParentMode = (childOptions?.length ?? 0) > 0

  return (
    <form ref={formRef} action={formAction} className="space-y-4">
      {isParentMode && (
        <div className="space-y-2">
          <Label htmlFor="studentId">{t("form.student")}</Label>
          <Select name="studentId" defaultValue={defaultStudentId ?? childOptions?.[0]?.id}>
            <SelectTrigger id="studentId">
              <SelectValue placeholder={t("form.studentPlaceholder")} />
            </SelectTrigger>
            <SelectContent>
              {childOptions?.map((c) => (
                <SelectItem key={c.id} value={c.id}>
                  {c.name}（{c.className}）
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          {state.errors?.studentId?.[0] && (
            <p className="text-sm text-destructive">{state.errors.studentId[0]}</p>
          )}
        </div>
      )}
      {!isParentMode && defaultStudentId && defaultClassId && (
        <>
          <input type="hidden" name="studentId" value={defaultStudentId} />
          <input type="hidden" name="classId" value={defaultClassId} />
        </>
      )}
      {/* 家长模式下 classId 通过子组件映射动态写入；学生模式已 hidden 写入 */}
      {isParentMode && (
        <input
          type="hidden"
          name="classId"
          value={childOptions?.find((c) => c.id === defaultStudentId)?.classId ?? childOptions?.[0]?.classId}
        />
      )}

      <div className="grid gap-4 md:grid-cols-2">
        <div className="space-y-2">
          <Label htmlFor="leaveType">{t("form.leaveType")}</Label>
          <Select name="leaveType" defaultValue="sick">
            <SelectTrigger id="leaveType">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="sick">{t("types.sick")}</SelectItem>
              <SelectItem value="personal">{t("types.personal")}</SelectItem>
              <SelectItem value="family">{t("types.family")}</SelectItem>
              <SelectItem value="other">{t("types.other")}</SelectItem>
            </SelectContent>
          </Select>
          {state.errors?.leaveType?.[0] && (
            <p className="text-sm text-destructive">{state.errors.leaveType[0]}</p>
          )}
        </div>
        <div className="space-y-2">
          <Label htmlFor="dateRange">{t("form.dateRange")}</Label>
          <div className="flex items-center gap-2">
            <Input
              id="startDate"
              name="startDate"
              type="date"
              required
              className="flex-1"
            />
            <span className="text-muted-foreground">—</span>
            <Input
              id="endDate"
              name="endDate"
              type="date"
              required
              className="flex-1"
            />
          </div>
          {state.errors?.startDate?.[0] && (
            <p className="text-sm text-destructive">{state.errors.startDate[0]}</p>
          )}
          {state.errors?.endDate?.[0] && (
            <p className="text-sm text-destructive">{state.errors.endDate[0]}</p>
          )}
        </div>
      </div>

      <div className="space-y-2">
        <Label htmlFor="reason">{t("form.reason")}</Label>
        <Textarea
          id="reason"
          name="reason"
          required
          rows={4}
          maxLength={500}
          placeholder={t("form.reasonPlaceholder")}
        />
        {state.errors?.reason?.[0] && (
          <p className="text-sm text-destructive">{state.errors.reason[0]}</p>
        )}
      </div>

      <div className="flex justify-end gap-2">
        <SubmitButton />
      </div>
    </form>
  )
}
