'use client'

import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Badge } from '@/components/ui/badge'
import { Plus, Trash2, ChevronUp, ChevronDown } from 'lucide-react'

type WizardRound = {
  tempId: string
  name: string
  slug: string
  roundType: string
  sortOrder: number
  configJson: Record<string, unknown>
}

type RoundsSectionProps = {
  rounds: WizardRound[]
  onChange: (rounds: WizardRound[]) => void
}

const roundTypes = [
  { value: 'INTAKE', label: 'Intake', color: 'bg-gray-100 text-gray-700' },
  { value: 'FILTERING', label: 'Filtering', color: 'bg-amber-100 text-amber-700' },
  { value: 'EVALUATION', label: 'Evaluation', color: 'bg-blue-100 text-blue-700' },
  { value: 'SUBMISSION', label: 'Submission', color: 'bg-purple-100 text-purple-700' },
  { value: 'MENTORING', label: 'Mentoring', color: 'bg-teal-100 text-teal-700' },
  { value: 'LIVE_FINAL', label: 'Live Final', color: 'bg-red-100 text-red-700' },
  { value: 'DELIBERATION', label: 'Deliberation', color: 'bg-indigo-100 text-indigo-700' },
]

export function RoundsSection({ rounds, onChange }: RoundsSectionProps) {
  const handleAddRound = () => {
    const newRound: WizardRound = {
      tempId: crypto.randomUUID(),
      name: '',
      slug: '',
      roundType: 'EVALUATION',
      sortOrder: rounds.length,
      configJson: {},
    }
    onChange([...rounds, newRound])
  }

  const handleRemoveRound = (tempId: string) => {
    const updated = rounds.filter((r) => r.tempId !== tempId)
    // Reorder
    const reordered = updated.map((r, index) => ({ ...r, sortOrder: index }))
    onChange(reordered)
  }

  const handleUpdateRound = (tempId: string, updates: Partial<WizardRound>) => {
    const updated = rounds.map((r) =>
      r.tempId === tempId ? { ...r, ...updates } : r
    )
    onChange(updated)
  }

  const handleMoveUp = (index: number) => {
    if (index === 0) return
    const updated = [...rounds]
    ;[updated[index - 1], updated[index]] = [updated[index], updated[index - 1]]
    const reordered = updated.map((r, i) => ({ ...r, sortOrder: i }))
    onChange(reordered)
  }

  const handleMoveDown = (index: number) => {
    if (index === rounds.length - 1) return
    const updated = [...rounds]
    ;[updated[index], updated[index + 1]] = [updated[index + 1], updated[index]]
    const reordered = updated.map((r, i) => ({ ...r, sortOrder: i }))
    onChange(reordered)
  }

  return (
    <div className="space-y-4">
      <Card>
        <CardHeader>
          <CardTitle className="text-base">Competition Rounds</CardTitle>
          <p className="text-sm text-muted-foreground">
            Define the stages of your competition workflow
          </p>
        </CardHeader>
        <CardContent className="space-y-3">
          {rounds.length === 0 ? (
            <div className="py-8 text-center text-sm text-muted-foreground">
              No rounds yet. Add your first round to get started.
            </div>
          ) : (
            rounds.map((round, index) => {
              const typeConfig = roundTypes.find((t) => t.value === round.roundType)
              return (
                <div key={round.tempId} className="flex items-start gap-2 border rounded-lg p-3">
                  <div className="flex flex-col gap-1 shrink-0">
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-6 w-6"
                      onClick={() => handleMoveUp(index)}
                      disabled={index === 0}
                    >
                      <ChevronUp className="h-3 w-3" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-6 w-6"
                      onClick={() => handleMoveDown(index)}
                      disabled={index === rounds.length - 1}
                    >
                      <ChevronDown className="h-3 w-3" />
                    </Button>
                  </div>

                  <div className="flex h-8 w-8 items-center justify-center rounded-full bg-muted text-sm font-bold shrink-0">
                    {index + 1}
                  </div>

                  <div className="flex-1 min-w-0 space-y-3">
                    <div className="grid gap-3 sm:grid-cols-2">
                      <div className="space-y-1.5">
                        <Label className="text-xs">Round Name</Label>
                        <Input
                          placeholder="e.g., First Evaluation"
                          value={round.name}
                          onChange={(e) => {
                            const name = e.target.value
                            const slug = name.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '')
                            handleUpdateRound(round.tempId, { name, slug })
                          }}
                        />
                      </div>

                      <div className="space-y-1.5">
                        <Label className="text-xs">Slug</Label>
                        <Input
                          placeholder="e.g., first-evaluation"
                          value={round.slug}
                          onChange={(e) => handleUpdateRound(round.tempId, { slug: e.target.value })}
                        />
                      </div>
                    </div>

                    <div className="flex items-center gap-2">
                      <div className="flex-1">
                        <Label className="text-xs">Round Type</Label>
                        <Select
                          value={round.roundType}
                          onValueChange={(value) => handleUpdateRound(round.tempId, { roundType: value })}
                        >
                          <SelectTrigger className="mt-1.5">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            {roundTypes.map((type) => (
                              <SelectItem key={type.value} value={type.value}>
                                {type.label}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                      {typeConfig && (
                        <Badge variant="secondary" className={typeConfig.color}>
                          {typeConfig.label}
                        </Badge>
                      )}
                    </div>
                  </div>

                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-8 w-8 text-destructive hover:text-destructive shrink-0"
                    onClick={() => handleRemoveRound(round.tempId)}
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </div>
              )
            })
          )}

          <Button variant="outline" className="w-full" onClick={handleAddRound}>
            <Plus className="h-4 w-4 mr-2" />
            Add Round
          </Button>
        </CardContent>
      </Card>
    </div>
  )
}
