'use client'

import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog'

interface LineLabelDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  onConfirm: (label: string) => void
  onSkip: () => void
  lineType: 'linestring' | 'arrow' | 'polygon'
}

export function LineLabelDialog({ open, onOpenChange, onConfirm, onSkip, lineType }: LineLabelDialogProps) {
  const [label, setLabel] = useState('')

  useEffect(() => {
    if (open) setLabel('')
  }, [open])

  const handleConfirm = () => {
    onConfirm(label.trim())
    setLabel('')
  }

  const handleSkip = () => {
    onSkip()
    setLabel('')
  }

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      if (label.trim()) {
        handleConfirm()
      } else {
        handleSkip()
      }
    }
  }

  const title = lineType === 'polygon' ? 'Fläche beschriften' : 'Leitung beschriften'
  const placeholder = lineType === 'polygon'
    ? 'z.B. Brandzone, Sperrgebiet...'
    : 'z.B. 1, L2, Zuleitung...'

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-sm top-[12%] translate-y-0">
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
        </DialogHeader>
        <div className="space-y-3 py-2">
          <div className="space-y-1.5">
            <Label htmlFor="line-label">Bezeichnung (optional)</Label>
            <Input
              id="line-label"
              value={label}
              onChange={(e) => setLabel(e.target.value)}
              onKeyDown={handleKeyDown}
              placeholder={placeholder}
              autoFocus
            />
          </div>
          <p className="text-xs text-muted-foreground">
            Wird am Mittelpunkt der Leitung auf der Karte angezeigt. Leer lassen für keine Beschriftung.
          </p>
        </div>
        <DialogFooter className="gap-2">
          <Button variant="outline" onClick={handleSkip}>
            Ohne Label
          </Button>
          <Button onClick={handleConfirm} disabled={!label.trim()}>
            Beschriften
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
