import React, { useEffect, useState } from 'react'
import axios from 'axios'
import { CrawlControls } from './CrawlControls'

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

export function App() {
  const [tab, setTab] = useState<'dashboard'|'brokers'|'crawl'|'schedule'|'logs'>('dashboard')
  const [status, setStatus] = useState<any>({})
  const [brokers, setBrokers] = useState<string[]>([])
  const [cron, setCron] = useState<string>('')

  const refresh = async () => {
    const [s, b, sc] = await Promise.all([
      axios.get(API('/status')).then(r=>r.data).catch(()=>({})),
      axios.get(API('/brokers')).then(r=>r.data.brokers).catch(()=>[]),
      axios.get(API('/schedule')).then(r=>r.data.cron).catch(()=>''),
    ])
    setStatus(s); setBrokers(b); setCron(sc)
  }

  useEffect(()=>{ refresh() },[])

  const runNow = async (broker?: string) => {
    await axios.post(API('/run') + (broker?`?broker=${encodeURIComponent(broker)}`:''))
    await refresh()
  }

  const saveCron = async () => {
    await axios.patch(API('/schedule'), { cron })
    await refresh()
  }

  return (
    <div className="min-h-screen">
      <header className="p-4 border-b border-gray-800 flex items-center justify-between">
        <h1 className="text-xl font-semibold">DVC Broker Scraper</h1>
        <nav className="flex gap-2">
          {['dashboard','brokers','crawl','schedule','logs'].map(k=>
            <button key={k} className={`btn ${tab===k?'bg-indigo-500':'bg-gray-800'}`} onClick={()=>setTab(k as any)}>
              {k}
            </button>
          )}
        </nav>
      </header>

      <main className="p-6 grid gap-6 max-w-6xl mx-auto">
        {tab==='dashboard' && (
          <section className="card p-6">
            <div className="flex items-center justify-between">
              <div>
                <h2 className="text-lg font-medium">Dashboard</h2>
                <p className="text-sm text-gray-400">Last run counts per broker.</p>
              </div>
              <button className="btn" onClick={()=>runNow()}>Run All</button>
            </div>
            <div className="mt-4 grid grid-cols-1 md:grid-cols-2 gap-4">
              {Object.entries(status.counts||{}).map(([b,c])=> (
                <div key={b} className="card p-4">
                  <div className="flex items-center justify-between">
                    <div className="font-medium">{b}</div>
                    <div className="text-indigo-400">{c as any} items</div>
                  </div>
                </div>
              ))}
            </div>
          </section>
        )}

        {tab==='brokers' && (
          <section className="card p-6">
            <div className="flex items-center justify-between">
              <h2 className="text-lg font-medium">Brokers</h2>
              <button className="btn" onClick={()=>runNow()}>Run All</button>
            </div>
            <div className="mt-4 divide-y divide-gray-800">
              {brokers.map(b=> (
                <div key={b} className="py-3 flex items-center justify-between">
                  <div>{b}</div>
                  <button className="btn" onClick={()=>runNow(b)}>Run</button>
                </div>
              ))}
            </div>
          </section>
        )}

        {tab==='crawl' && (
          <CrawlControls />
        )}

        {tab==='schedule' && (
          <section className="card p-6">
            <div className="flex items-center justify-between">
              <h2 className="text-lg font-medium">Schedule</h2>
              <div className="flex gap-2">
                <input className="input w-72" value={cron} onChange={e=>setCron(e.target.value)} />
                <button className="btn" onClick={saveCron}>Save</button>
              </div>
            </div>
            <div className="mt-4 flex gap-2 flex-wrap">
              {[
                {label:'Hourly', cron:'0 * * * *'},
                {label:'Every 6h', cron:'0 */6 * * *'},
                {label:'Daily 3am', cron:'0 3 * * *'},
                {label:'Weekly Mon 4am', cron:'0 4 * * 1'},
              ].map(p => (
                <button key={p.label} className="btn bg-gray-800" onClick={()=>setCron(p.cron)}>{p.label}</button>
              ))}
            </div>
          </section>
        )}

        {tab==='logs' && (
          <section className="card p-6">
            <h2 className="text-lg font-medium">Logs</h2>
            <p className="text-gray-400">SSE/polling to be implemented.</p>
          </section>
        )}
      </main>
    </div>
  )
}
