import { useEffect, useState } from 'react'
import type { Nip95Config } from '@/lib/configStorageTypes'
import { Nip95ConfigView } from './view'
import { loadApis } from './controller'
import { createNip95ConfigViewProps } from './viewModel'

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

export function Nip95ConfigManager(props: Nip95ConfigManagerProps): React.ReactElement {
  const [apis, setApis] = useState<Nip95Config[]>([])
  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(() => {
    void loadApis({ setApis, setLoading, setError })
  }, [])

  const viewProps = createNip95ConfigViewProps({
    apis,
    loading,
    error,
    editingId,
    newUrl,
    showAddForm,
    draggedId,
    dragOverId,
    setApis,
    setError,
    setEditingId,
    setNewUrl,
    setShowAddForm,
    setDraggedId,
    setDragOverId,
    onConfigChange: props.onConfigChange,
  })

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