import { useEffect, useState } from 'react'
import type { RelayConfig } from '@/lib/configStorageTypes'
import { RelayManagerView } from './view'
import { initialLoadRelays } from './viewModel'
import { buildRelayManagerViewProps } from './viewProps'

export interface RelayManagerProps {
  onConfigChange?: () => void
}

export function RelayManager(props: RelayManagerProps): React.ReactElement {
  const [relays, setRelays] = useState<RelayConfig[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [editingId, setEditingId] = useState<string | null>(null)
  const [newUrl, setNewUrl] = useState('')
  const [showAddForm, setShowAddForm] = useState(false)
  const [draggedId, setDraggedId] = useState<string | null>(null)
  const [dragOverId, setDragOverId] = useState<string | null>(null)

  useEffect(() => {
    initialLoadRelays({ setRelays, setLoading, setError })
  }, [])

  const viewProps = buildRelayManagerViewProps({
    relays,
    loading,
    error,
    editingId,
    newUrl,
    showAddForm,
    draggedId,
    dragOverId,
    setRelays,
    setLoading,
    setError,
    setEditingId,
    setNewUrl,
    setShowAddForm,
    setDraggedId,
    setDragOverId,
    onConfigChange: props.onConfigChange,
  })

  return <RelayManagerView {...viewProps} />
}
