"use client"

import { useFormContext, useWatch } from "react-hook-form"
import { useTranslations } from "next-intl"
import {
  FormField,
  FormItem,
  FormLabel,
  FormControl,
  FormMessage,
  FormDescription,
} from "@/shared/components/ui/form"
import { Input } from "@/shared/components/ui/input"
import { Label } from "@/shared/components/ui/label"
import { Switch } from "@/shared/components/ui/switch"
import { RadioGroup, RadioGroupItem } from "@/shared/components/ui/radio-group"
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/shared/components/ui/card"

import type { ExamMode } from "../types"

const EXAM_MODES: ExamMode[] = ["homework", "timed", "proctored"]

/**
 * 考试模式配置表单值约束
 * 集成到考试创建/编辑表单时，表单值需满足此接口
 */
export interface ExamModeConfigFieldValues {
  examMode: ExamMode
  durationMinutes?: number | null
  shuffleQuestions: boolean
  allowLateStart: boolean
  lateStartGraceMinutes: number
  antiCheatEnabled: boolean
}

/**
 * 考试模式配置卡片（homework / timed / proctored）。
 *
 * P1-2 修复：移除泛型与所有 as 断言。
 * 原方案通过 control: Control<ExamModeConfigFieldValues> 接收控制对象，
 * 但 Control<T> 在 react-hook-form 中为不变型（invariant），
 * Control<ExamFormValues> 无法赋值给 Control<ExamModeConfigFieldValues>。
 * 改为使用 useFormContext 从 FormProvider 读取表单上下文，
 * 避免在调用方使用 as 断言适配 Control 类型。
 *
 * 使用方需确保：
 * 1. 外层已通过 <Form {...form}> / <FormProvider {...form}> 提供上下文
 * 2. 表单值类型结构包含 ExamModeConfigFieldValues 的全部字段
 */
export function ExamModeConfig() {
  const t = useTranslations("examHomework")
  const form = useFormContext<ExamModeConfigFieldValues>()
  // useWatch 必须在条件返回之前无条件调用（Rules of Hooks）
  // form?.control 为 undefined 时 useWatch 会回退到 useFormContext
  const examMode = useWatch<ExamModeConfigFieldValues, "examMode">({
    control: form?.control,
    name: "examMode",
  })
  if (!form) return null
  const { control } = form
  const showDuration = examMode === "timed" || examMode === "proctored"
  const showProctorOptions = examMode === "proctored"

  return (
    <Card>
      <CardHeader>
        <CardTitle>{t("proctoring.mode.title")}</CardTitle>
        <CardDescription>{t("proctoring.mode.description")}</CardDescription>
      </CardHeader>
      <CardContent className="space-y-6">
        <FormField
          control={control}
          name="examMode"
          render={({ field }) => (
            <FormItem>
              <FormLabel>{t("proctoring.mode.title")}</FormLabel>
              <FormControl>
                <RadioGroup
                  value={field.value}
                  onValueChange={field.onChange}
                  className="grid gap-3 md:grid-cols-3"
                >
                  {EXAM_MODES.map((mode) => (
                    <Label
                      key={mode}
                      htmlFor={`exam-mode-${mode}`}
                      className="flex cursor-pointer items-start gap-3 rounded-md border p-3 has-[:checked]:border-primary has-[:checked]:bg-accent"
                    >
                      <RadioGroupItem
                        id={`exam-mode-${mode}`}
                        value={mode}
                        className="mt-0.5"
                      />
                      <div className="space-y-0.5">
                        <div className="text-sm font-medium">
                          {t(`proctoring.mode.${mode}`)}
                        </div>
                        <div className="text-xs text-muted-foreground">
                          {t(`proctoring.mode.${mode}Description`)}
                        </div>
                      </div>
                    </Label>
                  ))}
                </RadioGroup>
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        {showDuration && (
          <FormField
            control={control}
            name="durationMinutes"
            render={({ field }) => (
              <FormItem className="space-y-2">
                <div className="space-y-0.5">
                  <FormLabel>{t("proctoring.config.duration")}</FormLabel>
                  <FormDescription>
                    {examMode === "proctored"
                      ? t("proctoring.config.durationProctoredDescription")
                      : t("proctoring.config.durationTimedDescription")}
                  </FormDescription>
                </div>
                <FormControl>
                  <Input
                    type="number"
                    min={1}
                    value={field.value ?? ""}
                    onChange={(e) => {
                      if (e.target.value === "") {
                        field.onChange(null)
                        return
                      }
                      const n = Number(e.target.value)
                      field.onChange(Number.isFinite(n) ? n : null)
                    }}
                    onBlur={field.onBlur}
                    name={field.name}
                    ref={field.ref}
                    aria-label={t("proctoring.config.duration")}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
        )}

        {showProctorOptions && (
          <>
            <FormField
              control={control}
              name="shuffleQuestions"
              render={({ field }) => (
                <FormItem className="flex items-center justify-between rounded-md border p-3">
                  <div className="space-y-0.5">
                    <FormLabel>{t("proctoring.config.shuffleQuestions")}</FormLabel>
                    <FormDescription>{t("proctoring.config.shuffleQuestionsDescription")}</FormDescription>
                  </div>
                  <FormControl>
                    <Switch
                      checked={field.value}
                      onCheckedChange={field.onChange}
                      aria-label={t("proctoring.config.shuffleQuestions")}
                    />
                  </FormControl>
                </FormItem>
              )}
            />

            <FormField
              control={control}
              name="antiCheatEnabled"
              render={({ field }) => (
                <FormItem className="flex items-center justify-between rounded-md border p-3">
                  <div className="space-y-0.5">
                    <FormLabel>{t("proctoring.config.antiCheat")}</FormLabel>
                    <FormDescription>{t("proctoring.config.antiCheatDescription")}</FormDescription>
                  </div>
                  <FormControl>
                    <Switch
                      checked={field.value}
                      onCheckedChange={field.onChange}
                      aria-label={t("proctoring.config.antiCheat")}
                    />
                  </FormControl>
                </FormItem>
              )}
            />

            <FormField
              control={control}
              name="allowLateStart"
              render={({ field }) => (
                <FormItem className="flex items-center justify-between rounded-md border p-3">
                  <div className="space-y-0.5">
                    <FormLabel>{t("proctoring.config.allowLateStart")}</FormLabel>
                    <FormDescription>{t("proctoring.config.allowLateStartDescription")}</FormDescription>
                  </div>
                  <FormControl>
                    <Switch
                      checked={field.value}
                      onCheckedChange={field.onChange}
                      aria-label={t("proctoring.config.allowLateStart")}
                    />
                  </FormControl>
                </FormItem>
              )}
            />

            <FormField
              control={control}
              name="lateStartGraceMinutes"
              render={({ field }) => (
                <FormItem className="space-y-2">
                  <div className="space-y-0.5">
                    <FormLabel>{t("proctoring.config.lateStartGrace")}</FormLabel>
                    <FormDescription>{t("proctoring.config.lateStartGraceDescription")}</FormDescription>
                  </div>
                  <FormControl>
                    <Input
                      type="number"
                      min={0}
                      value={field.value ?? 0}
                      onChange={(e) => {
                        const n = Number(e.target.value)
                        field.onChange(Number.isFinite(n) ? n : 0)
                      }}
                      onBlur={field.onBlur}
                      name={field.name}
                      ref={field.ref}
                      aria-label={t("proctoring.config.lateStartGrace")}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </>
        )}
      </CardContent>
    </Card>
  )
}
