import React, { useEffect, useState } from 'react'
import axios from 'axios'

const API = (path: string) => `${window.location.origin.replace(':5173', ':8000')}${path}`

type Policy = any

export function CrawlControls() {
  const [policy, setPolicy] = useState<Policy | null>(null)
  const [saving, setSaving] = useState(false)

  const load = async () => {
    const p = await axios.get(API('/crawl-policy')).then(r=>r.data)
    setPolicy(p)
  }
  useEffect(()=>{ load() },[])

  const update = (path: string[], value: any) => {
    setPolicy(prev => {
      if (!prev) return prev
      const next = structuredClone(prev)
      let obj: any = next
      for (let i=0;i<path.length-1;i++) obj = obj[path[i]]
      obj[path[path.length-1]] = value
      return next
    })
  }

  const save = async () => {
    if (!policy) return
    setSaving(true)
    try {
      await axios.patch(API('/crawl-policy'), policy)
    } finally { setSaving(false) }
  }

  if (!policy) return <section className="card p-6">Loading…</section>

  const g = policy.global
  const brokers = policy.brokers || {}

  return (
    <section className="card p-6">
      <div className="flex items-center justify-between">
        <h2 className="text-lg font-medium">Crawl Controls</h2>
        <button className="btn" disabled={saving} onClick={save}>{saving?'Saving…':'Save'}</button>
      </div>

      <div className="mt-6 grid md:grid-cols-2 gap-6">
        <div className="card p-4">
          <h3 className="font-medium mb-2">Global</h3>
          <label className="block text-sm text-gray-400">Mode</label>
          <select className="select" value={g.crawl_mode} onChange={e=>update(['global','crawl_mode'], e.target.value)}>
            <option value="all">All</option>
            <option value="per_hour">Per Hour</option>
            <option value="per_run">Per Run</option>
          </select>
          {g.crawl_mode==='per_hour' && (
            <div className="mt-2">
              <label className="block text-sm text-gray-400">Per-hour quota</label>
              <input className="input" type="number" value={g.per_hour_quota||0} onChange={e=>update(['global','per_hour_quota'], Number(e.target.value))} />
            </div>
          )}
          {g.crawl_mode==='per_run' && (
            <div className="mt-2">
              <label className="block text-sm text-gray-400">Per-run limit</label>
              <input className="input" type="number" value={g.per_run_limit||0} onChange={e=>update(['global','per_run_limit'], Number(e.target.value))} />
            </div>
          )}
          <div className="mt-2">
            <label className="block text-sm text-gray-400">Burst concurrency</label>
            <input className="input" type="number" value={g.burst_concurrency||1} onChange={e=>update(['global','burst_concurrency'], Number(e.target.value))} />
          </div>
          <div className="mt-2 grid grid-cols-2 gap-2">
            <div>
              <label className="block text-sm text-gray-400">Token capacity</label>
              <input className="input" type="number" value={g.token_bucket?.capacity||0} onChange={e=>update(['global','token_bucket','capacity'], Number(e.target.value))} />
            </div>
            <div>
              <label className="block text-sm text-gray-400">Refill / hour</label>
              <input className="input" type="number" value={g.token_bucket?.refill_rate_per_hour||0} onChange={e=>update(['global','token_bucket','refill_rate_per_hour'], Number(e.target.value))} />
            </div>
          </div>
        </div>

        <div className="card p-4">
          <h3 className="font-medium mb-2">Per-broker overrides</h3>
          <table className="w-full text-sm">
            <thead>
              <tr className="text-gray-400">
                <th className="text-left p-2">Broker</th>
                <th className="text-left p-2">Mode</th>
                <th className="text-left p-2">Quota/Limit</th>
                <th className="text-left p-2">Burst</th>
              </tr>
            </thead>
            <tbody>
              {Object.keys(brokers).map(key => {
                const b = brokers[key]
                return (
                  <tr key={key} className="border-t border-gray-800">
                    <td className="p-2 font-mono text-xs">{key}</td>
                    <td className="p-2">
                      <select className="select" value={b.crawl_mode||'all'} onChange={e=>update(['brokers',key,'crawl_mode'], e.target.value)}>
                        <option value="all">All</option>
                        <option value="per_hour">Per Hour</option>
                        <option value="per_run">Per Run</option>
                      </select>
                    </td>
                    <td className="p-2">
                      {b.crawl_mode==='per_hour' && (
                        <input className="input" type="number" value={b.per_hour_quota||0} onChange={e=>update(['brokers',key,'per_hour_quota'], Number(e.target.value))} />
                      )}
                      {b.crawl_mode==='per_run' && (
                        <input className="input" type="number" value={b.per_run_limit||0} onChange={e=>update(['brokers',key,'per_run_limit'], Number(e.target.value))} />
                      )}
                    </td>
                    <td className="p-2">
                      <input className="input" type="number" value={b.burst_concurrency||0} onChange={e=>update(['brokers',key,'burst_concurrency'], Number(e.target.value))} />
                    </td>
                  </tr>
                )
              })}
            </tbody>
          </table>
        </div>
      </div>

      <div className="mt-4 text-xs text-gray-500">Presets: Crawl All, 100/hr, 250/hr, 500/hr, 1000/hr, Per-Run 100, Per-Run 500 (adjust above).</div>
    </section>
  )
}
