import { useEffect, useState } from 'react'
import { admin } from '../api/endpoints'
import { useSettings } from '../context/SettingsContext'
import { useToast } from '../context/ToastContext'
import { Card, Input, Toggle, Button, Select } from './ui'

export default function AdminSettings() {
  const { reload } = useSettings()
  const toast = useToast()
  const [s, setS] = useState(null)
  const [videos, setVideos] = useState([])
  const [busy, setBusy] = useState(false)

  useEffect(() => {
    admin.settings().then(setS).catch(() => {})
    admin.videos({ per_page: 100 }).then((r) => setVideos(r.data || [])).catch(() => {})
  }, [])

  if (!s) return <p className="text-gray-400">Loading settings…</p>

  const set = (k, v) => setS((prev) => ({ ...prev, [k]: v }))
  const bool = (k) => s[k] === '1' || s[k] === 1 || s[k] === true

  const save = async () => {
    setBusy(true)
    try {
      await admin.saveSettings(s)
      await reload()
      toast.success('Settings saved')
    } catch {
      toast.error('Could not save settings')
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-extrabold">Settings</h1>
        <Button onClick={save} disabled={busy}>
          {busy ? 'Saving…' : 'Save all'}
        </Button>
      </div>

      <Card title="Site">
        <div className="grid gap-4 sm:grid-cols-2">
          <Input label="Site name" value={s.site_name || ''} onChange={(e) => set('site_name', e.target.value)} />
          <Input label="Logo URL" value={s.logo_url || ''} onChange={(e) => set('logo_url', e.target.value)} />
          <label className="block">
            <span className="mb-1 block text-sm font-medium text-gray-600 dark:text-gray-300">Theme primary color</span>
            <div className="flex gap-2">
              <input type="color" value={s.theme_primary || '#6366f1'} onChange={(e) => set('theme_primary', e.target.value)} className="h-10 w-14 rounded-lg border border-gray-200 dark:border-gray-700" />
              <Input value={s.theme_primary || ''} onChange={(e) => set('theme_primary', e.target.value)} className="flex-1" />
            </div>
          </label>
        </div>
      </Card>

      <Card title="Channel (uploader shown on cards)">
        <div className="grid gap-4 sm:grid-cols-2">
          <Input label="Channel name" value={s.channel_name || ''} onChange={(e) => set('channel_name', e.target.value)} />
          <Input label="Channel avatar URL" value={s.channel_avatar || ''} onChange={(e) => set('channel_avatar', e.target.value)} />
        </div>
      </Card>

      <Card title="Marquee notice">
        <div className="space-y-4">
          <Toggle label="Enable marquee" checked={bool('marquee_enabled')} onChange={(v) => set('marquee_enabled', v ? '1' : '0')} />
          <Input label="Text (leave blank to hide)" value={s.marquee_text || ''} onChange={(e) => set('marquee_text', e.target.value)} />
          <div className="grid gap-4 sm:grid-cols-2">
            <Input label="Link (optional)" value={s.marquee_link || ''} onChange={(e) => set('marquee_link', e.target.value)} />
            <Input label="Speed (seconds per loop)" type="number" value={s.marquee_speed || ''} onChange={(e) => set('marquee_speed', e.target.value)} />
            <label className="block">
              <span className="mb-1 block text-sm font-medium text-gray-600 dark:text-gray-300">Background</span>
              <input type="color" value={s.marquee_bg || '#111827'} onChange={(e) => set('marquee_bg', e.target.value)} className="h-10 w-full rounded-lg border border-gray-200 dark:border-gray-700" />
            </label>
            <label className="block">
              <span className="mb-1 block text-sm font-medium text-gray-600 dark:text-gray-300">Text color</span>
              <input type="color" value={s.marquee_color || '#ffffff'} onChange={(e) => set('marquee_color', e.target.value)} className="h-10 w-full rounded-lg border border-gray-200 dark:border-gray-700" />
            </label>
          </div>
        </div>
      </Card>

      <Card title="Exclusive / Live featured item">
        <Select
          label="Featured video (blank = hide section)"
          value={s.exclusive_video_id || ''}
          onChange={(e) => set('exclusive_video_id', e.target.value)}
        >
          <option value="">— None —</option>
          {videos.map((v) => (
            <option key={v.id} value={v.id}>
              {v.title}
            </option>
          ))}
        </Select>
      </Card>

      <Card title="Ads configuration">
        <div className="grid gap-4 sm:grid-cols-2">
          <Input label="Grid ad frequency (1 ad per N videos)" type="number" value={s.ad_grid_frequency || ''} onChange={(e) => set('ad_grid_frequency', e.target.value)} />
          <Input label="In-player ad break interval (seconds, 60–300)" type="number" value={s.ad_break_interval || ''} onChange={(e) => set('ad_break_interval', e.target.value)} />
          <Toggle label="Randomize grid ad position" checked={bool('ad_grid_random')} onChange={(v) => set('ad_grid_random', v ? '1' : '0')} />
          <Toggle label="Enable in-player ad breaks globally" checked={bool('ad_break_enabled')} onChange={(v) => set('ad_break_enabled', v ? '1' : '0')} />
        </div>
      </Card>

      <div className="flex justify-end">
        <Button onClick={save} disabled={busy}>
          {busy ? 'Saving…' : 'Save all'}
        </Button>
      </div>
    </div>
  )
}
