'use client'

import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Tag } from 'lucide-react'
import { cn } from '@/lib/utils'
import { useLabels } from '@/context/LabelContext'
import { LabelBadge } from './label-badge'

interface LabelSelectorProps {
  selectedLabels: string[]
  onLabelsChange: (labels: string[]) => void
  variant?: 'default' | 'compact'
  triggerLabel?: string
  align?: 'start' | 'center' | 'end'
}

export function LabelSelector({
  selectedLabels,
  onLabelsChange,
  variant = 'default',
  triggerLabel = 'Tags',
  align = 'start',
}: LabelSelectorProps) {
  const { labels, loading } = useLabels()

  const handleToggleLabel = (labelName: string) => {
    if (selectedLabels.includes(labelName)) {
      onLabelsChange(selectedLabels.filter((l) => l !== labelName))
    } else {
      onLabelsChange([...selectedLabels, labelName])
    }
  }

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button variant="ghost" size="sm" className="h-8">
          <Tag className="h-4 w-4 mr-2" />
          {triggerLabel}
          {selectedLabels.length > 0 && (
            <Badge variant="secondary" className="ml-2 h-5 min-w-5 px-1.5">
              {selectedLabels.length}
            </Badge>
          )}
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align={align} className="w-64">
        <div className="max-h-64 overflow-y-auto">
          {loading ? (
            <div className="p-4 text-sm text-gray-500">Loading...</div>
          ) : labels.length === 0 ? (
            <div className="p-4 text-sm text-gray-500">No labels yet</div>
          ) : (
            labels.map((label) => {
              const isSelected = selectedLabels.includes(label.name)

              return (
                <DropdownMenuItem
                  key={label.id}
                  onClick={() => handleToggleLabel(label.name)}
                  className="flex items-center justify-between gap-2"
                >
                  <LabelBadge label={label.name} isSelected={isSelected} />
                </DropdownMenuItem>
              )
            })
          )}
        </div>
      </DropdownMenuContent>
    </DropdownMenu>
  )
}
