// frontend/src/pages/settings/PublicFeaturesSettings.jsx

import { useState, useEffect } from 'react'
import api from '@/lib/api'
import { useToast } from '@/components/ui/Toast'
import PageHeader from '@/components/ui/PageHeader'
import Card from '@/components/ui/Card'
import Spinner from '@/components/ui/Spinner'

// ─── Feature definitions ────────────────────────────────────────────────────

const FEATURES = [
  {
    key:         'cloudflash_enabled',
    title:       'CloudFlash',
    description: 'Allows end-users to flash their own devices via USB directly from the browser. When disabled, the CloudFlash page is inaccessible and displays a maintenance message.',
    url:         '/cloudflash',
    icon: (
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" />
      </svg>
    ),
  },
]

// ─── Toggle switch ──────────────────────────────────────────────────────────

function ToggleSwitch({ enabled, onChange, disabled, id }) {
  return (
    <button
      type="button"
      id={id}
      role="switch"
      aria-checked={enabled}
      disabled={disabled}
      onClick={() => onChange(!enabled)}
      style={{
        flexShrink: 0,
        position: 'relative',
        display: 'inline-flex',
        width: '44px',
        height: '24px',
        borderRadius: 'var(--radius-full)',
        border: 'none',
        cursor: disabled ? 'not-allowed' : 'pointer',
        padding: 0,
        transition: 'background 0.2s',
        background: enabled
          ? 'var(--color-success)'
          : 'var(--color-bg-island)',
        boxShadow: enabled
          ? 'inset 0 1px 3px rgba(0,0,0,0.2), 0 0 0 1px var(--color-success)'
          : 'inset 0 1px 3px rgba(0,0,0,0.2), 0 0 0 1px var(--color-border-strong)',
        opacity: disabled ? 0.5 : 1,
      }}
    >
      <span
        style={{
          position: 'absolute',
          top: '3px',
          left: enabled ? '23px' : '3px',
          width: '18px',
          height: '18px',
          borderRadius: 'var(--radius-full)',
          background: 'white',
          transition: 'left 0.2s',
          boxShadow: '0 1px 4px rgba(0,0,0,0.3)',
        }}
        aria-hidden="true"
      />
    </button>
  )
}

// ─── Feature row ────────────────────────────────────────────────────────────

function FeatureRow({ feature, enabled, saving, onToggle }) {
  return (
    <div style={{
      display: 'flex',
      alignItems: 'flex-start',
      gap: 'var(--space-4)',
      padding: 'var(--space-5)',
      borderRadius: 'var(--radius-lg)',
      backgroundColor: 'var(--color-bg-surface)',
      border: `1px solid ${enabled ? 'rgba(74,222,128,0.2)' : 'var(--color-border)'}`,
      boxShadow: enabled ? '0 0 0 1px rgba(74,222,128,0.08)' : 'none',
      transition: 'border-color 0.2s, box-shadow 0.2s',
    }}>
      {/* Icon */}
      <div style={{
        width: '40px',
        height: '40px',
        flexShrink: 0,
        borderRadius: 'var(--radius-md)',
        backgroundColor: enabled ? 'var(--color-success-bg)' : 'var(--color-bg-elevated)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        color: enabled ? 'var(--color-success)' : 'var(--color-text-muted)',
        transition: 'background 0.2s, color 0.2s',
      }}>
        {feature.icon}
      </div>

      {/* Text */}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-2)', marginBottom: 'var(--space-1)' }}>
          <span style={{
            fontSize: 'var(--font-size-base)',
            fontWeight: 'var(--font-weight-semibold)',
            color: 'var(--color-text-primary)',
          }}>
            {feature.title}
          </span>
          <span style={{
            padding: '1px 8px',
            borderRadius: 'var(--radius-full)',
            fontSize: 'var(--font-size-xs)',
            fontWeight: 'var(--font-weight-semibold)',
            backgroundColor: enabled ? 'var(--color-success-bg)' : 'var(--color-bg-island)',
            color: enabled ? 'var(--color-success)' : 'var(--color-text-muted)',
            transition: 'background 0.2s, color 0.2s',
          }}>
            {enabled ? 'Live' : 'Disabled'}
          </span>
        </div>
        <p style={{
          fontSize: 'var(--font-size-sm)',
          color: 'var(--color-text-muted)',
          lineHeight: 1.5,
          marginBottom: feature.url ? 'var(--space-2)' : 0,
        }}>
          {feature.description}
        </p>
        {feature.url && (
          <span style={{
            fontFamily: 'var(--font-family-mono)',
            fontSize: 'var(--font-size-xs)',
            color: 'var(--color-text-accent)',
          }}>
            {feature.url}
          </span>
        )}
      </div>

      {/* Toggle */}
      <div style={{ paddingTop: '2px' }}>
        <ToggleSwitch
          id={`toggle-${feature.key}`}
          enabled={enabled}
          onChange={onToggle}
          disabled={saving}
        />
      </div>
    </div>
  )
}

// ─── Main ─────────────────────────────────────────────────────────────────

export default function PublicFeaturesSettings() {
  const { toast } = useToast()

  const [settings, setSettings] = useState(null)
  const [loading,  setLoading]  = useState(true)
  const [saving,   setSaving]   = useState(false)

  useEffect(() => {
    api.get('/settings/public-features')
      .then(setSettings)
      .catch((e) => toast.danger('Failed to load settings', e.message))
      .finally(() => setLoading(false))
  }, [])

  const handleToggle = async (key, value) => {
    setSaving(true)
    try {
      const updated = await api.put('/settings/public-features', { [key]: value })
      setSettings(updated)
      toast.success('Settings saved', `${key.replace(/_/g, ' ')} has been ${value ? 'enabled' : 'disabled'}.`)
    } catch (e) {
      toast.danger('Failed to save', e.message)
    } finally {
      setSaving(false)
    }
  }

  return (
    <div className="page-wrapper page-wrapper--centered" style={{ '--page-content-max-width': 'var(--content-max-width-md)' }}>
      <PageHeader
        title="Public Features"
        subtitle="Control which public-facing pages are accessible to end-users without requiring a login."
      />

      {loading ? (
        <div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-12)' }}>
          <Spinner size="lg" />
        </div>
      ) : settings ? (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
          {FEATURES.map((feature) => (
            <FeatureRow
              key={feature.key}
              feature={feature}
              enabled={!!settings[feature.key]}
              saving={saving}
              onToggle={(val) => handleToggle(feature.key, val)}
            />
          ))}
        </div>
      ) : (
        <Card variant="flat">
          <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', textAlign: 'center', padding: 'var(--space-6)' }}>
            No settings available.
          </p>
        </Card>
      )}
    </div>
  )
}
