import { useState } from 'react'
import { Wifi } from 'lucide-react'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'

interface Props {
  onConnect: (address: string) => Promise<void>
}

export function ConnectDialog({ onConnect }: Props) {
  const [open, setOpen] = useState(false)
  const [address, setAddress] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  async function handleConnect() {
    if (!address.trim()) return
    setLoading(true)
    setError('')
    try {
      await onConnect(address.trim())
      setOpen(false)
      setAddress('')
    } catch (e) {
      setError(String(e))
    } finally {
      setLoading(false)
    }
  }

  return (
    <>
      <Button variant="outline" size="sm" className="gap-1.5" onClick={() => setOpen(true)}>
        <Wifi size={14} />
        Connect wireless
      </Button>
      <Dialog open={open} onOpenChange={setOpen}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Connect wireless device</DialogTitle>
        </DialogHeader>
        <div className="space-y-3 pt-2">
          <Input
            placeholder="192.168.1.100:5555"
            value={address}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => setAddress(e.target.value)}
            onKeyDown={(e: React.KeyboardEvent) => e.key === 'Enter' && handleConnect()}
            autoFocus
          />
          {error && <p className="text-sm text-destructive">{error}</p>}
          <div className="flex justify-end gap-2">
            <Button variant="ghost" onClick={() => setOpen(false)}>Cancel</Button>
            <Button onClick={handleConnect} disabled={loading || !address.trim()}>
              {loading ? 'Connecting…' : 'Connect'}
            </Button>
          </div>
        </div>
      </DialogContent>
      </Dialog>
    </>
  )
}
