// LeaveRequestForm：请假申请表单
// 依据：02-architecture-design.md §15 组件设计、project_rules §3.8 输入验证
// - react-hook-form + zod 校验
// - 字段：子女 / 请假类型 / 起止日期 / 原因
// - 提交成功后回调 onSuccess（用于刷新列表）并重置表单

"use client";

import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useCreateLeaveRequest } from "@/hooks/useCreateLeaveRequest";
import { useMyChildren } from "@/hooks/useMyChildren";
import {
  leaveRequestSchema,
  LEAVE_TYPES,
  type LeaveRequestFormValues,
} from "@/lib/schemas/leave-request";
import type { LeaveRequestInput, LeaveType } from "@/types";
import { cn } from "@/lib/utils";

const TYPE_LABELS: Record<LeaveType, string> = {
  sick: "病假",
  personal: "事假",
  family: "家庭假",
  other: "其他",
};

interface LeaveRequestFormProps {
  /** 提交成功后回调（通常用于刷新请假列表） */
  onSuccess?: () => void;
}

export function LeaveRequestForm({ onSuccess }: LeaveRequestFormProps) {
  const { children } = useMyChildren();
  const { createLeave, loading, error } = useCreateLeaveRequest();

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<LeaveRequestFormValues>({
    resolver: zodResolver(leaveRequestSchema),
    defaultValues: {
      childId: children[0]?.id ?? "",
      type: "sick",
      startDate: "",
      endDate: "",
      reason: "",
    },
  });

  const onSubmit = async (values: LeaveRequestFormValues): Promise<void> => {
    const input: LeaveRequestInput = {
      childId: values.childId,
      type: values.type,
      startDate: values.startDate,
      endDate: values.endDate,
      reason: values.reason,
    };
    const result = await createLeave(input);
    if (result.success) {
      reset();
      onSuccess?.();
    }
  };

  return (
    <form
      onSubmit={handleSubmit(onSubmit)}
      className="space-y-4 rounded border border-rule bg-paper-elevated p-4"
      aria-label="请假申请表单"
    >
      <h2 className="font-serif text-base">提交请假申请</h2>

      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
        {/* 子女选择 */}
        <div className="space-y-1">
          <label
            htmlFor="leave-child"
            className="text-xs text-ink-muted"
          >
            子女
          </label>
          <select
            id="leave-child"
            {...register("childId")}
            className="w-full rounded border border-rule bg-paper px-3 py-2 text-sm focus:outline-none"
          >
            {children.map((child) => (
              <option key={child.id} value={child.id}>
                {child.name}
              </option>
            ))}
          </select>
          {errors.childId && (
            <p className="text-xs text-danger" role="alert">
              {errors.childId.message}
            </p>
          )}
        </div>

        {/* 请假类型 */}
        <div className="space-y-1">
          <label
            htmlFor="leave-type"
            className="text-xs text-ink-muted"
          >
            请假类型
          </label>
          <select
            id="leave-type"
            {...register("type")}
            className="w-full rounded border border-rule bg-paper px-3 py-2 text-sm focus:outline-none"
          >
            {LEAVE_TYPES.map((t) => (
              <option key={t} value={t}>
                {TYPE_LABELS[t]}
              </option>
            ))}
          </select>
          {errors.type && (
            <p className="text-xs text-danger" role="alert">
              {errors.type.message}
            </p>
          )}
        </div>

        {/* 开始日期 */}
        <div className="space-y-1">
          <label
            htmlFor="leave-start"
            className="text-xs text-ink-muted"
          >
            开始日期
          </label>
          <input
            id="leave-start"
            type="date"
            {...register("startDate")}
            className="w-full rounded border border-rule bg-paper px-3 py-2 text-sm focus:outline-none"
          />
          {errors.startDate && (
            <p className="text-xs text-danger" role="alert">
              {errors.startDate.message}
            </p>
          )}
        </div>

        {/* 结束日期 */}
        <div className="space-y-1">
          <label
            htmlFor="leave-end"
            className="text-xs text-ink-muted"
          >
            结束日期
          </label>
          <input
            id="leave-end"
            type="date"
            {...register("endDate")}
            className="w-full rounded border border-rule bg-paper px-3 py-2 text-sm focus:outline-none"
          />
          {errors.endDate && (
            <p className="text-xs text-danger" role="alert">
              {errors.endDate.message}
            </p>
          )}
        </div>
      </div>

      {/* 原因 */}
      <div className="space-y-1">
        <label
          htmlFor="leave-reason"
          className="text-xs text-ink-muted"
        >
          请假原因
        </label>
        <textarea
          id="leave-reason"
          rows={3}
          {...register("reason")}
          placeholder="请详细说明请假原因（至少 10 个字）"
          className="w-full rounded border border-rule bg-paper px-3 py-2 text-sm focus:outline-none"
        />
        {errors.reason && (
          <p className="text-xs text-danger" role="alert">
            {errors.reason.message}
          </p>
        )}
      </div>

      {error && (
        <p className="text-sm text-danger" role="alert">
          提交失败：{error.message}
        </p>
      )}

      <button
        type="submit"
        disabled={loading}
        className={cn(
          "rounded bg-accent px-4 py-2 text-sm font-medium text-paper transition-colors",
          loading ? "cursor-not-allowed opacity-60" : "hover:opacity-90",
        )}
      >
        {loading ? "提交中..." : "提交申请"}
      </button>
    </form>
  );
}

export default LeaveRequestForm;
