"use client"

import { useTranslations } from "next-intl"
import {
  FormField,
  FormItem,
  FormLabel,
  FormControl,
  FormMessage,
  FormDescription,
} from "@/shared/components/ui/form"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select"
import type { Control } from "react-hook-form"

/** AI Provider 摘要信息（与 settings 模块类型兼容） */
export type AiProviderOption = {
  id: string
  provider: string
  model: string
  isDefault: boolean
}

type AiProviderSelectorProps = {
  /** react-hook-form control */
  control: Control<Record<string, unknown>>
  /** 表单字段名 */
  name: string
  /** Provider 列表 */
  providers: AiProviderOption[]
  /** 是否加载中 */
  loading?: boolean
  /** Provider 标签映射 */
  providerLabels?: Record<string, string>
}

/**
 * AI Provider 选择器
 *
 * 可复用的表单字段组件，用于选择 AI Provider。
 * 从 exam-ai-generator.tsx 抽取，支持在任何需要 AI Provider 选择的表单中复用。
 *
 * V3：移除内嵌"管理"链接，AI 配置统一在 /admin/ai-settings 管理。
 */
export function AiProviderSelector({
  control,
  name,
  providers,
  loading = false,
  providerLabels,
}: AiProviderSelectorProps): React.ReactNode {
  const t = useTranslations("ai")

  return (
    <FormField
      control={control}
      name={name}
      render={({ field }) => (
        <FormItem>
          <FormLabel>{t("provider.label")}</FormLabel>
          <Select value={typeof field.value === "string" ? field.value : ""} onValueChange={field.onChange} disabled={loading}>
            <FormControl>
              <SelectTrigger>
                <SelectValue
                  placeholder={loading ? t("provider.loading") : t("provider.placeholder")}
                />
              </SelectTrigger>
            </FormControl>
            <SelectContent>
              {providers.map((item) => (
                <SelectItem key={item.id} value={item.id}>
                  {providerLabels?.[item.provider] ?? item.provider} · {item.model}
                  {item.isDefault ? ` (${t("provider.default")})` : ""}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <FormDescription>{t("provider.description")}</FormDescription>
          <FormMessage />
        </FormItem>
      )}
    />
  )
}
