'use client'

import { useState, useCallback } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Switch } from '@/components/ui/switch'
import { Slider } from '@/components/ui/slider'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog'
import {
  Plus,
  Trash2,
  ChevronUp,
  ChevronDown,
  Edit,
  Eye,
  GripVertical,
  Check,
  X,
  Type,
  ToggleLeft,
  Hash,
  Heading,
  ThumbsUp,
  ThumbsDown,
  ArrowUpCircle,
} from 'lucide-react'
import { cn } from '@/lib/utils'

export type CriterionType = 'numeric' | 'text' | 'boolean' | 'advance' | 'section_header'

export interface CriterionCondition {
  criterionId: string
  operator: 'equals' | 'greaterThan' | 'lessThan'
  value: number | string | boolean
}

export interface Criterion {
  id: string
  label: string
  description?: string
  type?: CriterionType // defaults to 'numeric'
  // Numeric fields
  scale?: number // 5 or 10
  weight?: number
  required?: boolean
  // Text fields
  maxLength?: number
  placeholder?: string
  // Boolean fields
  trueLabel?: string
  falseLabel?: string
  // Conditional visibility
  condition?: CriterionCondition
  // Section grouping
  sectionId?: string
}

interface EvaluationFormBuilderProps {
  initialCriteria?: Criterion[]
  onChange: (criteria: Criterion[]) => void
  disabled?: boolean
}

function generateId(): string {
  return `criterion-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`
}

function createDefaultCriterion(type: CriterionType = 'numeric'): Criterion {
  const base: Criterion = {
    id: generateId(),
    label: '',
    description: '',
    type,
  }
  switch (type) {
    case 'numeric':
      return { ...base, scale: 5, weight: 1, required: true }
    case 'text':
      return { ...base, maxLength: 1000, placeholder: '', required: true }
    case 'boolean':
      return { ...base, trueLabel: 'Yes', falseLabel: 'No', required: true }
    case 'advance':
      return { ...base, label: 'Advance to next round?', trueLabel: 'Yes', falseLabel: 'No', required: true }
    case 'section_header':
      return { ...base, required: false }
    default:
      return { ...base, scale: 5, weight: 1, required: true }
  }
}

const CRITERION_TYPE_OPTIONS: { value: CriterionType; label: string; icon: typeof Hash }[] = [
  { value: 'numeric', label: 'Numeric Score', icon: Hash },
  { value: 'text', label: 'Text Response', icon: Type },
  { value: 'boolean', label: 'Yes / No', icon: ToggleLeft },
  { value: 'section_header', label: 'Section Header', icon: Heading },
]

export function EvaluationFormBuilder({
  initialCriteria = [],
  onChange,
  disabled = false,
}: EvaluationFormBuilderProps) {
  const [criteria, setCriteria] = useState<Criterion[]>(initialCriteria)
  const [editingId, setEditingId] = useState<string | null>(null)
  const [editDraft, setEditDraft] = useState<Criterion | null>(null)

  // Update parent when criteria change
  const updateCriteria = useCallback(
    (newCriteria: Criterion[]) => {
      setCriteria(newCriteria)
      onChange(newCriteria)
    },
    [onChange]
  )

  // Add new criterion
  const addCriterion = useCallback((type: CriterionType = 'numeric') => {
    const newCriterion = createDefaultCriterion(type)
    const newCriteria = [...criteria, newCriterion]
    updateCriteria(newCriteria)
    setEditingId(newCriterion.id)
    setEditDraft(newCriterion)
  }, [criteria, updateCriteria])

  // Delete criterion
  const deleteCriterion = useCallback(
    (id: string) => {
      updateCriteria(criteria.filter((c) => c.id !== id))
      if (editingId === id) {
        setEditingId(null)
        setEditDraft(null)
      }
    },
    [criteria, editingId, updateCriteria]
  )

  // Move criterion up/down
  const moveCriterion = useCallback(
    (id: string, direction: 'up' | 'down') => {
      const index = criteria.findIndex((c) => c.id === id)
      if (index === -1) return

      const newIndex = direction === 'up' ? index - 1 : index + 1
      if (newIndex < 0 || newIndex >= criteria.length) return

      const newCriteria = [...criteria]
      const [removed] = newCriteria.splice(index, 1)
      newCriteria.splice(newIndex, 0, removed)
      updateCriteria(newCriteria)
    },
    [criteria, updateCriteria]
  )

  // Start editing
  const startEditing = useCallback((criterion: Criterion) => {
    setEditingId(criterion.id)
    setEditDraft({ ...criterion })
  }, [])

  // Cancel editing
  const cancelEditing = useCallback(() => {
    // If it's a new criterion with no label, remove it
    if (editDraft && !editDraft.label.trim()) {
      updateCriteria(criteria.filter((c) => c.id !== editDraft.id))
    }
    setEditingId(null)
    setEditDraft(null)
  }, [editDraft, criteria, updateCriteria])

  // Save editing
  const saveEditing = useCallback(() => {
    if (!editDraft || !editDraft.label.trim()) return

    updateCriteria(
      criteria.map((c) => (c.id === editDraft.id ? editDraft : c))
    )
    setEditingId(null)
    setEditDraft(null)
  }, [editDraft, criteria, updateCriteria])

  // Update edit draft
  const updateDraft = useCallback(
    (updates: Partial<Criterion>) => {
      if (!editDraft) return
      setEditDraft({ ...editDraft, ...updates })
    },
    [editDraft]
  )

  return (
    <div className="space-y-4">
      {/* Criteria list */}
      {criteria.length > 0 ? (
        <div className="space-y-2">
          {criteria.map((criterion, index) => {
            const isEditing = editingId === criterion.id

            return (
              <div
                key={criterion.id}
                className={cn(
                  'rounded-lg border transition-colors',
                  isEditing ? 'border-primary bg-muted/30' : 'bg-background',
                  disabled && 'opacity-60'
                )}
              >
                {isEditing && editDraft ? (
                  // Edit mode
                  <div className="p-4 space-y-4">
                    {/* Type indicator */}
                    <div className="flex items-center gap-2">
                      <Badge variant="outline" className="text-xs">
                        {editDraft.type === 'advance' ? 'Advance to Next Round?' : (CRITERION_TYPE_OPTIONS.find((t) => t.value === (editDraft.type || 'numeric'))?.label ?? 'Numeric Score')}
                      </Badge>
                    </div>

                    <div className="space-y-2">
                      <Label htmlFor={`label-${criterion.id}`}>Label *</Label>
                      <Input
                        id={`label-${criterion.id}`}
                        value={editDraft.label}
                        onChange={(e) => updateDraft({ label: e.target.value })}
                        placeholder={
                          (editDraft.type || 'numeric') === 'section_header'
                            ? 'e.g., Technical Assessment'
                            : 'e.g., Innovation'
                        }
                        disabled={disabled}
                        autoFocus
                      />
                    </div>

                    <div className="space-y-2">
                      <Label htmlFor={`description-${criterion.id}`}>
                        Description (optional)
                      </Label>
                      <Textarea
                        id={`description-${criterion.id}`}
                        value={editDraft.description || ''}
                        onChange={(e) => updateDraft({ description: e.target.value })}
                        placeholder="Help jurors understand this criterion..."
                        rows={2}
                        maxLength={500}
                        disabled={disabled}
                      />
                    </div>

                    {/* Type-specific fields */}
                    {(editDraft.type || 'numeric') === 'numeric' && (
                      <div className="grid gap-4 sm:grid-cols-3">
                        <div className="space-y-2">
                          <Label htmlFor={`scale-${criterion.id}`}>Scale</Label>
                          <Select
                            value={String(editDraft.scale ?? 5)}
                            onValueChange={(v) => updateDraft({ scale: parseInt(v) })}
                            disabled={disabled}
                          >
                            <SelectTrigger id={`scale-${criterion.id}`}>
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="5">1-5</SelectItem>
                              <SelectItem value="10">1-10</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>

                        <div className="space-y-2">
                          <Label htmlFor={`weight-${criterion.id}`}>
                            Weight: {editDraft.weight ?? 1}x
                          </Label>
                          <div className="flex items-center gap-3">
                            <span className="text-xs text-muted-foreground w-4">0.5</span>
                            <Slider
                              id={`weight-${criterion.id}`}
                              min={0.5}
                              max={3}
                              step={0.5}
                              value={[editDraft.weight ?? 1]}
                              onValueChange={(v) => updateDraft({ weight: v[0] })}
                              disabled={disabled}
                              className="flex-1"
                            />
                            <span className="text-xs text-muted-foreground w-4">3</span>
                          </div>
                          <p className="text-xs text-muted-foreground">
                            {(editDraft.weight ?? 1) === 1
                              ? 'Normal importance'
                              : (editDraft.weight ?? 1) < 1
                                ? 'Lower importance'
                                : 'Higher importance'}
                          </p>
                        </div>

                        <div className="space-y-2">
                          <Label>Required</Label>
                          <div className="flex items-center h-10">
                            <Switch
                              checked={editDraft.required ?? true}
                              onCheckedChange={(checked) =>
                                updateDraft({ required: checked })
                              }
                              disabled={disabled}
                            />
                          </div>
                        </div>
                      </div>
                    )}

                    {(editDraft.type || 'numeric') === 'text' && (
                      <div className="grid gap-4 sm:grid-cols-3">
                        <div className="space-y-2">
                          <Label htmlFor={`maxLength-${criterion.id}`}>Max Length</Label>
                          <Input
                            id={`maxLength-${criterion.id}`}
                            type="number"
                            min={1}
                            max={10000}
                            value={editDraft.maxLength ?? 1000}
                            onChange={(e) => updateDraft({ maxLength: parseInt(e.target.value) || 1000 })}
                            disabled={disabled}
                          />
                        </div>

                        <div className="space-y-2">
                          <Label htmlFor={`placeholder-${criterion.id}`}>Placeholder</Label>
                          <Input
                            id={`placeholder-${criterion.id}`}
                            value={editDraft.placeholder || ''}
                            onChange={(e) => updateDraft({ placeholder: e.target.value })}
                            placeholder="Enter placeholder text..."
                            disabled={disabled}
                          />
                        </div>

                        <div className="space-y-2">
                          <Label>Required</Label>
                          <div className="flex items-center h-10">
                            <Switch
                              checked={editDraft.required ?? true}
                              onCheckedChange={(checked) =>
                                updateDraft({ required: checked })
                              }
                              disabled={disabled}
                            />
                          </div>
                        </div>
                      </div>
                    )}

                    {(editDraft.type || 'numeric') === 'boolean' && (
                      <div className="grid gap-4 sm:grid-cols-3">
                        <div className="space-y-2">
                          <Label htmlFor={`trueLabel-${criterion.id}`}>Yes Label</Label>
                          <Input
                            id={`trueLabel-${criterion.id}`}
                            value={editDraft.trueLabel || 'Yes'}
                            onChange={(e) => updateDraft({ trueLabel: e.target.value })}
                            placeholder="Yes"
                            disabled={disabled}
                          />
                        </div>

                        <div className="space-y-2">
                          <Label htmlFor={`falseLabel-${criterion.id}`}>No Label</Label>
                          <Input
                            id={`falseLabel-${criterion.id}`}
                            value={editDraft.falseLabel || 'No'}
                            onChange={(e) => updateDraft({ falseLabel: e.target.value })}
                            placeholder="No"
                            disabled={disabled}
                          />
                        </div>

                        <div className="space-y-2">
                          <Label>Required</Label>
                          <div className="flex items-center h-10">
                            <Switch
                              checked={editDraft.required ?? true}
                              onCheckedChange={(checked) =>
                                updateDraft({ required: checked })
                              }
                              disabled={disabled}
                            />
                          </div>
                        </div>
                      </div>
                    )}

                    {editDraft.type === 'advance' && (
                      <div className="grid gap-4 sm:grid-cols-2">
                        <div className="space-y-2">
                          <Label htmlFor={`trueLabel-${criterion.id}`}>Yes Label</Label>
                          <Input
                            id={`trueLabel-${criterion.id}`}
                            value={editDraft.trueLabel || 'Yes'}
                            onChange={(e) => updateDraft({ trueLabel: e.target.value })}
                            placeholder="Yes"
                            disabled={disabled}
                          />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor={`falseLabel-${criterion.id}`}>No Label</Label>
                          <Input
                            id={`falseLabel-${criterion.id}`}
                            value={editDraft.falseLabel || 'No'}
                            onChange={(e) => updateDraft({ falseLabel: e.target.value })}
                            placeholder="No"
                            disabled={disabled}
                          />
                        </div>
                      </div>
                    )}

                    {/* Condition builder - available for all types except section_header and advance */}
                    {(editDraft.type || 'numeric') !== 'section_header' && editDraft.type !== 'advance' && criteria.filter((c) => c.id !== editDraft.id).length > 0 && (
                      <div className="space-y-2 border-t pt-4">
                        <div className="flex items-center justify-between">
                          <Label>Conditional Visibility</Label>
                          {editDraft.condition ? (
                            <Button
                              type="button"
                              variant="ghost"
                              size="sm"
                              onClick={() => updateDraft({ condition: undefined })}
                              disabled={disabled}
                            >
                              <X className="mr-1 h-3 w-3" />
                              Remove
                            </Button>
                          ) : (
                            <Button
                              type="button"
                              variant="outline"
                              size="sm"
                              onClick={() =>
                                updateDraft({
                                  condition: {
                                    criterionId: criteria.filter((c) => c.id !== editDraft.id)[0]?.id ?? '',
                                    operator: 'equals',
                                    value: 0,
                                  },
                                })
                              }
                              disabled={disabled}
                            >
                              Add Condition
                            </Button>
                          )}
                        </div>
                        {editDraft.condition && (
                          <div className="grid gap-2 sm:grid-cols-3 p-3 rounded-md bg-muted/50">
                            <div className="space-y-1">
                              <Label className="text-xs">When criterion</Label>
                              <Select
                                value={editDraft.condition.criterionId}
                                onValueChange={(v) =>
                                  updateDraft({ condition: { ...editDraft.condition!, criterionId: v } })
                                }
                                disabled={disabled}
                              >
                                <SelectTrigger><SelectValue /></SelectTrigger>
                                <SelectContent>
                                  {criteria
                                    .filter((c) => c.id !== editDraft.id && (c.type || 'numeric') !== 'section_header')
                                    .map((c) => (
                                      <SelectItem key={c.id} value={c.id}>
                                        {c.label || '(Untitled)'}
                                      </SelectItem>
                                    ))}
                                </SelectContent>
                              </Select>
                            </div>
                            <div className="space-y-1">
                              <Label className="text-xs">Operator</Label>
                              <Select
                                value={editDraft.condition.operator}
                                onValueChange={(v) =>
                                  updateDraft({ condition: { ...editDraft.condition!, operator: v as 'equals' | 'greaterThan' | 'lessThan' } })
                                }
                                disabled={disabled}
                              >
                                <SelectTrigger><SelectValue /></SelectTrigger>
                                <SelectContent>
                                  <SelectItem value="equals">equals</SelectItem>
                                  <SelectItem value="greaterThan">greater than</SelectItem>
                                  <SelectItem value="lessThan">less than</SelectItem>
                                </SelectContent>
                              </Select>
                            </div>
                            <div className="space-y-1">
                              <Label className="text-xs">Value</Label>
                              <Input
                                value={String(editDraft.condition.value)}
                                onChange={(e) => {
                                  const raw = e.target.value
                                  const parsed = Number(raw)
                                  updateDraft({
                                    condition: {
                                      ...editDraft.condition!,
                                      value: isNaN(parsed) ? (raw === 'true' ? true : raw === 'false' ? false : raw) : parsed,
                                    },
                                  })
                                }}
                                disabled={disabled}
                                placeholder="Value"
                              />
                            </div>
                          </div>
                        )}
                      </div>
                    )}

                    {/* Edit actions */}
                    <div className="flex justify-end gap-2 pt-2">
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        onClick={cancelEditing}
                        disabled={disabled}
                      >
                        <X className="mr-1 h-4 w-4" />
                        Cancel
                      </Button>
                      <Button
                        type="button"
                        size="sm"
                        onClick={saveEditing}
                        disabled={disabled || !editDraft.label.trim()}
                      >
                        <Check className="mr-1 h-4 w-4" />
                        Save
                      </Button>
                    </div>
                  </div>
                ) : (
                  // View mode
                  <div className="flex items-center gap-3 p-3">
                    {/* Drag handle / position indicator */}
                    <div className="text-muted-foreground/50">
                      <GripVertical className="h-4 w-4" />
                    </div>

                    {/* Criterion info */}
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 flex-wrap">
                        <span className={cn(
                          'font-medium truncate',
                          (criterion.type || 'numeric') === 'section_header' && 'text-base font-semibold'
                        )}>
                          {criterion.label || '(Untitled)'}
                        </span>
                        {(() => {
                          const type = criterion.type || 'numeric'
                          const TypeIcon = type === 'advance' ? ArrowUpCircle : (CRITERION_TYPE_OPTIONS.find((t) => t.value === type)?.icon ?? Hash)
                          return (
                            <Badge variant="secondary" className="shrink-0 text-xs gap-1">
                              <TypeIcon className="h-3 w-3" />
                              {type === 'numeric' ? `1-${criterion.scale ?? 5}` : type === 'advance' ? 'Advance to Next Round?' : CRITERION_TYPE_OPTIONS.find((t) => t.value === type)?.label}
                            </Badge>
                          )
                        })()}
                        {criterion.weight && criterion.weight !== 1 && (criterion.type || 'numeric') === 'numeric' && (
                          <Badge variant="outline" className="shrink-0 text-xs">
                            {criterion.weight}x
                          </Badge>
                        )}
                        {criterion.required && (criterion.type || 'numeric') !== 'section_header' && (
                          <Badge variant="default" className="shrink-0 text-xs">
                            Required
                          </Badge>
                        )}
                        {criterion.condition && (
                          <Badge variant="outline" className="shrink-0 text-xs text-amber-600 border-amber-300">
                            Conditional
                          </Badge>
                        )}
                      </div>
                      {criterion.description && (
                        <p className="text-sm text-muted-foreground truncate mt-0.5">
                          {criterion.description}
                        </p>
                      )}
                    </div>

                    {/* Actions */}
                    {!disabled && (
                      <div className="flex items-center gap-1">
                        <Button
                          type="button"
                          variant="ghost"
                          size="icon"
                          className="h-8 w-8"
                          aria-label="Move criterion up"
                          onClick={() => moveCriterion(criterion.id, 'up')}
                          disabled={index === 0}
                        >
                          <ChevronUp className="h-4 w-4" />
                        </Button>
                        <Button
                          type="button"
                          variant="ghost"
                          size="icon"
                          className="h-8 w-8"
                          aria-label="Move criterion down"
                          onClick={() => moveCriterion(criterion.id, 'down')}
                          disabled={index === criteria.length - 1}
                        >
                          <ChevronDown className="h-4 w-4" />
                        </Button>
                        <Button
                          type="button"
                          variant="ghost"
                          size="icon"
                          className="h-8 w-8"
                          aria-label="Edit criterion"
                          onClick={() => startEditing(criterion)}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        <AlertDialog>
                          <AlertDialogTrigger asChild>
                            <Button
                              type="button"
                              variant="ghost"
                              size="icon"
                              className="h-8 w-8 text-destructive hover:text-destructive"
                              aria-label="Delete criterion"
                            >
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          </AlertDialogTrigger>
                          <AlertDialogContent>
                            <AlertDialogHeader>
                              <AlertDialogTitle>Delete criterion?</AlertDialogTitle>
                              <AlertDialogDescription>
                                Are you sure you want to delete &quot;{criterion.label}&quot;?
                                This action cannot be undone.
                              </AlertDialogDescription>
                            </AlertDialogHeader>
                            <AlertDialogFooter>
                              <AlertDialogCancel>Cancel</AlertDialogCancel>
                              <AlertDialogAction
                                onClick={() => deleteCriterion(criterion.id)}
                                className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                              >
                                Delete
                              </AlertDialogAction>
                            </AlertDialogFooter>
                          </AlertDialogContent>
                        </AlertDialog>
                      </div>
                    )}
                  </div>
                )}
              </div>
            )
          })}
        </div>
      ) : (
        <div className="rounded-lg border border-dashed p-8 text-center">
          <p className="text-muted-foreground">
            No evaluation criteria defined yet.
          </p>
        </div>
      )}

      {/* Actions */}
      {!disabled && (
        <div className="flex items-center gap-3 flex-wrap">
          {CRITERION_TYPE_OPTIONS.map(({ value, label, icon: Icon }) => (
            <Button
              key={value}
              type="button"
              variant="outline"
              size="sm"
              onClick={() => addCriterion(value)}
              disabled={editingId !== null}
            >
              <Icon className="mr-1 h-4 w-4" />
              {label}
            </Button>
          ))}

          <Button
            type="button"
            variant="outline"
            size="sm"
            onClick={() => addCriterion('advance')}
            disabled={editingId !== null || criteria.some((c) => c.type === 'advance')}
            title={criteria.some((c) => c.type === 'advance') ? 'Only one advance criterion allowed per form' : undefined}
            className={cn(
              'border-brand-blue/40 text-brand-blue hover:bg-brand-blue/5',
              criteria.some((c) => c.type === 'advance') && 'opacity-50 cursor-not-allowed'
            )}
          >
            <ArrowUpCircle className="mr-1 h-4 w-4" />
            Advance to Next Round?
          </Button>

          {criteria.length > 0 && (
            <PreviewDialog criteria={criteria} />
          )}
        </div>
      )}
    </div>
  )
}

// Preview dialog showing how the evaluation form will look
function PreviewDialog({ criteria }: { criteria: Criterion[] }) {
  return (
    <Dialog>
      <DialogTrigger asChild>
        <Button type="button" variant="ghost" size="sm">
          <Eye className="mr-1 h-4 w-4" />
          Preview
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Evaluation Form Preview</DialogTitle>
          <DialogDescription>
            This is how the evaluation form will appear to jurors.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6 py-4">
          {criteria.map((criterion) => {
            const type = criterion.type || 'numeric'

            if (type === 'section_header') {
              return (
                <div key={criterion.id} className="border-b pb-2 pt-4">
                  <h3 className="font-semibold text-lg">{criterion.label}</h3>
                  {criterion.description && (
                    <p className="text-sm text-muted-foreground mt-1">{criterion.description}</p>
                  )}
                </div>
              )
            }

            return (
              <Card key={criterion.id}>
                <CardHeader className="pb-3">
                  <CardTitle className="text-base flex items-center gap-2">
                    {criterion.label}
                    {criterion.required && (
                      <Badge variant="destructive" className="text-xs">
                        Required
                      </Badge>
                    )}
                  </CardTitle>
                  {criterion.description && (
                    <CardDescription>{criterion.description}</CardDescription>
                  )}
                </CardHeader>
                <CardContent>
                  {type === 'numeric' && (
                    <div className="space-y-3">
                      <div className="flex items-center gap-2">
                        <span className="text-xs text-muted-foreground w-4">1</span>
                        <div className="flex-1 h-2 bg-muted rounded-full overflow-hidden">
                          <div
                            className="h-full bg-primary/30 rounded-full"
                            style={{ width: '50%' }}
                          />
                        </div>
                        <span className="text-xs text-muted-foreground w-4">
                          {criterion.scale ?? 5}
                        </span>
                      </div>
                      <div className="flex gap-1 flex-wrap">
                        {Array.from({ length: criterion.scale ?? 5 }, (_, i) => i + 1).map(
                          (num) => (
                            <div
                              key={num}
                              className={cn(
                                'w-9 h-9 rounded-md text-sm font-medium flex items-center justify-center',
                                num <= Math.ceil((criterion.scale ?? 5) / 2)
                                  ? 'bg-primary/20 text-primary'
                                  : 'bg-muted'
                              )}
                            >
                              {num}
                            </div>
                          )
                        )}
                      </div>
                    </div>
                  )}
                  {type === 'text' && (
                    <Textarea
                      placeholder={criterion.placeholder || 'Enter your response...'}
                      rows={3}
                      maxLength={criterion.maxLength ?? 1000}
                      disabled
                      className="opacity-60"
                    />
                  )}
                  {type === 'boolean' && (
                    <div className="flex gap-4">
                      <div className="flex-1 h-12 rounded-md border flex items-center justify-center text-sm font-medium bg-muted/50">
                        <ThumbsUp className="mr-2 h-4 w-4" />
                        {criterion.trueLabel || 'Yes'}
                      </div>
                      <div className="flex-1 h-12 rounded-md border flex items-center justify-center text-sm font-medium bg-muted/50">
                        <ThumbsDown className="mr-2 h-4 w-4" />
                        {criterion.falseLabel || 'No'}
                      </div>
                    </div>
                  )}
                  {type === 'advance' && (
                    <div className="flex gap-4">
                      <div className="flex-1 h-14 rounded-lg border-2 border-emerald-300 bg-emerald-50/50 flex items-center justify-center text-sm font-semibold text-emerald-700">
                        <ThumbsUp className="mr-2 h-4 w-4" />
                        {criterion.trueLabel || 'Yes'}
                      </div>
                      <div className="flex-1 h-14 rounded-lg border-2 border-red-300 bg-red-50/50 flex items-center justify-center text-sm font-semibold text-red-700">
                        <ThumbsDown className="mr-2 h-4 w-4" />
                        {criterion.falseLabel || 'No'}
                      </div>
                    </div>
                  )}
                </CardContent>
              </Card>
            )
          })}

          {criteria.length === 0 && (
            <p className="text-center text-muted-foreground py-8">
              No criteria to preview.
            </p>
          )}
        </div>
      </DialogContent>
    </Dialog>
  )
}
