import { useState, useEffect, useRef } from 'react'
import {
  LayoutDashboard, Activity, Puzzle, Clock,
  CreditCard, Store, Settings, ChevronLeft, ChevronRight,
  WifiOff, Loader, Download, X,
} from 'lucide-react'
import { listen } from '@tauri-apps/api/event'
import { useUpdater } from './hooks/useUpdater'
import Dashboard from './components/Dashboard'
import LiveFeed, { useLiveFeed } from './components/LiveFeed'
import SkillsLibrary from './components/SkillsLibrary'
import PendingQueue, { usePending } from './components/PendingQueue'
import Billing from './components/Billing'
import MarketplacePayouts from './components/MarketplacePayouts'
import SettingsPanel from './components/SettingsPanel'
import Wizard from './components/Wizard'
import './index.css'

type Tab = 'dashboard' | 'feed' | 'skills' | 'pending' | 'billing' | 'marketplace' | 'settings'

// Show "Starting…" for up to 10 s after launch, before switching to "Disconnected"
function useProxyStarting(connected: boolean) {
  const [starting, setStarting] = useState(true)
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null)

  useEffect(() => {
    if (connected) { setStarting(false); return }
    timerRef.current = setTimeout(() => setStarting(false), 10_000)
    return () => { if (timerRef.current) clearTimeout(timerRef.current) }
  }, [connected])

  return starting && !connected
}

export default function App() {
  const [tab, setTab] = useState<Tab>('dashboard')
  const [collapsed, setCollapsed] = useState(false)
  const { pending, reload } = usePending()
  const { connected } = useLiveFeed()
  const update = useUpdater()
  const starting = useProxyStarting(connected)

  // ── First-run wizard ────────────────────────────────────────────────────────
  // null = still checking, true = show wizard, false = skip wizard
  const [showWizard, setShowWizard] = useState<boolean | null>(null)
  const [deepLinkKey, setDeepLinkKey] = useState('')

  useEffect(() => {
    fetch('/bibividi/api/config/status')
      .then(r => r.json())
      .then((data: { license_key_set: boolean }) => {
        setShowWizard(!data.license_key_set)
      })
      .catch(() => setShowWizard(false)) // proxy not yet ready — skip wizard
  }, [])

  // Listen for bibividi:// deep links arriving from Tauri
  useEffect(() => {
    const unlisten = listen<string>('activate-key', event => {
      setDeepLinkKey(event.payload)
      setShowWizard(true)
    })
    return () => { unlisten.then(f => f()) }
  }, [])

  if (showWizard === null) {
    return (
      <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Loader size={20} className="spin" />
      </div>
    )
  }

  if (showWizard) {
    return (
      <Wizard
        initialKey={deepLinkKey}
        onComplete={() => setShowWizard(false)}
      />
    )
  }

  const nav = (id: Tab, Icon: React.ElementType, label: string, badge?: number) => (
    <button
      className={`nav-item${tab === id ? ' active' : ''}`}
      onClick={() => setTab(id)}
      title={collapsed ? label : undefined}
    >
      <Icon size={18} />
      {!collapsed && <span>{label}</span>}
      {!collapsed && badge != null && badge > 0 && (
        <span className="badge">{badge}</span>
      )}
    </button>
  )

  return (
    <div className={`shell${collapsed ? ' collapsed' : ''}`}>
      {/* ── Titlebar ─────────────────────────────────────── */}
      <header className="titlebar">
        <button
          className="collapse-btn"
          onClick={() => setCollapsed(!collapsed)}
          title={collapsed ? 'Expand sidebar' : 'Collapse sidebar'}
        >
          {collapsed ? <ChevronRight size={16} /> : <ChevronLeft size={16} />}
        </button>
        {!collapsed && <span className="logo">BIBIVIDI</span>}
        <div className="proxy-status">
          {connected
            ? <><span className="dot dot-green" /><span>Proxy live</span></>
            : starting
              ? <><Loader size={13} className="spin" /><span>Starting…</span></>
              : <><WifiOff size={13} /><span>Disconnected</span></>
          }
        </div>
      </header>

      {/* ── Sidebar ──────────────────────────────────────── */}
      <aside className="sidebar">
        {nav('dashboard',   LayoutDashboard, 'Dashboard')}
        {nav('feed',        Activity,        'Live Feed')}
        {nav('skills',      Puzzle,          'Skills')}
        {nav('pending',     Clock,           'Pending', pending.length)}
        {nav('billing',     CreditCard,      'Billing')}
        {nav('marketplace', Store,           'Marketplace')}
        <div className="nav-spacer" />
        {nav('settings',    Settings,        'Settings')}
      </aside>

      {/* ── Main ─────────────────────────────────────────── */}
      <main className="main">
        {/* Update banner — shown when a new version is available */}
        {update.available && (
          <div className="update-banner">
            <Download size={15} />
            <span>BIBIVIDI {update.version} is available.</span>
            <button
              className="update-btn"
              onClick={update.install}
              disabled={update.installing}
            >
              {update.installing ? 'Installing…' : 'Update & restart'}
            </button>
            <button className="update-dismiss" onClick={update.dismiss} title="Dismiss">
              <X size={13} />
            </button>
          </div>
        )}
        {tab === 'dashboard'   && <Dashboard />}
        {tab === 'feed'        && <LiveFeedPage />}
        {tab === 'skills'      && <SkillsLibrary />}
        {tab === 'pending'     && <PendingQueue pending={pending} reload={reload} />}
        {tab === 'billing'     && <Billing />}
        {tab === 'marketplace' && <MarketplacePayouts />}
        {tab === 'settings'    && <SettingsPanel />}
      </main>
    </div>
  )
}

function LiveFeedPage() {
  return <LiveFeed />
}
