import React from 'react'
import { createRoot } from 'react-dom/client'
import { getSettings, saveSettings, type ExtensionSettings } from '../lib/settings'
import './styles.css'

function SettingsPage(): JSX.Element {
  const [settings, setSettings] = React.useState<ExtensionSettings | null>(null)
  const [blacklistText, setBlacklistText] = React.useState('')
  const [saved, setSaved] = React.useState('')

  React.useEffect(() => {
    void getSettings().then((v) => {
      setSettings(v)
      setBlacklistText((v.blacklist || []).join('\n'))
    })
  }, [])

  const update = <K extends keyof ExtensionSettings>(key: K, value: ExtensionSettings[K]) => {
    setSettings((prev) => (prev ? { ...prev, [key]: value } : prev))
  }

  const onSave = async () => {
    if (!settings) return
    const normalized: ExtensionSettings = {
      ...settings,
      minFileSize: Number(settings.minFileSize || 0),
      motrixPort: Number(settings.motrixPort || 16800),
      blacklist: blacklistText
        .split('\n')
        .map((v) => v.trim())
        .filter(Boolean),
    }
    await saveSettings(normalized)
    setSettings(normalized)
    setSaved('Saved')
    window.setTimeout(() => setSaved(''), 1500)
  }

  if (!settings) return <div className="wrap">Loading...</div>

  return (
    <div className="wrap">
      <h1>Gomdown Helper Settings</h1>

      <div className="grid">
        <section className="card">
          <label>RPC Secret</label>
          <input value={settings.motrixAPIkey} onChange={(e) => update('motrixAPIkey', e.target.value)} />

          <label>RPC Port</label>
          <input
            type="number"
            value={settings.motrixPort}
            onChange={(e) => update('motrixPort', Number(e.target.value || 16800))}
          />

          <label>Min file size (MB)</label>
          <input
            type="number"
            value={settings.minFileSize}
            onChange={(e) => update('minFileSize', Number(e.target.value || 0))}
          />

          <label>Blacklist (one per line)</label>
          <textarea rows={8} value={blacklistText} onChange={(e) => setBlacklistText(e.target.value)} />
        </section>

        <section className="card">
          <div className="row"><span>Extension enabled</span><input type="checkbox" checked={settings.extensionStatus} onChange={(e) => update('extensionStatus', e.target.checked)} /></div>
          <div className="row"><span>Enable notifications</span><input type="checkbox" checked={settings.enableNotifications} onChange={(e) => update('enableNotifications', e.target.checked)} /></div>
          <div className="row"><span>Use native host</span><input type="checkbox" checked={settings.useNativeHost} onChange={(e) => update('useNativeHost', e.target.checked)} /></div>
          <div className="row"><span>Activate app on download</span><input type="checkbox" checked={settings.activateAppOnDownload} onChange={(e) => update('activateAppOnDownload', e.target.checked)} /></div>
          <div className="row"><span>Hide browser download shelf</span><input type="checkbox" checked={settings.hideChromeBar} onChange={(e) => update('hideChromeBar', e.target.checked)} /></div>
          <div className="row"><span>Show context menu option</span><input type="checkbox" checked={settings.showContextOption} onChange={(e) => update('showContextOption', e.target.checked)} /></div>
          <div className="row"><span>Download fallback</span><input type="checkbox" checked={settings.downloadFallback} onChange={(e) => update('downloadFallback', e.target.checked)} /></div>
          <div className="row"><span>Dark mode</span><input type="checkbox" checked={settings.darkMode} onChange={(e) => update('darkMode', e.target.checked)} /></div>
          <div className="row"><span>Show only aria downloads</span><input type="checkbox" checked={settings.showOnlyAria} onChange={(e) => update('showOnlyAria', e.target.checked)} /></div>
        </section>
      </div>

      <div className="actions">
        <button onClick={onSave}>Save</button>
        <button className="ghost" onClick={() => window.close()}>Close</button>
      </div>
      <div>{saved}</div>
    </div>
  )
}

createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <SettingsPage />
  </React.StrictMode>
)
