"use client"

import { Button } from "@/shared/components/ui/button"
import { Input } from "@/shared/components/ui/input"
import { Label } from "@/shared/components/ui/label"
import { useTranslations } from "next-intl"
import { ArrowUp, ArrowDown, Trash2 } from "lucide-react"
import type { Question } from "@/modules/questions/types"

export type ExamNode = {
  id: string
  type: 'section' | 'group' | 'question'
  title?: string // For section/group
  instruction?: string // For group (大题说明)
  level?: number // For section (分卷层级 1=卷 2=部分)
  questionId?: string // For question
  score?: number
  children?: ExamNode[] // For section/group
  question?: Question // Populated for rendering
}

type SelectedQuestionListProps = {
  items: ExamNode[]
  onRemove: (id: string, parentId?: string) => void
  onMove: (id: string, direction: 'up' | 'down', parentId?: string) => void
  onScoreChange: (id: string, score: number) => void
  onGroupTitleChange: (id: string, title: string) => void
  onAddGroup: () => void
  onAddSection?: () => void
}

export function SelectedQuestionList({
  items,
  onRemove,
  onMove,
  onScoreChange,
  onGroupTitleChange,
  onAddGroup,
  onAddSection
}: SelectedQuestionListProps) {
  const t = useTranslations("examHomework.exam.build")
  if (items.length === 0) {
    return (
      <div className="border border-dashed rounded-lg p-8 text-center text-muted-foreground text-sm flex flex-col gap-4">
        <p>{t("noQuestionsSelected")}</p>
        <div className="flex justify-center gap-2">
          <Button variant="outline" onClick={onAddGroup}>{t("createGroup")}</Button>
          {onAddSection && (
            <Button variant="outline" onClick={onAddSection}>{t("createSection")}</Button>
          )}
        </div>
      </div>
    )
  }

  const renderNode = (node: ExamNode, idx: number, total: number, parentId?: string) => {
    if (node.type === 'section') {
      return (
        <div key={node.id} className="rounded-lg border-2 border-primary/20 bg-primary/5 p-4 space-y-4">
          <div className="flex items-center gap-3">
            <Input
              value={node.title || ""}
              onChange={(e) => onGroupTitleChange(node.id, e.target.value)}
              placeholder={t("sectionTitlePlaceholder")}
              className="font-bold h-9 bg-transparent border-transparent hover:border-input focus:bg-background"
            />
            <div className="flex items-center gap-1">
              <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => onMove(node.id, 'up', parentId)} disabled={idx === 0}>
                <ArrowUp className="h-4 w-4" />
              </Button>
              <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => onMove(node.id, 'down', parentId)} disabled={idx === total - 1}>
                <ArrowDown className="h-4 w-4" />
              </Button>
              <Button variant="ghost" size="icon" className="h-8 w-8 text-destructive" onClick={() => onRemove(node.id, parentId)}>
                <Trash2 className="h-4 w-4" />
              </Button>
            </div>
          </div>
          <div className="pl-4 border-l-2 border-primary/30 space-y-3">
            {!node.children || node.children.length === 0 ? (
              <div className="text-xs text-muted-foreground italic py-2">{t("dragGroupsHere")}</div>
            ) : (
              node.children.map((child, cIdx) => renderNode(child, cIdx, node.children?.length || 0, node.id))
            )}
          </div>
        </div>
      )
    }

    if (node.type === 'group') {
      return (
        <div key={node.id} className="rounded-lg border bg-muted/10 p-4 space-y-4">
          <div className="flex items-center gap-3">
            <Input
              value={node.title || t("untitledGroup")}
              onChange={(e) => onGroupTitleChange(node.id, e.target.value)}
              className="font-semibold h-9 bg-transparent border-transparent hover:border-input focus:bg-background"
            />
            <div className="flex items-center gap-1">
              <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => onMove(node.id, 'up', parentId)} disabled={idx === 0}>
                <ArrowUp className="h-4 w-4" />
              </Button>
              <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => onMove(node.id, 'down', parentId)} disabled={idx === total - 1}>
                <ArrowDown className="h-4 w-4" />
              </Button>
              <Button variant="ghost" size="icon" className="h-8 w-8 text-destructive" onClick={() => onRemove(node.id, parentId)}>
                <Trash2 className="h-4 w-4" />
              </Button>
            </div>
          </div>

          <div className="pl-4 border-l-2 border-muted space-y-3">
            {!node.children || node.children.length === 0 ? (
              <div className="text-xs text-muted-foreground italic py-2">{t("dragQuestionsHere")}</div>
            ) : (
              node.children?.map((child, cIdx) => renderNode(child, cIdx, node.children?.length || 0, node.id))
            )}
          </div>
        </div>
      )
    }

    return (
      <QuestionItem
        key={node.id}
        item={node}
        index={idx}
        total={total}
        onRemove={() => onRemove(node.id, parentId)}
        onMove={(dir) => onMove(node.id, dir, parentId)}
        onScoreChange={(score) => onScoreChange(node.id, score)}
      />
    )
  }

  return (
    <div className="space-y-4">
      {items.map((node, idx) => renderNode(node, idx, items.length))}

      <div className="flex justify-center gap-2 pt-2">
        <Button variant="outline" size="sm" onClick={onAddGroup} className="border-dashed">
          {t("addGroup")}
        </Button>
        {onAddSection && (
          <Button variant="outline" size="sm" onClick={onAddSection} className="border-dashed">
            {t("addSection")}
          </Button>
        )}
      </div>
    </div>
  )
}

function QuestionItem({ item, index, total, onRemove, onMove, onScoreChange }: {
  item: ExamNode
  index: number
  total: number
  onRemove: () => void
  onMove: (dir: 'up' | 'down') => void
  onScoreChange: (score: number) => void
}) {
  const t = useTranslations("examHomework.exam.build")
  const rawContent = item.question?.content
  const parsedContent = (() => {
    if (rawContent && typeof rawContent === "object") return rawContent as { text?: string; options?: Array<{ id?: string; text?: string }> }
    if (typeof rawContent === "string") {
      try {
        const parsed = JSON.parse(rawContent) as unknown
        if (parsed && typeof parsed === "object") return parsed as { text?: string; options?: Array<{ id?: string; text?: string }> }
        return { text: rawContent }
      } catch {
        return { text: rawContent }
      }
    }
    return { text: "" }
  })()

  const options = Array.isArray(parsedContent.options) ? parsedContent.options : []
  return (
    <div className="group flex flex-col gap-3 rounded-md border p-3 bg-card hover:border-primary/50 transition-colors">
      <div className="flex items-start justify-between gap-3">
        <div className="flex gap-2">
          <span className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-muted text-xs font-medium">
            {index + 1}
          </span>
          <p className="text-sm line-clamp-2 pt-0.5">
            {parsedContent.text || t("questionContent")}
          </p>
        </div>
        <Button
          variant="ghost"
          size="icon"
          className="h-6 w-6 text-muted-foreground hover:text-destructive"
          onClick={onRemove}
        >
          <Trash2 className="h-4 w-4" />
        </Button>
      </div>
      {(item.question?.type === "single_choice" || item.question?.type === "multiple_choice") && options.length > 0 && (
        <div className="grid grid-cols-1 gap-1 pl-8 text-xs text-muted-foreground">
          {options.map((opt, idx) => (
            <div key={opt.id ?? idx} className="flex gap-2">
              <span className="font-medium">{opt.id ?? String.fromCharCode(65 + idx)}.</span>
              <span>{opt.text ?? ""}</span>
            </div>
          ))}
        </div>
      )}

      <div className="flex items-center justify-between pl-8">
        <div className="flex items-center gap-1">
          <Button
            variant="ghost"
            size="icon"
            className="h-6 w-6"
            disabled={index === 0}
            onClick={() => onMove('up')}
          >
            <ArrowUp className="h-3 w-3" />
          </Button>
          <Button
            variant="ghost"
            size="icon"
            className="h-6 w-6"
            disabled={index === total - 1}
            onClick={() => onMove('down')}
          >
            <ArrowDown className="h-3 w-3" />
          </Button>
        </div>

        <div className="flex items-center gap-2">
          <Label htmlFor={`score-${item.id}`} className="text-xs text-muted-foreground">
            {t("score")}
          </Label>
          <Input
            id={`score-${item.id}`}
            type="number"
            min={0}
            className="h-7 w-16 text-right"
            value={item.score}
            onChange={(e) => onScoreChange(parseInt(e.target.value, 10) || 0)}
          />
        </div>
      </div>
    </div>
  )
}
