"use client"

import { useTranslations } from "next-intl"
import { Plus, Trash2, GripVertical } from "lucide-react"

import { Button } from "@/shared/components/ui/button"
import { Checkbox } from "@/shared/components/ui/checkbox"
import { Input } from "@/shared/components/ui/input"
import { FormLabel } from "@/shared/components/ui/form"

export interface QuestionOptionInput {
  label: string
  value: string
  isCorrect: boolean
}

interface OptionsEditorProps {
  options: QuestionOptionInput[]
  onChange: (options: QuestionOptionInput[]) => void
  /** 单选模式：选中一个选项时自动取消其他 */
  singleChoice: boolean
}

/**
 * 选项编辑器组件。
 *
 * 从 create-question-dialog.tsx 抽取，负责选择题选项的增删改。
 * 支持单选（single_choice）和多选（multiple_choice）模式。
 */
export function OptionsEditor({ options, onChange, singleChoice }: OptionsEditorProps): React.ReactNode {
  const t = useTranslations("questions")

  const addOption = (): void => {
    const nextIndex = options.length
    const nextChar = nextIndex < 26 ? String.fromCharCode(65 + nextIndex) : String(nextIndex + 1)
    onChange([
      ...options,
      { label: `Option ${nextChar}`, value: nextChar, isCorrect: false },
    ])
  }

  const toggleCorrect = (index: number, checked: boolean): void => {
    const next = [...options]
    if (!next[index]) return

    if (singleChoice && checked) {
      for (let i = 0; i < next.length; i++) next[i].isCorrect = i === index
    } else {
      next[index].isCorrect = checked
    }
    onChange(next)
  }

  const updateLabel = (index: number, label: string): void => {
    const next = [...options]
    if (!next[index]) return
    next[index].label = label
    onChange(next)
  }

  const removeOption = (index: number): void => {
    const next = [...options]
    next.splice(index, 1)
    onChange(next)
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <FormLabel>{t("dialog.options")}</FormLabel>
        <Button type="button" variant="outline" size="sm" onClick={addOption}>
          <Plus className="mr-2 h-3 w-3" /> {t("dialog.addOption")}
        </Button>
      </div>

      <div className="space-y-2">
        {options.map((option, index) => (
          <div key={option.value || `option-${index}`} className="flex items-center gap-2">
            <div className="flex h-8 w-8 items-center justify-center text-muted-foreground">
              <GripVertical className="h-4 w-4" />
            </div>
            <Checkbox
              checked={option.isCorrect}
              onCheckedChange={(checked) => toggleCorrect(index, checked === true)}
              aria-label={t("dialog.markCorrect")}
            />
            <Input
              value={option.label}
              onChange={(e) => updateLabel(index, e.target.value)}
              placeholder={t("dialog.optionPlaceholder", { index: index + 1 })}
            />
            <Button
              type="button"
              variant="ghost"
              size="icon"
              className="text-destructive hover:text-destructive/90"
              onClick={() => removeOption(index)}
            >
              <Trash2 className="h-4 w-4" />
            </Button>
          </div>
        ))}
      </div>
    </div>
  )
}
