import React from 'react'
import { registerPlugin } from '@wordpress/plugins'
import { PluginDocumentSettingPanel } from '@wordpress/editor'
import { useSelect } from '@wordpress/data'
import { __ } from '@wordpress/i18n'
import StatusIndicator from './components/statusIndicator'
import GenerateButton from './components/generateButton'
import SettingsPanel from './components/settingsPanel'
import { useSettings } from './hooks/useSettings'
import { useStatus } from './hooks/useStatus'
import { usePostSaving } from './hooks/usePostSaving'
import { useEffectiveSettings } from './hooks/useEffectiveSettings'
import { useSettingsVisibility } from './hooks/useSettingsVisibility'

const { settingsSchema, settings: initialSettings, mode, secondaryBehavior } = eccSettings

const CriticalCSSSidebar: React.FC = () => {
  const postId = useSelect((select: any) =>
    select('core/editor').getCurrentPostId(),
    []
  )

  const { settings, updateSetting } = useSettings(settingsSchema, initialSettings, postId)
  const { status, loading, fetchStatus } = useStatus(postId, settings.activate_critical_css)

  usePostSaving(postId, settings)

  const { effectiveMode, effectiveSecondaryBehavior } = useEffectiveSettings(settings, mode, secondaryBehavior)
  const { settingsVisible, setSettingsVisible } = useSettingsVisibility(effectiveMode)

  return (
    <PluginDocumentSettingPanel name='easy-critical-css-sidebar' title='Easy Critical CSS' className='easy-critical-css-panel'>
      {effectiveMode !== 'manual' && (
        <>
          <StatusIndicator status={status} loading={loading} fetchStatus={fetchStatus} />
          <GenerateButton postId={postId} fetchStatus={fetchStatus} status={status} activate_critical_css={settings.activate_critical_css} />
        </>
      )}

      <SettingsPanel
        settingsSchema={settingsSchema}
        settings={settings}
        effectiveMode={effectiveMode}
        effectiveSecondaryBehavior={effectiveSecondaryBehavior}
        settingsVisible={settingsVisible}
        setSettingsVisible={setSettingsVisible}
        handleSettingsChange={updateSetting}
      />
    </PluginDocumentSettingPanel>
  )
}

registerPlugin('critical-css-sidebar', { render: CriticalCSSSidebar })
