import { useState, useEffect, useRef } from 'react'
import { apiCall } from './apiHelper'

const installRequirement = ({ requirement }) => {
  const [loading, setLoading] = useState(true)
  const [data, setData] = useState(null)
  const [error, setError] = useState(null)
  const hasInstalled = useRef(false)

  useEffect(() => {
    if (!requirement || hasInstalled.current) {
      setLoading(false)
      return
    }

    const install = async () => {
      try {
        hasInstalled.current = true
        setLoading(true)
        setError(null)
        const result = await apiCall('installRequirement', 'POST', { requirement })
        setData(result)
        setLoading(false)
      } catch (err) {
        setError(err.message)
        setLoading(false)
      }
    }

    install()
  }, [])

  return { loading, data, error }
}

export default installRequirement

