import { useEffect, useRef, useState } from 'react'
import useConnectionStore from '../store/connectionStore'
import client from '../api/client'
import { useSSEContext } from '../context/SSEContext'

const RETRY_INTERVAL = 10_000  // 10s auto-retry while modal is open in Wait mode

export default function ConnectionLostModal() {
  const { status, setOnline, enterEmergency } = useConnectionStore()
  const { reconnect, fullRefresh } = useSSEContext()
  const [retrying, setRetrying] = useState(false)
  const retryRef = useRef(null)

  const isVisible = status === 'lost'

  async function tryReconnect() {
    setRetrying(true)
    try {
      await client.get('/api/system/health')
      // Server is back
      setOnline()
      reconnect()
      await fullRefresh()
    } catch {
      // Still down — stay in modal
    } finally {
      setRetrying(false)
    }
  }

  // Auto-retry every 10s while modal is open
  useEffect(() => {
    if (!isVisible) {
      clearInterval(retryRef.current)
      return
    }
    retryRef.current = setInterval(tryReconnect, RETRY_INTERVAL)
    return () => clearInterval(retryRef.current)
  }, [isVisible])

  if (!isVisible) return null

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 99999,
      background: 'rgba(0,0,0,0.75)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 24,
    }}>
      <div style={{
        background: '#1e293b',
        border: '2px solid #ef4444',
        borderRadius: 20,
        padding: '32px 28px',
        maxWidth: 400, width: '100%',
        textAlign: 'center',
        boxShadow: '0 24px 64px rgba(0,0,0,0.6)',
      }}>
        <div style={{ fontSize: 48, marginBottom: 16 }}>⚠️</div>

        <p style={{
          fontSize: 20, fontWeight: 700, color: '#f1f5f9',
          marginBottom: 10,
        }}>
          Χάθηκε η σύνδεση με τον Manager
        </p>

        <p style={{
          fontSize: 14, color: '#94a3b8', lineHeight: 1.6,
          marginBottom: 28,
        }}>
          Δεν μπορώ να φτάσω στον server.{'\n'}
          Περίμενε ή άνοιξε <strong style={{ color: '#fbbf24' }}>ΕΚΤΑΚΤΗ ΛΕΙΤΟΥΡΓΙΑ</strong>{'\n'}
          για να συνεχίσεις με τοπικά δεδομένα.
        </p>

        <div style={{
          display: 'flex', gap: 12, justifyContent: 'center',
        }}>
          <button
            onClick={enterEmergency}
            style={{
              flex: 1,
              height: 48, borderRadius: 12, border: 'none',
              background: '#dc2626', color: '#fff',
              fontSize: 15, fontWeight: 700,
              cursor: 'pointer',
            }}
          >
            EMERGENCY MODE
          </button>
        </div>

        <p style={{ fontSize: 11, color: '#475569', marginTop: 16 }}>
          Αυτόματη επανάληψη κάθε 10 δευτερόλεπτα
        </p>
      </div>
    </div>
  )
}
