import { useCallback, useEffect, useState } from 'react'
import type { FeedItem, Tab } from './data'
import { SAMPLE } from './data'
import {
  getFeed, getMe, toggleLike,
  captureTokensFromUrl, getKakaoAuthUrl, startKakaoLogin, logout as apiLogout,
} from './api'
import type { Me } from './api'
import { Nav, TopBar, Home, Search, Channel, CreateSheet, Viewer, Login, ChargeSheet, ProfileEdit } from './components'

export default function App() {
  const [tab, setTab] = useState<Tab>('home')
  const [data, setData] = useState<FeedItem[]>(SAMPLE)
  const [me, setMe] = useState<Me | null>(null)
  const [authReady, setAuthReady] = useState(false)
  const [busy, setBusy] = useState(false)
  const [viewerId, setViewerId] = useState<string | null>(null)
  const [sheetOpen, setSheetOpen] = useState(false)
  const [loginOpen, setLoginOpen] = useState(false)
  const [chargeOpen, setChargeOpen] = useState(false)
  const [profileOpen, setProfileOpen] = useState(false)
  const [toast, setToast] = useState('')

  const notify = useCallback((m: string) => {
    setToast(m)
    window.setTimeout(() => setToast((t) => (t === m ? '' : t)), 2600)
  }, [])

  const loadFeed = useCallback(async () => {
    const f = await getFeed()
    if (f) setData(f.length ? f : [])       // 백엔드 연결 시 실제 output(빈 배열이면 빈 상태)
  }, [])

  useEffect(() => {
    (async () => {
      captureTokensFromUrl()                // 카카오 콜백 토큰 수신
      // 유튜브 연동 콜백 복귀 처리(?connected=youtube&tab=channel)
      const q = new URLSearchParams(window.location.search)
      if (q.get('connected') === 'youtube') { setTab('channel'); notify('유튜브 채널이 연동됐어요!') }
      if (q.get('connected') || q.get('tab')) window.history.replaceState({}, '', window.location.pathname)
      setMe(await getMe())
      setAuthReady(true)
      await loadFeed()
    })()
  }, [loadFeed])

  const onKakao = async () => {
    setBusy(true)
    const url = await getKakaoAuthUrl()
    if (url) startKakaoLogin(url)
    else { notify('카카오 로그인이 아직 설정되지 않았어요.'); setBusy(false) }
  }
  const onLogout = () => { apiLogout(); setMe(null); setTab('home') }
  const requireLogin = () => { setLoginOpen(true); return false }

  const onTab = (t: Tab | 'create') => {
    if (t === 'create') { if (!me) return void requireLogin(); setSheetOpen(true); return }
    if (t === 'channel' && !me) return void requireLogin()
    setTab(t)
  }

  const onLike = async (id: string) => {
    if (!me) return void requireLogin()
    try {
      const r = await toggleLike(id)
      setData((d) => d.map((it) => (it.id === id ? { ...it, liked: r.liked, likes: r.likes } : it)))
    } catch { /* 네트워크 — 무시 */ }
  }

  const viewer = data.find((x) => x.id === viewerId) ?? null
  void authReady

  return (
    <div id="app">
      <Nav tab={tab} onTab={onTab} nickname={me?.nickname ?? null} avatar={me?.profile_image_url ?? null}
        onLogin={() => setLoginOpen(true)} onLogout={onLogout} />

      <div className="main">
        <TopBar tab={tab} nickname={me?.nickname ?? null} onLogin={() => setLoginOpen(true)} />
        <main className="screen">
          {tab === 'home' && <Home data={data} onOpen={setViewerId} />}
          {tab === 'search' && <Search data={data} onOpen={setViewerId} />}
          {tab === 'channel' && (
            <Channel
              data={me ? data.filter((d) => d.mine) : data}
              credits={me?.credits ?? 0}
              nickname={me?.nickname ?? '게스트'}
              avatar={me?.profile_image_url ?? null}
              bio={me?.bio ?? null}
              onOpen={setViewerId}
              toast={notify}
              onLogout={onLogout}
              onCharge={() => setChargeOpen(true)}
              onEditProfile={() => setProfileOpen(true)}
            />
          )}
        </main>
      </div>

      <div className={'scrim' + (sheetOpen || chargeOpen || profileOpen ? ' on' : '')}
        onClick={() => { setSheetOpen(false); setChargeOpen(false); setProfileOpen(false) }} />
      <ChargeSheet
        open={chargeOpen}
        onClose={() => setChargeOpen(false)}
        onDone={(credits) => setMe((m) => (m ? { ...m, credits } : m))}
        toast={notify}
      />
      <ProfileEdit
        open={profileOpen}
        onClose={() => setProfileOpen(false)}
        me={me}
        onSaved={(updated) => setMe(updated)}
        toast={notify}
      />
      <CreateSheet
        open={sheetOpen}
        onClose={() => setSheetOpen(false)}
        onCreated={async () => { await loadFeed(); setMe(await getMe()); setTab('home') }}
      />
      <Viewer item={viewer} onClose={() => setViewerId(null)} onLike={onLike} toast={notify} />
      <Login open={loginOpen} onClose={() => setLoginOpen(false)} onKakao={onKakao} busy={busy} />
      <div className={'toast' + (toast ? ' on' : '')} role="status">{toast}</div>
    </div>
  )
}
