import { useEffect, useState } from 'react'
import { ShoppingCart, Sparkles, Settings, Plus } from 'lucide-react'
import { useStore } from './store'
import { ChatView } from './components/ChatView'
import { MarketPage } from './components/MarketPage'
import { UserSettings } from './components/UserSettings'
import { ThemeToggle } from './components/ThemeToggle'
import { Onboarding } from './components/Onboarding'
import { MemberList } from './components/MemberList'
import { RightSidebar } from './components/RightSidebar'

const API = '/api'

const COLORS = ['#5865F2', '#57F287', '#FEE75C', '#EB459E', '#ED4245', '#3BA55C', '#FAA61A', '#00B0F4']
const randomColor = () => COLORS[Math.floor(Math.random() * COLORS.length)]

export default function App() {
  const { page, setPage, onboardingCompleted, setOnboardingCompleted, fetchUser, fetchRooms, rooms, activeRoomId, setActiveRoom } = useStore()
  const [showOnboarding, setShowOnboarding] = useState(onboardingCompleted ? false : true)
  const [creating, setCreating] = useState(false)
  const [newRoomName, setNewRoomName] = useState('')

  useEffect(() => {
    fetchUser()
    fetchRooms().then(() => {
      const savedRoomId = useStore.getState().activeRoomId
      if (savedRoomId) {
        useStore.getState().connectRoom(savedRoomId)
        // 加载历史消息、任务、工作区
        fetch(`${API}/rooms/${savedRoomId}/messages`).then(r => r.json()).then(msgs => {
          if (msgs?.length) useStore.setState(s => ({ messages: { ...s.messages, [savedRoomId]: msgs } }))
        }).catch(() => {})
        fetch(`${API}/rooms/${savedRoomId}/tasks`).then(r => r.json()).then(d => {
          useStore.setState(s => ({ tasks: { ...s.tasks, [savedRoomId]: d.content } }))
        }).catch(() => {})
        fetch(`${API}/rooms/${savedRoomId}/workspace`).then(r => r.json()).then(files => {
          useStore.setState(s => ({ workspace: { ...s.workspace, [savedRoomId]: files || [] } }))
        }).catch(() => {})
      }
    })
  }, [fetchUser, fetchRooms])

  const handleOnboardingComplete = () => {
    setShowOnboarding(false)
    setOnboardingCompleted(true)
    fetchUser()
  }

  const createRoom = async () => {
    if (!newRoomName.trim()) return
    const color = randomColor()
    await fetch(`${API}/rooms`, {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name: newRoomName.trim(), type: 'project', color, master: '', members: [] })
    })
    setCreating(false)
    setNewRoomName('')
    useStore.getState().fetchRooms()
  }

  return (
    <>
      {showOnboarding && !onboardingCompleted && (
        <Onboarding onComplete={handleOnboardingComplete} />
      )}

      <div className="flex h-screen bg-[var(--bg-primary)] text-[var(--text-primary)] overflow-hidden">
        {/* Left sidebar - Navigation */}
        <div className="flex flex-col w-[72px] bg-[var(--sidebar-bg)] items-center py-3 gap-2">
          {/* Logo */}
          <div className="w-12 h-12 rounded-xl flex items-center justify-center mb-2">
            <Sparkles className="w-7 h-7 text-[var(--accent)]" />
          </div>

          {/* Room list */}
          <div className="flex flex-col gap-1 w-full px-3 flex-1 overflow-y-auto scrollbar-thin">
            {rooms.map(r => {
              const isActive = activeRoomId === r.id
              const initial = r.name[0]?.toUpperCase() || '?'
              const color = r.color || '#5865F2'
              return (
                <button
                  key={r.id}
                  onClick={() => { setPage('chat'); setActiveRoom(r.id) }}
                  title={r.name}
                  className={`
                    w-full h-10 rounded-lg flex items-center justify-center transition-all duration-200 relative text-white text-sm font-bold
                    ${isActive ? 'ring-2 ring-white/40' : 'hover:rounded-xl'}
                  `}
                  style={{ backgroundColor: color }}
                >
                  {initial}
                  {r.status !== 'pending' && (
                    <span className={`absolute top-0.5 right-0.5 w-2.5 h-2.5 rounded-full border-2 border-[var(--sidebar-bg)] ${r.status === 'thinking' ? 'bg-yellow-400' : 'bg-green-400 animate-pulse'}`} />
                  )}
                </button>
              )
            })}
            
            {/* Add room button */}
            <button
              onClick={() => setCreating(true)}
              title="创建项目"
              className="w-full h-10 rounded-lg flex items-center justify-center text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-hover)] transition-all duration-200"
            >
              <Plus className="w-5 h-5" />
            </button>
          </div>

          {/* Bottom buttons */}
          <div className="mt-auto flex flex-col gap-1 w-full px-3">
            {/* Market */}
            <button
              onClick={() => setPage('market')}
              className={`
                w-9 h-9 rounded-lg flex items-center justify-center transition-colors duration-200 
                text-[var(--text-secondary)] hover:text-[var(--text-primary)]
                ${page === 'market' ? 'bg-[var(--accent)] text-white' : 'hover:bg-[var(--bg-hover)]'}
              `}
              title="市场"
            >
              <ShoppingCart className="w-5 h-5" />
            </button>

            {/* Theme toggle */}
            <ThemeToggle />

            {/* Settings */}
            <button
              onClick={() => setPage('settings')}
              className={`
                w-9 h-9 rounded-lg flex items-center justify-center transition-colors duration-200 
                text-[var(--text-secondary)] hover:text-[var(--text-primary)]
                ${page === 'settings' ? 'bg-[var(--accent)] text-white' : 'hover:bg-[var(--bg-hover)]'}
              `}
              title="设置"
            >
              <Settings className="w-5 h-5" />
            </button>
          </div>
        </div>

        {/* Create room modal */}
        {creating && (
          <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50" onClick={() => setCreating(false)}>
            <div className="bg-[var(--bg-secondary)] rounded-lg p-4 w-80 shadow-xl" onClick={e => e.stopPropagation()}>
              <h3 className="font-semibold mb-3">创建新项目</h3>
              <input
                autoFocus
                className="w-full bg-[var(--bg-tertiary)] border border-[var(--border)] rounded-lg px-3 py-2 text-sm outline-none focus:border-[var(--accent)] mb-3"
                placeholder="项目名称"
                value={newRoomName}
                onChange={e => setNewRoomName(e.target.value)}
                onKeyDown={e => e.key === 'Enter' && createRoom()}
              />
              <div className="flex gap-2">
                <button
                  onClick={createRoom}
                  className="flex-1 bg-[var(--accent)] hover:bg-[var(--accent-hover)] text-white rounded-lg py-2 text-sm font-medium"
                >
                  创建
                </button>
                <button
                  onClick={() => setCreating(false)}
                  className="flex-1 bg-[var(--bg-hover)] hover:bg-[var(--bg-active)] rounded-lg py-2 text-sm"
                >
                  取消
                </button>
              </div>
            </div>
          </div>
        )}

        {/* Main content */}
        {page === 'chat' && (
          <>
            <MemberList />
            <ChatView />
            <RightSidebar />
          </>
        )}
        {page === 'market' && <MarketPage />}
        {page === 'settings' && <UserSettings />}
      </div>
    </>
  )
}