'use client'

import { useState, useEffect } from 'react'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Loader2, Tag } from 'lucide-react'
import { useNetcupUpdateNickname } from '@/hooks/use-netcup'

interface EditNicknameDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  serverId: string
  currentNickname?: string
  serverName?: string
}

export function EditNicknameDialog({
  open,
  onOpenChange,
  serverId,
  currentNickname,
  serverName,
}: EditNicknameDialogProps) {
  const [nickname, setNickname] = useState(currentNickname || '')
  const [error, setError] = useState<string | null>(null)
  const updateMutation = useNetcupUpdateNickname()

  // Reset form when dialog opens
  useEffect(() => {
    if (open) {
      setNickname(currentNickname || '')
      setError(null)
    }
  }, [open, currentNickname])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError(null)

    const trimmedNickname = nickname.trim()

    // Nickname can be empty to clear it, but if set, validate length
    if (trimmedNickname.length > 50) {
      setError('Nickname must be 50 characters or less')
      return
    }

    try {
      await updateMutation.mutateAsync({ serverId, nickname: trimmedNickname })
      onOpenChange(false)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to update nickname')
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Tag className="h-5 w-5 text-muted-foreground" />
            Edit Nickname
          </DialogTitle>
          <DialogDescription>
            Change the nickname for {serverName || `server ${serverId}`}. This is a friendly label visible only in Netcup.
          </DialogDescription>
        </DialogHeader>

        <form onSubmit={handleSubmit} className="space-y-4 mt-4">
          <div className="space-y-2">
            <Label htmlFor="nickname">Nickname</Label>
            <Input
              id="nickname"
              type="text"
              placeholder="e.g., Production Server, Test Box"
              value={nickname}
              onChange={(e) => {
                setNickname(e.target.value)
                setError(null)
              }}
              disabled={updateMutation.isPending}
            />
            {error && (
              <p className="text-sm text-destructive">{error}</p>
            )}
            <p className="text-xs text-muted-foreground">
              Enter a friendly name for this server. Leave empty to clear the nickname.
            </p>
          </div>

          <DialogFooter className="gap-2 sm:gap-0 mt-6">
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
              disabled={updateMutation.isPending}
            >
              Cancel
            </Button>
            <Button
              type="submit"
              disabled={updateMutation.isPending}
            >
              {updateMutation.isPending ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Updating...
                </>
              ) : (
                'Update Nickname'
              )}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  )
}
