import { useState, useCallback } from 'react'
import { upsertUserSetting } from '../../services/directiveApi'

interface DocumentSettingsProps {
  isOpen: boolean
  onClose: () => void
  enabled: boolean
  onToggle: (enabled: boolean) => void
}

export default function DocumentSettings({
  isOpen,
  onClose,
  enabled,
  onToggle,
}: DocumentSettingsProps) {
  const [saving, setSaving] = useState(false)

  const handleToggle = useCallback(async () => {
    const newValue = !enabled
    setSaving(true)
    try {
      // Update localStorage immediately for instant UI response
      localStorage.setItem('document_ui_enabled', JSON.stringify(newValue))
      onToggle(newValue)

      // Persist to backend
      await upsertUserSetting('document_ui_enabled', newValue)
    } catch (err) {
      console.error('Failed to save document UI setting:', err)
      // Revert on failure
      localStorage.setItem('document_ui_enabled', JSON.stringify(!newValue))
      onToggle(!newValue)
    } finally {
      setSaving(false)
    }
  }, [enabled, onToggle])

  if (!isOpen) return null

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="config-modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-header">
          <h2>Document UI Settings</h2>
          <button className="close-btn" onClick={onClose}>{'\u00D7'}</button>
        </div>

        <div className="modal-content">
          <div className="config-option">
            <label className="config-label" style={{ cursor: 'pointer' }}>
              <input
                type="checkbox"
                checked={enabled}
                onChange={handleToggle}
                disabled={saving}
                className="config-checkbox"
              />
              <span className="config-text">
                Enable Document UI (Experimental)
              </span>
            </label>
            <div className="config-description">
              Replace the directive management interface with an interactive
              document editor. This is a proof of concept.
            </div>
          </div>
        </div>

        <div className="modal-footer">
          <button className="modal-btn" onClick={onClose}>Close</button>
        </div>
      </div>
    </div>
  )
}
