import { useState, useEffect, useCallback } from 'react'
import { fetchAllStatus, containerAction, addVps, deleteVps, fetchLogs, authStatus, getToken, setToken, composeUpdate, updateVps, updateAgent, exportVps } from './api/client'
import Header        from './components/Header'
import VpsCard       from './components/VpsCard'
import LogsModal     from './components/LogsModal'
import AddVpsModal   from './components/AddVpsModal'
import EditVpsModal  from './components/EditVpsModal'
import StatsModal    from './components/StatsModal'
import LoginPage     from './components/LoginPage'
import ProfilePage   from './components/ProfilePage'
import AdminPage     from './components/AdminPage'

const INTERVAL_OPTIONS = [
  { label: '10 s',  value: 10_000 },
  { label: '30 s',  value: 30_000 },
  { label: '1 min', value: 60_000 },
  { label: '2 min', value: 120_000 },
  { label: '5 min', value: 300_000 },
  { label: 'Off',   value: 0 },
]

export default function App() {
  const [token,       setTokenState]  = useState(() => getToken())
  const [username,    setUsername]    = useState(null)
  const [role,        setRole]        = useState(null)
  const [page,        setPage]        = useState('main') // 'main' | 'profile' | 'admin'
  const [isFirstUser, setIsFirstUser] = useState(false)
  const [authChecked, setAuthChecked] = useState(false)

  const [vpsList,     setVpsList]     = useState([])
  const [loading,     setLoading]     = useState(true)
  const [refreshing,  setRefreshing]  = useState(false)
  const [error,       setError]       = useState(null)
  const [lastUpdate,  setLastUpdate]  = useState(null)
  const [logsModal,   setLogsModal]   = useState(null)
  const [logsContent, setLogsContent] = useState('')
  const [logsLoading, setLogsLoading] = useState(false)
  const [showAddVps,  setShowAddVps]  = useState(false)
  const [editVps,     setEditVps]     = useState(null)   // objet vps à éditer
  const [refreshInterval, setRefreshInterval] = useState(() => {
    const stored = localStorage.getItem('refreshInterval')
    return stored ? parseInt(stored, 10) : 30_000
  })

  const handleIntervalChange = (val) => {
    setRefreshInterval(val)
    localStorage.setItem('refreshInterval', val)
  }

  const [updateModal,   setUpdateModal]   = useState(null)   // { vpsId, project }
  const [updateContent, setUpdateContent] = useState('')
  const [updateLoading, setUpdateLoading] = useState(false)

  const [statsModal,    setStatsModal]    = useState(null)   // { vpsId, vpsName }

  // Vérifie si des utilisateurs existent (pour afficher login ou register)
  useEffect(() => {
    authStatus()
      .then(({ has_users }) => setIsFirstUser(!has_users))
      .catch(() => setIsFirstUser(false))
      .finally(() => setAuthChecked(true))
  }, [])

  // Écoute l'événement d'expiration de token émis par client.js
  useEffect(() => {
    const onExpired = () => {
      setToken(null)
      setTokenState(null)
      setUsername(null)
      setRole(null)
      setPage('main')
    }
    window.addEventListener('auth:expired', onExpired)
    return () => window.removeEventListener('auth:expired', onExpired)
  }, [])

  const handleAuthenticated = (accessToken, role, user) => {
    setToken(accessToken)
    setTokenState(accessToken)
    try {
      const payload = JSON.parse(atob(accessToken.split('.')[1]))
      setUsername(payload.sub)
      setRole(payload.role ?? role ?? 'user')
    } catch {
      setUsername(user ?? 'user')
      setRole(role ?? 'user')
    }
  }

  const handleLogout = () => {
    setToken(null)
    setTokenState(null)
    setUsername(null)
    setRole(null)
    setPage('main')
    setVpsList([])
    setLoading(true)
  }

  const refresh = useCallback(async (showSpinner = false) => {
    if (showSpinner) setRefreshing(true)
    try {
      const data = await fetchAllStatus()
      setVpsList(data)
      setLastUpdate(new Date())
      setError(null)
    } catch (e) {
      setError(e.message)
    } finally {
      setLoading(false)
      setRefreshing(false)
    }
  }, [])

  useEffect(() => {
    if (!token) return
    refresh()
    if (!refreshInterval) return
    const id = setInterval(() => refresh(), refreshInterval)
    return () => clearInterval(id)
  }, [refresh, token, refreshInterval])

  // Extrait le username et le rôle du token stocké au rechargement de page
  useEffect(() => {
    if (token && !username) {
      try {
        const payload = JSON.parse(atob(token.split('.')[1]))
        setUsername(payload.sub)
        setRole(payload.role ?? 'user')
      } catch { /* ignore */ }
    }
  }, [token, username])

  const openLogs = async (vpsId, containerId, name) => {
    setLogsModal({ vpsId, containerId, name })
    setLogsLoading(true)
    setLogsContent('')
    try {
      const data = await fetchLogs(vpsId, containerId)
      setLogsContent(data.logs)
    } catch (e) {
      setLogsContent(`Erreur lors de la récupération des logs :\n${e.message}`)
    } finally {
      setLogsLoading(false)
    }
  }

  const handleAction = async (vpsId, containerId, action) => {
    await containerAction(vpsId, containerId, action)
    await refresh()
  }

  const handleUpdate = async (vpsId, project) => {
    setUpdateModal({ vpsId, project })
    setUpdateLoading(true)
    setUpdateContent('')
    try {
      const data = await composeUpdate(vpsId, project)
      setUpdateContent(data.output || '(aucune sortie)')
    } catch (e) {
      setUpdateContent(`Erreur lors de la mise à jour :\n${e.message}`)
    } finally {
      setUpdateLoading(false)
      await refresh()
    }
  }

  const handleUpdateAgent = async (vpsId) => {
    setUpdateModal({ vpsId, project: 'agent' })
    setUpdateLoading(true)
    setUpdateContent('Lancement de la mise à jour de l\'agent…\n')
    try {
      await updateAgent(vpsId)
      setUpdateContent('Mise à jour lancée. L\'agent va redémarrer dans quelques secondes.\nActualisez dans un moment pour vérifier la nouvelle version.')
    } catch (e) {
      setUpdateContent(`Erreur lors de la mise à jour de l'agent :\n${e.message}`)
    } finally {
      setUpdateLoading(false)
      setTimeout(() => refresh(), 8000)
    }
  }

  const handleAddVps = async (formData) => {
    await addVps(formData)
    setShowAddVps(false)
    await refresh(true)
  }

  const handleDeleteVps = async (vpsId) => {
    if (!window.confirm('Supprimer ce VPS de la configuration ?')) return
    await deleteVps(vpsId)
    await refresh(true)
  }

  const handleEditVps = async (vpsId, data) => {
    await updateVps(vpsId, data)
    setEditVps(null)
    await refresh(true)
  }

  const handleExportVps = async (vpsId) => {
    const config = await exportVps(vpsId)
    await navigator.clipboard.writeText(JSON.stringify(config, null, 2))
  }

  // Attente vérification auth
  if (!authChecked) return null

  // Pas de token → login / register
  if (!token) {
    return (
      <LoginPage
        isFirstUser={isFirstUser}
        onAuthenticated={handleAuthenticated}
      />
    )
  }

  // Statistiques globales
  const totalOnline     = vpsList.filter(v => v.online).length
  const totalContainers = vpsList.reduce((acc, v) => acc + v.containers.length, 0)
  const totalRunning    = vpsList.reduce((acc, v) => acc + v.containers.filter(c => c.status === 'running').length, 0)

  // ─── Pages profil / admin ───────────────────────────────────────────────
  if (page === 'profile') {
    return <ProfilePage username={username} onBack={() => setPage('main')} />
  }

  if (page === 'admin') {
    return <AdminPage onBack={() => setPage('main')} />
  }

  return (
    <div className="min-h-screen bg-gray-950 text-gray-100">
      <Header
        lastUpdate={lastUpdate}
        onRefresh={() => refresh(true)}
        onAddVps={() => setShowAddVps(true)}
        refreshing={refreshing}
        username={username}
        role={role}
        onLogout={handleLogout}
        onProfile={() => setPage('profile')}
        onAdmin={() => setPage('admin')}
        refreshInterval={refreshInterval}
        onIntervalChange={handleIntervalChange}
        intervalOptions={INTERVAL_OPTIONS}
      />

      <main className="max-w-7xl mx-auto px-4 py-8">

        {/* Barre d'erreur backend */}
        {error && (
          <div className="mb-6 bg-red-950/40 border border-red-800/50 rounded-xl px-4 py-3 text-sm text-red-300">
            Impossible de joindre le backend : <span className="font-mono">{error}</span>
          </div>
        )}

        {/* Stats globales */}
        {!loading && vpsList.length > 0 && (
          <div className="grid grid-cols-3 gap-4 mb-8">
            {[
              { label: 'VPS en ligne',       value: `${totalOnline}/${vpsList.length}`,  color: 'text-emerald-400' },
              { label: 'Conteneurs actifs',  value: `${totalRunning}/${totalContainers}`, color: 'text-indigo-400' },
              { label: 'Actualisation auto', value: INTERVAL_OPTIONS.find(o => o.value === refreshInterval)?.label ?? 'Off', color: 'text-gray-400' },
            ].map(({ label, value, color }) => (
              <div key={label} className="bg-gray-900 border border-gray-800 rounded-xl px-4 py-3">
                <p className={`text-2xl font-bold ${color}`}>{value}</p>
                <p className="text-xs text-gray-500 mt-0.5">{label}</p>
              </div>
            ))}
          </div>
        )}

        {/* Chargement initial */}
        {loading && (
          <div className="text-center py-24 text-gray-600">
            <svg className="w-8 h-8 animate-spin mx-auto mb-3 text-indigo-500" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
            </svg>
            Chargement…
          </div>
        )}

        {/* Aucun VPS */}
        {!loading && vpsList.length === 0 && !error && (
          <div className="text-center py-24 text-gray-600">
            <p className="text-lg font-medium text-gray-500">Aucun VPS configuré</p>
            <p className="text-sm mt-1">Cliquez sur <strong className="text-gray-400">Ajouter un VPS</strong> pour commencer.</p>
            <button
              onClick={() => setShowAddVps(true)}
              className="mt-6 px-4 py-2 rounded-xl bg-indigo-600 hover:bg-indigo-500 text-sm transition-colors"
            >
              Ajouter un VPS
            </button>
          </div>
        )}

        {/* Grille de VPS */}
        {!loading && vpsList.length > 0 && (
          <div className="grid gap-5 lg:grid-cols-2">
            {vpsList.map(vps => (
              <VpsCard
                key={vps.id}
                vps={vps}
                onAction={handleAction}
                onLogs={openLogs}
                onDelete={handleDeleteVps}
                onUpdate={handleUpdate}
                onEdit={setEditVps}
                onStats={(vpsId, vpsName) => setStatsModal({ vpsId, vpsName })}
                onUpdateAgent={handleUpdateAgent}
                onExport={handleExportVps}
              />
            ))}
          </div>
        )}
      </main>

      {/* Modal logs */}
      {logsModal && (
        <LogsModal
          name={logsModal.name}
          logs={logsContent}
          loading={logsLoading}
          onClose={() => setLogsModal(null)}
        />
      )}

      {/* Modal mise à jour compose */}
      {updateModal && (
        <LogsModal
          name={`🔄 Update — ${updateModal.project}`}
          logs={updateContent}
          loading={updateLoading}
          onClose={() => setUpdateModal(null)}
        />
      )}

      {/* Modal ajout VPS */}
      {showAddVps && (
        <AddVpsModal
          onSave={handleAddVps}
          onClose={() => setShowAddVps(false)}
        />
      )}

      {/* Modal édition VPS */}
      {editVps && (
        <EditVpsModal
          vps={editVps}
          onSave={handleEditVps}
          onClose={() => setEditVps(null)}
        />
      )}

      {/* Modal statistiques */}
      {statsModal && (
        <StatsModal
          vpsId={statsModal.vpsId}
          vpsName={statsModal.vpsName}
          onClose={() => setStatsModal(null)}
        />
      )}
    </div>
  )
}
