import { useEffect, useState } from 'react'
import { Save } from 'lucide-react'
import { getSettings, saveSettings, type AppSetting } from '../api'

const SETTING_LABELS: Record<string, { label: string; hint: string; secret?: boolean }> = {
  forecasting_api_key: {
    label: 'Forecasting API Key',
    hint: 'API key for the Forecasting app public API. Create one in Forecasting → Settings → API Keys.',
    secret: true,
  },
  forecasting_url: {
    label: 'Forecasting URL',
    hint: 'Internal URL for the Forecasting backend (e.g. http://10.10.10.113:3080). Leave blank to use the default.',
  },
}

export function SettingsPage() {
  const [settings, setSettings]   = useState<AppSetting[]>([])
  const [values, setValues]       = useState<Record<string, string>>({})
  const [loading, setLoading]     = useState(true)
  const [saving, setSaving]       = useState(false)
  const [saved, setSaved]         = useState(false)
  const [error, setError]         = useState<string | null>(null)
  const [revealed, setRevealed]   = useState<Record<string, boolean>>({})

  useEffect(() => {
    getSettings()
      .then(({ settings: rows }) => {
        setSettings(rows)
        const v: Record<string, string> = {}
        for (const r of rows) v[r.key] = r.value
        setValues(v)
      })
      .catch(e => setError(e.message))
      .finally(() => setLoading(false))
  }, [])

  async function handleSave() {
    setSaving(true); setSaved(false); setError(null)
    try {
      await saveSettings(Object.entries(values).map(([key, value]) => ({ key, value })))
      setSaved(true)
      setTimeout(() => setSaved(false), 3000)
    } catch (e) {
      setError((e as Error).message)
    } finally {
      setSaving(false)
    }
  }

  if (loading) return <div className="df-loading"><div className="df-spinner" /></div>

  return (
    <div className="settings-page">
      <div className="settings-header">
        <h1>Reports Settings</h1>
        <p>These settings are stored in the database and override environment variables.</p>
      </div>

      <div className="settings-body">
        {settings.map(s => {
          const meta = SETTING_LABELS[s.key] ?? { label: s.key, hint: '' }
          const isSecret = meta.secret
          const isRevealed = revealed[s.key]
          return (
            <div key={s.key} className="setting-row">
              <label className="setting-label">
                {meta.label}
                {meta.hint && <span className="setting-hint">{meta.hint}</span>}
              </label>
              <div className="setting-input-wrap">
                <input
                  type={isSecret && !isRevealed ? 'password' : 'text'}
                  value={values[s.key] ?? ''}
                  placeholder={isSecret ? 'fk_…' : 'http://10.10.10.113:3080'}
                  onChange={e => setValues(v => ({ ...v, [s.key]: e.target.value }))}
                  className="setting-input"
                  autoComplete="off"
                  spellCheck={false}
                />
                {isSecret && (
                  <button
                    type="button"
                    className="setting-reveal-btn"
                    onClick={() => setRevealed(r => ({ ...r, [s.key]: !r[s.key] }))}
                  >
                    {isRevealed ? 'Hide' : 'Show'}
                  </button>
                )}
              </div>
              {s.updated_at && (
                <span className="setting-updated">
                  Last saved: {new Date(s.updated_at).toLocaleString('en-GB')}
                </span>
              )}
            </div>
          )
        })}

        <div className="settings-actions">
          {error && <span className="df-error-inline">{error}</span>}
          {saved && <span className="setting-saved">Saved ✓</span>}
          <button className="btn-run" onClick={handleSave} disabled={saving}>
            <Save size={13} strokeWidth={1.75} />
            {saving ? 'Saving…' : 'Save Settings'}
          </button>
        </div>
      </div>
    </div>
  )
}
