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

const DEFAULTS = { id: '', name: '', host: '', port: '8001', api_key: '', description: '', tags: [] }

const FIELDS = [
  { key: 'name',        label: 'Nom affiché',        placeholder: 'Mon VPS 1',    required: true,  type: 'text' },
  { key: 'id',          label: 'Identifiant unique', placeholder: 'vps-1',        required: true,  type: 'text',     hint: 'Sert de clé interne — ne peut plus être modifié ensuite.' },
  { 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: '••••••••',     required: true,  type: 'password' },
  { key: 'description', label: 'Description',        placeholder: 'Optionnel',    required: false, type: 'text' },
]

export default function AddVpsModal({ onSave, onClose }) {
  const [mode,   setMode]   = useState('manual')  // 'manual' | 'import'
  const [form,   setForm]   = useState(DEFAULTS)
  const [saving, setSaving] = useState(false)
  const [error,  setError]  = useState('')
  const [json,   setJson]   = useState('')
  const [jsonError, setJsonError] = useState('')

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

  const handleImportJson = () => {
    setJsonError('')
    try {
      const parsed = JSON.parse(json.trim())
      const required = ['id', 'name', 'host', 'port', 'api_key']
      const missing = required.filter(k => !parsed[k])
      if (missing.length > 0) {
        setJsonError(`Champs manquants : ${missing.join(', ')}`)
        return
      }
      setForm({
        id:          String(parsed.id),
        name:        String(parsed.name),
        host:        String(parsed.host),
        port:        String(parsed.port),
        api_key:     String(parsed.api_key),
        description: String(parsed.description ?? ''),
        tags:        Array.isArray(parsed.tags) ? parsed.tags : [],
      })
      setMode('manual')
    } catch {
      setJsonError('JSON invalide. Assurez-vous d\'avoir collé la config exportée.')
    }
  }

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

  return (
    <Modal
      size="sm"
      title="Ajouter un VPS"
      subtitle={mode === 'import' ? 'Importer une configuration exportée' : 'Saisie manuelle'}
      icon={<ServerCog size={16} className="text-indigo-400 flex-shrink-0" />}
      onClose={onClose}
      headerRight={
        <div className="flex rounded-lg overflow-hidden border border-gray-700 text-xs" role="group" aria-label="Mode d'ajout">
          <button
            type="button"
            onClick={() => setMode('manual')}
            aria-pressed={mode === 'manual'}
            className={`px-2.5 py-1 transition-colors ${mode === 'manual' ? 'bg-indigo-600 text-white' : 'text-gray-400 hover:bg-gray-800'}`}
          >
            Manuel
          </button>
          <button
            type="button"
            onClick={() => setMode('import')}
            aria-pressed={mode === 'import'}
            className={`px-2.5 py-1 transition-colors flex items-center gap-1 ${mode === 'import' ? 'bg-indigo-600 text-white' : 'text-gray-400 hover:bg-gray-800'}`}
          >
            <Upload size={11} />
            Importer
          </button>
        </div>
      }
    >
      {mode === 'import' ? (
        <div className="space-y-3">
          <p className="text-xs text-gray-400">
            Collez le JSON copié via le bouton <strong className="text-gray-300">Exporter</strong> d'une autre instance.
          </p>
          <textarea
            value={json}
            onChange={(e) => setJson(e.target.value)}
            rows={10}
            placeholder='{"id": "vps-1", "name": "Mon VPS", ...}'
            aria-label="Configuration JSON à importer"
            className={`${inputClass} text-xs font-mono resize-none`}
          />
          {jsonError && (
            <p className="text-xs text-red-400 bg-red-950/30 border border-red-900/40 rounded-lg px-3 py-2" role="alert">
              {jsonError}
            </p>
          )}
          <div className="flex gap-2">
            <Button variant="outline" size="lg" className="flex-1" onClick={onClose}>
              Annuler
            </Button>
            <Button variant="primary" size="lg" className="flex-1" icon={Upload} onClick={handleImportJson} disabled={!json.trim()}>
              Importer
            </Button>
          </div>
        </div>
      ) : (
        <form onSubmit={handleSubmit} className="space-y-3">
          {FIELDS.map(({ key, label, placeholder, required, type, hint }) => (
            <div key={key}>
              <label htmlFor={`add-${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={`add-${key}`}
                  value={form[key]}
                  onChange={set(key)}
                  placeholder={placeholder}
                  required={required}
                  autoComplete="off"
                />
              ) : (
                <input
                  id={`add-${key}`}
                  type={type}
                  value={form[key]}
                  onChange={set(key)}
                  placeholder={placeholder}
                  required={required}
                  className={inputClass}
                />
              )}
              {hint && <p className="text-[11px] text-gray-600 mt-1">{hint}</p>}
            </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…' : 'Ajouter'}
            </Button>
          </div>
        </form>
      )}
    </Modal>
  )
}
