import { useEffect, useState } from 'react'
import { Plus, Hash, ShoppingCart } from 'lucide-react'
import { useStore } from '../store'
import type { Room } from '../types'

const API = '/api'

export function RoomSidebar() {
  const { rooms, activeRoomId, setActiveRoom, fetchRooms, setPage } = useStore()
  const [creating, setCreating] = useState(false)
  const [name, setName] = useState('')

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

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

  const statusColor = (status: string) => {
    if (status === 'thinking') return 'bg-[var(--color-warning)]'
    if (status === 'working') return 'bg-[var(--color-success)] animate-pulse'
    return 'bg-[var(--text-muted)]'
  }

  return (
    <div className="w-60 bg-[var(--channel-list-bg)] flex flex-col border-r border-[var(--border)]">
      {/* 头部 */}
      <div className="h-12 px-4 border-b border-[var(--border)] flex items-center justify-between shadow-sm">
        <h1 className="font-semibold text-sm truncate">项目</h1>
        <button
          onClick={() => setCreating(!creating)}
          className="w-6 h-6 rounded flex items-center justify-center text-[var(--text-secondary)] hover:bg-[var(--bg-hover)] hover:text-[var(--text-primary)] transition-colors"
        >
          <Plus className="w-4 h-4" />
        </button>
      </div>

      {/* 创建项目表单 */}
      {creating && (
        <div className="p-3 border-b border-[var(--border)] space-y-2 text-sm bg-[var(--bg-tertiary)]">
          <input
            autoFocus
            className="w-full bg-[var(--bg-secondary)] border border-[var(--border)] rounded px-2 py-1.5 text-sm outline-none focus:border-[var(--accent)] transition-colors"
            placeholder="项目名称"
            value={name}
            onChange={e => setName(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && create()}
          />
          <div className="flex gap-1">
            <button
              onClick={create}
              className="flex-1 bg-[var(--accent)] hover:bg-[var(--accent-hover)] text-white rounded py-1.5 text-sm font-medium transition-colors"
            >
              创建
            </button>
            <button
              onClick={() => setCreating(false)}
              className="bg-[var(--bg-hover)] hover:bg-[var(--bg-active)] rounded px-2 py-1.5 text-sm transition-colors"
            >
              取消
            </button>
          </div>
        </div>
      )}

      {/* 项目列表 */}
      <div className="flex-1 overflow-y-auto py-2 scrollbar-thin">
        {rooms.map(r => (
          <RoomItem
            key={r.id}
            room={r}
            active={r.id === activeRoomId}
            onClick={() => setActiveRoom(r.id)}
            statusColor={statusColor(r.status)}
          />
        ))}

        {rooms.length === 0 && (
          <div className="px-4 py-8 text-center text-sm text-[var(--text-muted)]">
            <Hash className="w-8 h-8 mx-auto mb-2 opacity-50" />
            <p>暂无项目</p>
            <p className="text-xs mt-1">点击 + 创建第一个项目</p>
          </div>
        )}
      </div>

      {/* 底部 - 去市场 */}
      <div className="p-3 border-t border-[var(--border)]">
        <button
          onClick={() => setPage('market')}
          className="w-full flex items-center justify-center gap-2 py-2 bg-[var(--accent-muted)] text-[var(--accent)] rounded-lg text-sm font-medium hover:bg-[var(--accent)] hover:text-white transition-colors"
        >
          <ShoppingCart className="w-4 h-4" />
          去雇佣团队
        </button>
      </div>
    </div>
  )
}

function RoomItem({ room, active, onClick, statusColor }: { room: Room; active: boolean; onClick: () => void; statusColor: string }) {
  return (
    <div
      onClick={onClick}
      className={`
        mx-2 px-2 py-1.5 rounded cursor-pointer group flex items-center gap-2 transition-all duration-150
        ${active
          ? 'bg-[var(--accent-muted)] text-[var(--text-primary)]'
          : 'hover:bg-[var(--bg-hover)] text-[var(--text-secondary)] hover:text-[var(--text-primary)]'
        }
      `}
    >
      <Hash className={`w-4 h-4 flex-shrink-0 ${active ? 'text-[var(--accent)]' : 'text-[var(--text-muted)]'}`} />
      <div className="flex-1 min-w-0 flex items-center gap-2">
        <span className="truncate text-sm font-medium">{room.name}</span>
        {room.status !== 'pending' && (
          <span className={`w-2 h-2 rounded-full flex-shrink-0 ${statusColor}`} />
        )}
      </div>
    </div>
  )
}
