import { useState } from 'react'
import { Pencil } from 'lucide-react'
import TagInput from './TagInput'
import Modal from './ui/Modal'
import { Button, inputClass, PasswordInput } from './ui/controls'

const FIELDS = [
  { key: 'name',        label: 'Nom affiché',    placeholder: 'Mon VPS 1',    required: true,  type: 'text' },
  { key: 'host',        label: 'IP ou hostname', placeholder: '192.168.1.10', required: true,  type: 'text' },
  { key: 'port',        label: 'Port agent',     placeholder: '8001',         required: true,  type: 'number' },
  { key: 'api_key',     label: 'Clé API agent',  placeholder: 'Laisser vide pour conserver la clé actuelle', required: false, type: 'password' },
  { key: 'description', label: 'Description',    placeholder: 'Optionnel',    required: false, type: 'text' },
]

export default function EditVpsModal({ vps, onSave, onClose }) {
  const [form, setForm] = useState({
    name:        vps.name        ?? '',
    host:        vps.host        ?? '',
    port:        String(vps.port ?? 8001),
    api_key:     '',
    description: vps.description ?? '',
    tags:        vps.tags        ?? [],
  })
  const [saving, setSaving] = useState(false)
  const [error,  setError]  = useState('')

  const set = (key) => (e) => setForm(f => ({ ...f, [key]: e.target.value }))

  const handleSubmit = async (e) => {
    e.preventDefault()
    setSaving(true)
    setError('')
    try {
      await onSave(vps.id, { ...form, port: parseInt(form.port, 10) })
    } catch (err) {
      setError(err.message)
      setSaving(false)
    }
  }

  return (
    <Modal
      size="sm"
      title="Modifier le VPS"
      subtitle={vps.id}
      icon={<Pencil size={16} className="text-indigo-400 flex-shrink-0" />}
      onClose={onClose}
    >
      <form onSubmit={handleSubmit} className="space-y-3">
        {FIELDS.map(({ key, label, placeholder, required, type }) => (
          <div key={key}>
            <label htmlFor={`edit-${key}`} className="block text-xs text-gray-400 mb-1">
              {label} {required && <span className="text-red-400" aria-hidden="true">*</span>}
            </label>
            {type === 'password' ? (
              <PasswordInput
                id={`edit-${key}`}
                value={form[key]}
                onChange={set(key)}
                placeholder={placeholder}
                required={required}
                autoComplete="off"
              />
            ) : (
              <input
                id={`edit-${key}`}
                type={type}
                value={form[key]}
                onChange={set(key)}
                placeholder={placeholder}
                required={required}
                className={inputClass}
              />
            )}
          </div>
        ))}

        {error && (
          <p className="text-xs text-red-400 bg-red-950/30 border border-red-900/40 rounded-lg px-3 py-2" role="alert">
            {error}
          </p>
        )}

        <div>
          <label className="block text-xs text-gray-400 mb-1">Tags</label>
          <TagInput tags={form.tags} onChange={tags => setForm(f => ({ ...f, tags }))} />
          <p className="text-[11px] text-gray-600 mt-1">Entrée ou virgule pour valider</p>
        </div>

        <div className="flex gap-2 pt-1">
          <Button type="button" variant="outline" size="lg" className="flex-1" onClick={onClose}>
            Annuler
          </Button>
          <Button type="submit" variant="primary" size="lg" className="flex-1" loading={saving}>
            {saving ? 'Enregistrement…' : 'Enregistrer'}
          </Button>
        </div>
      </form>
    </Modal>
  )
}
