'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,
} from 'lucide-react'
import { cn } from '@/lib/utils'

export interface Criterion {
  id: string
  label: string
  description?: string
  scale: number // 5 or 10
  weight?: number
  required: boolean
}

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(): Criterion {
  return {
    id: generateId(),
    label: '',
    description: '',
    scale: 5,
    weight: 1,
    required: true,
  }
}

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(() => {
    const newCriterion = createDefaultCriterion()
    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">
                    <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="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>

                    <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)}
                          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}
                            onCheckedChange={(checked) =>
                              updateDraft({ required: checked })
                            }
                            disabled={disabled}
                          />
                        </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="font-medium truncate">
                          {criterion.label || '(Untitled)'}
                        </span>
                        <Badge variant="secondary" className="shrink-0 text-xs">
                          1-{criterion.scale}
                        </Badge>
                        {criterion.weight && criterion.weight !== 1 && (
                          <Badge variant="outline" className="shrink-0 text-xs">
                            {criterion.weight}x
                          </Badge>
                        )}
                        {criterion.required && (
                          <Badge variant="default" className="shrink-0 text-xs">
                            Required
                          </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">
          <Button
            type="button"
            variant="outline"
            size="sm"
            onClick={addCriterion}
            disabled={editingId !== null}
          >
            <Plus className="mr-1 h-4 w-4" />
            Add Criterion
          </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) => (
            <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>
                <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}
                    </span>
                  </div>

                  <div className="flex gap-1 flex-wrap">
                    {Array.from({ length: criterion.scale }, (_, 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 / 2)
                              ? 'bg-primary/20 text-primary'
                              : 'bg-muted'
                          )}
                        >
                          {num}
                        </div>
                      )
                    )}
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}

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