import React from 'react'
import { Button } from '@wordpress/components'
import { useSelect } from '@wordpress/data'
import { __ } from '@wordpress/i18n'
import SettingsField from './settingsField'
import { SettingsSchema, SettingsSchemaObject, SettingsObject } from '../types/types'
import { isManualMode, areBothManualFieldsFilled, buildGeneratorUrl } from '../hooks/useGeneratorButton'

interface SettingsPanelProps {
  settingsSchema: SettingsSchema
  settings: SettingsObject
  effectiveMode: string | boolean
  effectiveSecondaryBehavior: string | boolean
  settingsVisible: boolean
  setSettingsVisible: (visible: boolean) => void
  handleSettingsChange: (key: string, value: any) => void
  globalMode?: string
  pluginVersion?: string
  userEmail?: string
}

const isSettingVisible = (
  key: string,
  setting: SettingsSchemaObject,
  settings: SettingsObject,
  effectiveMode: string | boolean,
  effectiveSecondaryBehavior: string | boolean,
  globalMode?: string
) => {
  if (!setting.visible) return true

  for (const [dependency, expectedValue] of Object.entries(setting.visible)) {
    let actualValue = settings[dependency]

    if (dependency === 'critical_css_mode') {
      const modeValue = isManualMode(settings, globalMode || 'auto') ? 'manual' : 'auto'
      if (modeValue !== expectedValue) {
        return false
      }
    } else if (dependency === 'secondary_css_behavior' && (actualValue === 'default' ? effectiveSecondaryBehavior !== expectedValue : actualValue !== expectedValue)) {
      return false
    } else if (dependency !== 'secondary_css_behavior' && actualValue !== expectedValue) {
      return false
    }
  }

  return true
}

const SettingsPanel: React.FC<SettingsPanelProps> = ({
  settingsSchema,
  settings,
  effectiveMode,
  effectiveSecondaryBehavior,
  settingsVisible,
  setSettingsVisible,
  handleSettingsChange,
  globalMode,
  pluginVersion,
  userEmail
}) => {
  const visibleSettings = Object.entries(settingsSchema).filter(([key, setting]) =>
    isSettingVisible(key, setting, settings, effectiveMode, effectiveSecondaryBehavior, globalMode)
  )

  const postStatus = useSelect((select: any) =>
    select('core/editor').getCurrentPostAttribute('status'),
    []
  )

  const currentPermalink = useSelect((select: any) =>
    select('core/editor').getPermalink(),
    []
  )

  const shouldShowGeneratedCssButton = postStatus === 'publish' && 
    isManualMode(settings, globalMode || 'auto') && 
    !areBothManualFieldsFilled(settings) &&
    !!currentPermalink

  return (
    <>
      <Button
        type="button"
        aria-expanded={settingsVisible}
        className="components-button components-panel__body-toggle"
        style={{
          padding: '10px',
          background: '#f8f8f8',
          cursor: 'pointer',
          userSelect: 'none',
          marginTop: '15px',
        }}
        onClick={() => setSettingsVisible(!settingsVisible)}
      >
        {__('Settings', 'easy-critical-css')}
        <span aria-hidden="true">
          <svg
            viewBox="0 0 24 24"
            xmlns="http://www.w3.org/2000/svg"
            width="24"
            height="24"
            className="components-panel__arrow"
            aria-hidden="true"
            focusable="false"
          >
            {settingsVisible
              ? <path d="M6.5 12.4L12 8l5.5 4.4-.9 1.2L12 10l-4.5 3.6-1-1.2z"></path>
              : <path d="M17.5 11.6L12 16l-5.5-4.4.9-1.2L12 14l4.5-3.6 1 1.2z"></path>
            }
          </svg>
        </span>
      </Button>

      {settingsVisible && (
        <div style={{ marginTop: '10px' }}>
          {visibleSettings.map(([key, setting], index, array) => {
            const isLast = index === array.length - 1
            return (
              <React.Fragment key={key}>
                <div style={{ marginBottom: '15px' }}>
                  <SettingsField
                    keyName={key}
                    setting={setting}
                    settings={settings}
                    effectiveMode={effectiveMode}
                    effectiveSecondaryBehavior={effectiveSecondaryBehavior}
                    handleSettingsChange={handleSettingsChange}
                  />
                </div>
                {key === 'critical_css_mode' && shouldShowGeneratedCssButton && pluginVersion && currentPermalink && (
                  <div style={{ marginBottom: '15px' }}>
                    <Button
                      onClick={() => {
                        const url = buildGeneratorUrl(currentPermalink, pluginVersion, userEmail)
                        window.open(url, '_blank')
                      }}
                      variant='primary'
                      style={{ width: '100%', justifyContent: 'center' }}
                    >
                      {__('Get Generated Critical CSS', 'easy-critical-css')}
                    </Button>
                  </div>
                )}
              </React.Fragment>
            )
          })}
        </div>
      )}
    </>
  )
}

export default SettingsPanel
