import React, { CSSProperties } from 'react'
import { CheckboxControl, Tooltip, Icon } from '@wordpress/components'
import { __ } from '@wordpress/i18n'
import { SettingsObject, SettingsSchemaObject } from '../types/types'

interface SettingsFieldProps {
  keyName: string
  setting: SettingsSchemaObject
  settings: SettingsObject
  effectiveMode: string | boolean
  effectiveSecondaryBehavior: string | boolean
  handleSettingsChange: (key: string, value: any) => void
}

const SettingsField: React.FC<SettingsFieldProps> = ({
  keyName,
  setting,
  settings,
  effectiveMode,
  effectiveSecondaryBehavior,
  handleSettingsChange
}) => {
  const value = settings[keyName] !== undefined ? settings[keyName] : setting.default
  const modeKey = typeof effectiveMode === 'boolean' ? String(effectiveMode) : effectiveMode
  const showLabel = setting.type !== 'checkbox'
  const dynamicLabel = typeof setting.label === 'object' ? setting.label[modeKey] || setting.label['auto'] : setting.label
  const dynamicDesc = typeof setting.desc === 'object' ? setting.desc[modeKey] || setting.desc['auto'] : setting.desc

  const tooltipStyle: CSSProperties = {
    marginRight: '10px',
    maxWidth: '245px',
    whiteSpace: 'normal',
    wordWrap: 'break-word',
    textAlign: 'left',
  }

  return (
    <div key={keyName}>
      {showLabel && (
        <label htmlFor={keyName} style={{ display: 'flex', alignItems: 'center', fontWeight: '500', marginBottom: '5px' }}>
          {dynamicLabel}

          {dynamicDesc && (
            <Tooltip text={dynamicDesc} {...({ style: tooltipStyle })}>
              <span style={{ marginLeft: '5px', cursor: 'help', color: '#999' }}>
                <Icon icon="editor-help" />
              </span>
            </Tooltip>
          )}
        </label>
      )}

      {setting.type === 'checkbox' && (
        <div style={{
          display: 'flex',
          alignItems: 'center'
        }}>
          <CheckboxControl
            key={keyName}
            label={dynamicLabel}
            checked={!!value}
            onChange={(val) => handleSettingsChange(keyName, val)}
          />
          {dynamicDesc && (
            <Tooltip text={dynamicDesc} {...({ style: tooltipStyle })}>
              <span style={{ marginBottom: '8px', marginLeft: '5px', cursor: 'help', color: '#999' }}>
                <Icon icon="editor-help" />
              </span>
            </Tooltip>
          )}
        </div>
      )}

      {setting.type === 'select' && (
        <select
          id={keyName}
          value={String(value)}
          onChange={(e) => handleSettingsChange(keyName, e.target.value)}
          style={{ width: '100%', padding: '5px' }}
        >
          {Object.entries(setting.options ?? {}).map(([optionValue, label]) => (
            <option key={optionValue} value={optionValue}>
              {label}
            </option>
          ))}
        </select>
      )}

      {setting.type === 'textarea' && (
        <>
          <textarea
            id={keyName}
            value={typeof value === 'string' ? value : ""}
            onChange={(e) => handleSettingsChange(keyName, e.target.value)}
            rows={5}
            style={{ width: '100%', padding: '5px' }}
          />

          {/* Show warning if the textarea contents look like a URL */}
          {(keyName === 'critical_css' || keyName === 'manual_secondary_css') && typeof value === 'string' && (() => {
            const raw = value as string
            // Minimal check: left-trim, take first 10 chars, and test for prefixes.
            const firstTen = raw.replace(/^\s+/, '').slice(0, 10)
            const looksLikeUrl = (firstTen.startsWith('http://') || firstTen.startsWith('https://') || (firstTen.startsWith('/') && !firstTen.startsWith('/*')))
            return looksLikeUrl ? (
              <div style={{ marginTop: '8px', padding: '8px', background: '#fff3cd', border: '1px solid #ffeeba', borderRadius: '4px' }}>
                <div style={{ fontWeight: 600, marginBottom: '6px' }}>{__('It looks like you pasted a URL.', 'easy-critical-css')}</div>
                <div style={{ marginBottom: '6px' }}>{__('Open that URL, copy the stylesheet contents, and paste the CSS here. Do not paste the URL itself. Pasting a URL can break your site when used as CSS.', 'easy-critical-css')}</div>
                <div style={{ marginBottom: '6px' }}>
                  <a href="https://criticalcss.net/docs/" target="_blank" rel="noopener noreferrer">{__('View help docs', 'easy-critical-css')}</a>
                </div>
              </div>
            ) : null
          })()}
        </>
      )}

      {setting.type === 'text' && (
        <input
          id={keyName}
          type='text'
          value={typeof value === 'string' ? value : ''}
          onChange={(e) => handleSettingsChange(keyName, e.target.value)}
          style={{ width: '100%', padding: '5px' }}
        />
      )}
    </div>
  )
}

export default SettingsField
