"use client"

import type { Control, UseFormReturn } from "react-hook-form"
import { useTranslations } from "next-intl"
import {
  FormField,
  FormItem,
  FormLabel,
  FormControl,
  FormMessage,
  FormDescription,
} from "@/shared/components/ui/form"
import { Textarea } from "@/shared/components/ui/textarea"
import { Button } from "@/shared/components/ui/button"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select"
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/shared/components/ui/card"
import type { AiProviderSummary } from "@/modules/settings/actions"
import { formatDateTime } from "@/shared/lib/utils"
import type { ExamFormValues, PreviewBackgroundTask } from "./exam-form-types"
import { aiProviderLabels } from "./exam-form-types"

type ExamAiGeneratorProps = {
  form: UseFormReturn<ExamFormValues>
  control: Control<ExamFormValues>
  aiProviders: AiProviderSummary[]
  setAiProviders: (providers: AiProviderSummary[]) => void
  loadingAiProviders: boolean
  handlePreview: () => void
  handleBackgroundPreview: () => void
  previewLoading: boolean
  previewTasks: PreviewBackgroundTask[]
  handleOpenPreviewTask: (taskId: string) => void
  activePreviewTaskCount: number
  runningPreviewTaskCount: number
  queuedPreviewTaskCount: number
}

export function ExamAiGenerator({
  form: _form,
  control,
  aiProviders,
  setAiProviders: _setAiProviders,
  loadingAiProviders,
  handlePreview,
  handleBackgroundPreview,
  previewLoading,
  previewTasks,
  handleOpenPreviewTask,
  activePreviewTaskCount,
  runningPreviewTaskCount,
  queuedPreviewTaskCount,
}: ExamAiGeneratorProps) {
  const t = useTranslations("ai")
  const formatTaskTime = (value: number) => {
    if (!Number.isFinite(value)) return ""
    const date = new Date(value)
    if (Number.isNaN(date.getTime())) return ""
    return formatDateTime(date)
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>{t("exam.generationTitle")}</CardTitle>
        <CardDescription>
          {t("exam.generationDesc")}
        </CardDescription>
      </CardHeader>
      <CardContent className="grid gap-4">
        <FormField
          control={control}
          name="aiProviderId"
          render={({ field }) => (
            <FormItem>
              <FormLabel>{t("provider.label")}</FormLabel>
              <Select value={field.value} onValueChange={field.onChange} disabled={loadingAiProviders}>
                <FormControl>
                  <SelectTrigger>
                    <SelectValue placeholder={loadingAiProviders ? t("provider.loading") : t("provider.placeholder")} />
                  </SelectTrigger>
                </FormControl>
                <SelectContent>
                  {aiProviders.map((item) => (
                    <SelectItem key={item.id} value={item.id}>
                      {aiProviderLabels[item.provider] ?? item.provider} · {item.model}{item.isDefault ? ` (${t("provider.default")})` : ""}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <FormDescription>
                {t("provider.description")}
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />
        <div className="flex justify-end gap-2">
          <Button type="button" variant="outline" size="sm" onClick={handleBackgroundPreview}>
            {t("exam.queue")} ({t("exam.queueRunning")} {runningPreviewTaskCount}/3, {t("exam.queueQueued")} {queuedPreviewTaskCount})
          </Button>
          <Button type="button" variant="outline" size="sm" onClick={handlePreview} disabled={previewLoading || activePreviewTaskCount > 0}>
            {previewLoading ? t("exam.generating") : t("exam.preview")}
          </Button>
        </div>
        <FormField
          control={control}
          name="aiSourceText"
          render={({ field }) => (
            <FormItem>
              <FormLabel>{t("exam.sourceText")}</FormLabel>
              <FormControl>
                <Textarea
                  placeholder={t("exam.sourceTextPlaceholder")}
                  className="min-h-[200px]"
                  {...field}
                />
              </FormControl>
              <FormDescription>
                {t("exam.sourceTextDesc")}
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />
        {previewTasks.length > 0 ? (
          <div className="rounded-md border p-3 space-y-2">
            <div className="text-sm font-medium">{t("exam.backgroundTasks")}</div>
            <div className="space-y-2">
              {previewTasks.slice(0, 6).map((task) => (
                <div key={task.id} className="rounded-md border p-2">
                  <div className="flex items-center justify-between gap-2">
                    <div className="text-sm font-medium truncate">{task.title}</div>
                    <div className="text-xs text-muted-foreground">{formatTaskTime(task.createdAt)}</div>
                  </div>
                  <div className="mt-1 text-xs text-muted-foreground">
                    {task.status === "queued"
                      ? t("exam.taskStatus.queued")
                      : task.status === "running"
                        ? t("exam.taskStatus.running")
                        : task.status === "success"
                          ? t("exam.taskStatus.success")
                          : `${t("exam.taskStatus.failed")}：${task.message || ""}`}
                  </div>
                  {task.status === "success" && task.result ? (
                    <div className="mt-2 flex justify-end">
                      <Button type="button" variant="ghost" size="sm" onClick={() => handleOpenPreviewTask(task.id)}>
                        {t("exam.openPreview")}
                      </Button>
                    </div>
                  ) : null}
                </div>
              ))}
            </div>
          </div>
        ) : null}
      </CardContent>
    </Card>
  )
}
