"use client"

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

export type ExamNode = {
  id: string
  type: 'group' | 'question'
  title?: string // For group
  questionId?: string // For question
  score?: number
  children?: ExamNode[] // For 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
}

export function SelectedQuestionList({ 
  items, 
  onRemove, 
  onMove, 
  onScoreChange,
  onGroupTitleChange,
  onAddGroup
}: SelectedQuestionListProps) {
  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>No questions selected. Add questions from the bank or create a group.</p>
        <Button variant="outline" onClick={onAddGroup}>Create Section</Button>
      </div>
    )
  }

  return (
    <div className="space-y-4">
      {items.map((node, idx) => {
        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 || "Untitled Section"} 
                  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')} 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')} disabled={idx === items.length - 1}>
                    <ArrowDown className="h-4 w-4" />
                  </Button>
                  <Button variant="ghost" size="icon" className="h-8 w-8 text-destructive" onClick={() => onRemove(node.id)}>
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </div>
              </div>
              
              <div className="pl-4 border-l-2 border-muted space-y-3">
                {node.children?.length === 0 ? (
                  <div className="text-xs text-muted-foreground italic py-2">Drag questions here or add from bank</div>
                ) : (
                  node.children?.map((child, cIdx) => (
                    <QuestionItem 
                      key={child.id} 
                      item={child} 
                      index={cIdx} 
                      total={node.children?.length || 0}
                      onRemove={() => onRemove(child.id, node.id)}
                      onMove={(dir) => onMove(child.id, dir, node.id)}
                      onScoreChange={(score) => onScoreChange(child.id, score)}
                    />
                  ))
                )}
              </div>
            </div>
          )
        }
        
        return (
          <QuestionItem 
            key={node.id} 
            item={node} 
            index={idx} 
            total={items.length}
            onRemove={() => onRemove(node.id)}
            onMove={(dir) => onMove(node.id, dir)}
            onScoreChange={(score) => onScoreChange(node.id, score)}
          />
        )
      })}
      
      <div className="flex justify-center pt-2">
        <Button variant="outline" size="sm" onClick={onAddGroup} className="w-full border-dashed">
          + Add Section
        </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 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 || "Question content"}
          </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">
            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) || 0)}
          />
        </div>
      </div>
    </div>
  )
}
