import React, { useState, useEffect } from 'react'
import './App.css'

import FirstPage from './pages/FirstPage'
import SettingsPage from './pages/SettingsPage'
import OnboardingPage from './pages/OnboardingPage'
import ReactLoader from './components/ReactLoader'

declare const ajaxurl: string
declare const wcbe_nonce: string

interface DataItem {
  name: string
  value: string
}

type PageName = 'firstPage' | 'onBoarding' | 'settingsPage' | 'loader'

const App: React.FC = () => {
  const [data, setData] = useState<DataItem[] | null>(null)
  const [page, setPage] = useState<PageName>('loader')

  useEffect(() => {
    const fetchData = async () => {
      try {
        // Create URLSearchParams for form data
        const formData = new URLSearchParams()
        formData.append('nonce', wcbe_nonce)
        formData.append('action', 'get_edgetag_options')

        const response = await fetch(ajaxurl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          },
          body: formData,
        })

        // Check if the response is ok
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }

        // Parse the JSON response
        const parsedData = (await response.json()) as DataItem[]

        if (Object.values(parsedData[0])[0].length > 0) {
          setPage('settingsPage')
        } else {
          setPage('firstPage')
        }

        setData(parsedData)
      } catch (error) {
        console.error(error)
      }
    }

    fetchData()
  }, [])

  const handleNavigation = (newPage: PageName) => {
    setPage(newPage)
  }

  const renderPage = () => {
    switch (page) {
      case 'settingsPage':
        return <SettingsPage data={data} />
      case 'onBoarding':
        return <OnboardingPage onNavigate={handleNavigation} />
      case 'firstPage':
        return <FirstPage onNavigate={handleNavigation} />
      default:
        return <ReactLoader />
    }
  }

  return renderPage()
}

export default App
