import { useCallback, useEffect, useState } from 'react'
import {
  Boxes, FilePlus2, RefreshCw, Pencil, Rocket, ArrowLeft, AlertTriangle,
  FolderOpen, Terminal as TerminalIcon,
} from 'lucide-react'
import Modal from './ui/Modal'
import YamlEditor from './YamlEditor'
import { Button, inputClass, Skeleton, EmptyState } from './ui/controls'
import { useToast } from './ui/Toast'
import { fetchApps, fetchAppCompose, saveAppCompose, createApp, deployApp } from '../api/client'
import { formatBytes } from '../lib/format'

const APP_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/

const COMPOSE_FILENAMES = ['compose.yaml', 'compose.yml', 'docker-compose.yml', 'docker-compose.yaml']

const TEMPLATE = (name) => `services:
  ${name}:
    image: nginx:alpine
    container_name: ${name}
    restart: unless-stopped
    ports:
      - "8080:80"
    volumes:
      - ./data:/usr/share/nginx/html:ro
`

export default function AppsModal({ vps, onClose }) {
  const toast = useToast()

  const [view,    setView]    = useState('list')   // 'list' | 'editor' | 'create'
  const [apps,    setApps]    = useState([])
  const [loading, setLoading] = useState(true)
  const [error,   setError]   = useState(null)
  const [busy,    setBusy]    = useState(null)     // nom de l'app en cours de déploiement

  // Édition
  const [editing,  setEditing]  = useState(null)   // { name, file, path, original }
  const [content,  setContent]  = useState('')
  const [saving,   setSaving]   = useState(false)
  const [saveError, setSaveError] = useState(null)
  const [leaving,  setLeaving]  = useState(false)  // demande de sortie avec modifications

  // Création — le modèle suit le nom saisi tant que l'utilisateur n'a pas
  // touché à l'éditeur ; dès qu'il y écrit, on ne réécrit plus rien.
  const [newName,     setNewName]     = useState('')
  const [newFilename, setNewFilename] = useState('compose.yaml')
  const [newContent,  setNewContent]  = useState('')
  const [templateTouched, setTemplateTouched] = useState(false)

  // Sortie de déploiement
  const [output, setOutput] = useState(null)

  const dirty = view === 'editor' && editing !== null && content !== editing.original

  const load = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      setApps(await fetchApps(vps.id))
    } catch (e) {
      setError(e.message)
    } finally {
      setLoading(false)
    }
  }, [vps.id])

  useEffect(() => { load() }, [load])

  // ─── Actions ──────────────────────────────────────────────────────────────

  const openEditor = async (app) => {
    setBusy(app.name)
    setSaveError(null)
    setOutput(null)
    try {
      const data = await fetchAppCompose(vps.id, app.name)
      setEditing({ name: data.name, file: data.file, path: data.path, original: data.content })
      setContent(data.content)
      setView('editor')
    } catch (e) {
      toast.error(`Lecture de ${app.name} impossible : ${e.message}`)
    } finally {
      setBusy(null)
    }
  }

  const handleSave = async (deploy) => {
    setSaving(true)
    setSaveError(null)
    setOutput(null)
    try {
      const result = await saveAppCompose(vps.id, editing.name, content, deploy)
      setEditing(prev => ({ ...prev, original: content, file: result.file }))
      toast.success(
        deploy ? `${editing.name} enregistrée et déployée.` : `${editing.name} enregistrée.`
      )
      if (result.output) setOutput(result.output)
      load()
    } catch (e) {
      setSaveError(e.message)
    } finally {
      setSaving(false)
    }
  }

  const handleCreate = async (deploy) => {
    setSaving(true)
    setSaveError(null)
    setOutput(null)
    try {
      const result = await createApp(vps.id, {
        name: newName.trim(), content: newContent, filename: newFilename, deploy,
      })
      toast.success(`Application « ${result.name} » créée dans ${result.path}.`)
      if (result.output) setOutput(result.output)
      await load()
      setEditing({ name: result.name, file: result.file, path: result.path, original: newContent })
      setContent(newContent)
      setView('editor')
    } catch (e) {
      setSaveError(e.message)
    } finally {
      setSaving(false)
    }
  }

  const handleDeploy = async (app) => {
    setBusy(app.name)
    setOutput(null)
    try {
      const result = await deployApp(vps.id, app.name)
      toast.success(`${app.name} déployée.`)
      setOutput(result.output)
      load()
    } catch (e) {
      toast.error(`Déploiement de ${app.name} impossible : ${e.message}`)
    } finally {
      setBusy(null)
    }
  }

  const startCreate = () => {
    setNewName('')
    setNewFilename('compose.yaml')
    setNewContent(TEMPLATE('mon-app'))
    setTemplateTouched(false)
    setSaveError(null)
    setOutput(null)
    setView('create')
  }

  const handleNewName = (value) => {
    setNewName(value)
    const trimmed = value.trim()
    if (!templateTouched) setNewContent(TEMPLATE(APP_NAME_RE.test(trimmed) ? trimmed : 'mon-app'))
  }

  const handleNewContent = (value) => {
    setTemplateTouched(true)
    setNewContent(value)
  }

  const backToList = () => {
    if (dirty && !leaving) { setLeaving(true); return }
    setLeaving(false)
    setEditing(null)
    setSaveError(null)
    setView('list')
  }

  const requestClose = () => {
    if (dirty && !leaving) { setLeaving(true); return }
    onClose()
  }

  const nameValid = APP_NAME_RE.test(newName.trim())

  // ─── Rendu ────────────────────────────────────────────────────────────────

  const title = {
    list:   `Applications — ${vps.name}`,
    editor: editing ? `${editing.name} / ${editing.file}` : 'Édition',
    create: `Nouvelle application — ${vps.name}`,
  }[view]

  const subtitle = {
    list:   `Fichiers compose sous /home sur ${vps.host}`,
    editor: editing?.path,
    create: `Créé dans /home/${newName.trim() || '<nom>'}/${newFilename}`,
  }[view]

  return (
    <Modal
      size="xl"
      title={title}
      subtitle={subtitle}
      icon={<Boxes size={16} className="text-indigo-400 flex-shrink-0" />}
      onClose={requestClose}
      // Tab sert à indenter le YAML ; Échap ne doit pas jeter des modifications.
      trapTab={false}
      closeOnEscape={!dirty}
      bodyClassName="flex flex-col overflow-hidden p-0"
      headerRight={view === 'list' && (
        <>
          <Button variant="ghost" size="sm" icon={RefreshCw} onClick={load} disabled={loading}>
            <span className="hidden sm:inline">Actualiser</span>
          </Button>
          <Button variant="primary" size="sm" icon={FilePlus2} onClick={startCreate}>
            <span className="hidden sm:inline">Nouvelle application</span>
          </Button>
        </>
      )}
      footer={
        <div className="flex flex-wrap items-center justify-between gap-3">
          {leaving ? (
            <>
              <p className="text-xs text-orange-300 flex items-center gap-1.5">
                <AlertTriangle size={13} />
                Modifications non enregistrées. Quitter sans enregistrer ?
              </p>
              <div className="flex gap-2">
                <Button variant="outline" size="sm" onClick={() => setLeaving(false)}>Rester</Button>
                <Button variant="danger" size="sm" onClick={() => { setLeaving(false); setEditing(null); setView('list') }}>
                  Abandonner
                </Button>
              </div>
            </>
          ) : view === 'list' ? (
            <>
              <p className="text-[11px] text-gray-600">
                {apps.length} application{apps.length > 1 ? 's' : ''} détectée{apps.length > 1 ? 's' : ''}
              </p>
              <Button variant="outline" size="sm" onClick={onClose}>Fermer</Button>
            </>
          ) : view === 'editor' ? (
            <>
              <p className="text-[11px] text-gray-600">
                {dirty
                  ? 'Modifications non enregistrées · l\'ancienne version est sauvegardée en .bak'
                  : 'Validé par `docker compose config` avant écriture'}
              </p>
              <div className="flex gap-2">
                <Button variant="outline" size="sm" icon={ArrowLeft} onClick={backToList}>Retour</Button>
                <Button variant="secondary" size="sm" onClick={() => handleSave(false)} loading={saving} disabled={!dirty}>
                  Enregistrer
                </Button>
                <Button variant="primary" size="sm" icon={Rocket} onClick={() => handleSave(true)} loading={saving}>
                  Enregistrer et déployer
                </Button>
              </div>
            </>
          ) : (
            <>
              <p className="text-[11px] text-gray-600">
                Le dossier est créé s'il n'existe pas encore.
              </p>
              <div className="flex gap-2">
                <Button variant="outline" size="sm" icon={ArrowLeft} onClick={() => setView('list')}>Retour</Button>
                <Button variant="secondary" size="sm" onClick={() => handleCreate(false)} loading={saving} disabled={!nameValid}>
                  Créer
                </Button>
                <Button variant="primary" size="sm" icon={Rocket} onClick={() => handleCreate(true)} loading={saving} disabled={!nameValid}>
                  Créer et déployer
                </Button>
              </div>
            </>
          )}
        </div>
      }
    >
      {/* ── Liste ── */}
      {view === 'list' && (
        <div className="flex-1 overflow-y-auto p-4">
          {error && (
            <div role="alert" className="mb-4 bg-red-950/40 border border-red-800/50 rounded-lg px-3 py-2 text-xs text-red-300">
              {error}
            </div>
          )}

          {loading ? (
            <div className="space-y-2">
              {Array.from({ length: 4 }, (_, i) => <Skeleton key={i} className="h-14" />)}
            </div>
          ) : apps.length === 0 && !error ? (
            <EmptyState
              icon={FolderOpen}
              title="Aucune application détectée"
              description="Aucun dossier de /home ne contient de fichier compose. Créez-en une pour démarrer."
              action={<Button variant="primary" icon={FilePlus2} onClick={startCreate}>Nouvelle application</Button>}
            />
          ) : (
            <ul className="divide-y divide-gray-800/60">
              {apps.map(app => (
                <li key={app.name} className="flex flex-wrap items-center gap-3 py-3">
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center gap-2 flex-wrap">
                      <span className="text-sm font-medium text-gray-200">{app.name}</span>
                      <span className="text-[10px] font-mono text-gray-500 bg-gray-800 px-1.5 py-0.5 rounded">
                        {app.file}
                      </span>
                      {app.running_containers > 0 ? (
                        <span className="text-[10px] px-1.5 py-0.5 rounded-full bg-emerald-500/10 text-emerald-400">
                          {app.running_containers} conteneur{app.running_containers > 1 ? 's' : ''} actif{app.running_containers > 1 ? 's' : ''}
                        </span>
                      ) : (
                        <span className="text-[10px] px-1.5 py-0.5 rounded-full bg-gray-700/40 text-gray-500">
                          arrêtée
                        </span>
                      )}
                    </div>
                    <p className="text-xs text-gray-600 font-mono truncate mt-0.5">
                      {app.path} · {formatBytes(app.size)} · modifié le {new Date(app.modified).toLocaleString('fr-FR')}
                    </p>
                  </div>
                  <div className="flex items-center gap-2 flex-shrink-0">
                    <Button variant="secondary" size="sm" icon={Pencil}
                            onClick={() => openEditor(app)} loading={busy === app.name}>
                      Éditer
                    </Button>
                    <Button variant="outline" size="sm" icon={Rocket}
                            onClick={() => handleDeploy(app)} loading={busy === app.name}>
                      Déployer
                    </Button>
                  </div>
                </li>
              ))}
            </ul>
          )}

          {output && <DeployOutput output={output} onClear={() => setOutput(null)} />}
        </div>
      )}

      {/* ── Édition ── */}
      {view === 'editor' && editing && (
        <div className="flex-1 flex flex-col overflow-hidden">
          {saveError && (
            <div role="alert" className="m-4 mb-0 bg-red-950/40 border border-red-800/50 rounded-lg px-3 py-2 text-xs text-red-300 whitespace-pre-wrap font-mono max-h-32 overflow-y-auto">
              {saveError}
            </div>
          )}
          <div className="p-4 pb-0 flex-1 flex flex-col overflow-hidden">
            <YamlEditor value={content} onChange={setContent} disabled={saving} />
            {output && <DeployOutput output={output} onClear={() => setOutput(null)} />}
          </div>
        </div>
      )}

      {/* ── Création ── */}
      {view === 'create' && (
        <div className="flex-1 overflow-y-auto p-4 space-y-3">
          {saveError && (
            <div role="alert" className="bg-red-950/40 border border-red-800/50 rounded-lg px-3 py-2 text-xs text-red-300 whitespace-pre-wrap font-mono max-h-32 overflow-y-auto">
              {saveError}
            </div>
          )}

          <div className="flex flex-wrap gap-3">
            <div className="flex-1 min-w-[200px]">
              <label htmlFor="app-name" className="block text-xs text-gray-400 mb-1">
                Nom de l'application <span className="text-red-400" aria-hidden="true">*</span>
              </label>
              <input
                id="app-name"
                value={newName}
                onChange={e => handleNewName(e.target.value)}
                placeholder="mon-app"
                autoFocus
                className={inputClass}
              />
              <p className={`text-[11px] mt-1 ${newName && !nameValid ? 'text-red-400' : 'text-gray-600'}`}>
                {newName && !nameValid
                  ? 'Lettres, chiffres, point, tiret et souligné uniquement.'
                  : `Dossier créé : /home/${newName.trim() || '<nom>'}`}
              </p>
            </div>
            <div>
              <label htmlFor="app-filename" className="block text-xs text-gray-400 mb-1">Nom du fichier</label>
              <select
                id="app-filename"
                value={newFilename}
                onChange={e => setNewFilename(e.target.value)}
                className={inputClass}
              >
                {COMPOSE_FILENAMES.map(f => <option key={f} value={f}>{f}</option>)}
              </select>
            </div>
          </div>

          <YamlEditor value={newContent} onChange={handleNewContent} disabled={saving} height="h-[38vh]" />

          {output && <DeployOutput output={output} onClear={() => setOutput(null)} />}
        </div>
      )}
    </Modal>
  )
}

function DeployOutput({ output, onClear }) {
  return (
    <div className="mt-4">
      <div className="flex items-center justify-between mb-1.5">
        <span className="flex items-center gap-1.5 text-xs text-gray-400">
          <TerminalIcon size={12} className="text-indigo-400" />
          Sortie du déploiement
        </span>
        <button onClick={onClear} className="text-xs text-gray-500 hover:text-gray-300 transition-colors">
          Masquer
        </button>
      </div>
      <pre className="bg-gray-950 border border-gray-800 rounded-lg p-3 text-[11px] font-mono text-gray-300 whitespace-pre-wrap break-all max-h-48 overflow-y-auto">
        {output || '(aucune sortie)'}
      </pre>
    </div>
  )
}
