import { useEffect, useState } from 'react'
import { Crown, Users, ShoppingCart, X, Loader2, Save, FileText } from 'lucide-react'
import { useStore } from '../store'
import { MarkdownEditor } from './MarkdownEditor'

const API = '/api'

interface TeamInfo {
  id: string
  name: string
  description: string
}

function SelectTeamModal({ roomId, onClose }: { roomId: string; onClose: () => void }) {
  const { setRoomTeam, setPage } = useStore()
  const [teams, setTeams] = useState<TeamInfo[]>([])
  const [loading, setLoading] = useState(true)
  const [selecting, setSelecting] = useState<string | null>(null)

  useEffect(() => {
    fetch(`${API}/teams`).then(r => r.json()).then(data => {
      setTeams(data || [])
      setLoading(false)
    })
  }, [])

  const handleSelect = async (teamId: string) => {
    setSelecting(teamId)
    await setRoomTeam(roomId, teamId)
    onClose()
  }

  return (
    <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4">
      <div className="bg-[var(--bg-secondary)] border border-[var(--border)] rounded-xl w-full max-w-md shadow-2xl">
        {/* Header */}
        <div className="flex items-center justify-between px-5 py-4 border-b border-[var(--border)]">
          <div className="flex items-center gap-2">
            <Users className="w-5 h-5 text-[var(--accent)]" />
            <span className="font-semibold">为项目选择团队</span>
          </div>
          <button onClick={onClose} className="text-[var(--text-muted)] hover:text-[var(--text-primary)] transition-colors">
            <X className="w-4 h-4" />
          </button>
        </div>

        {/* Body */}
        <div className="p-5 space-y-4">
          <p className="text-sm text-[var(--text-muted)]">
            选择一个已安装的 AI 团队来处理这个项目。团队中的 Agent 将协作完成你交代的任务。
          </p>

          {loading ? (
            <div className="flex items-center justify-center py-8">
              <Loader2 className="w-5 h-5 animate-spin text-[var(--text-muted)]" />
            </div>
          ) : teams.length > 0 ? (
            <div className="flex flex-col gap-2">
              {teams.map(t => (
                <button
                  key={t.id}
                  disabled={!!selecting}
                  onClick={() => handleSelect(t.id)}
                  className="w-full text-left px-4 py-3 rounded-lg border border-[var(--border)] hover:border-[var(--accent)] hover:bg-[var(--accent)]/5 transition-colors disabled:opacity-50"
                >
                  <div className="flex items-center justify-between">
                    <div className="text-sm font-medium">{t.name}</div>
                    {selecting === t.id && <Loader2 className="w-4 h-4 animate-spin text-[var(--accent)]" />}
                  </div>
                  {t.description && <div className="text-xs text-[var(--text-muted)] mt-0.5">{t.description}</div>}
                </button>
              ))}
            </div>
          ) : (
            <div className="text-center py-6 space-y-2">
              <Users className="w-10 h-10 mx-auto text-[var(--text-muted)] opacity-30" />
              <p className="text-sm text-[var(--text-muted)]">还没有安装任何团队</p>
            </div>
          )}

          {/* Go to market */}
          <div className="pt-2 border-t border-[var(--border)]">
            <button
              onClick={() => { setPage('market'); onClose() }}
              className="w-full flex items-center justify-center gap-2 py-2.5 rounded-lg border border-dashed border-[var(--border)] hover:border-[var(--accent)] hover:text-[var(--accent)] text-[var(--text-muted)] text-sm transition-colors"
            >
              <ShoppingCart className="w-4 h-4" />
              去市场安装团队
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}

function AgentEditModal({ roomId, agentName, onClose }: { roomId: string; agentName: string; onClose: () => void }) {
  const [tab, setTab] = useState<'soul' | 'agent'>('soul')
  const [soul, setSoul] = useState('')
  const [agent, setAgent] = useState('')
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)

  useEffect(() => {
    setLoading(true)
    const base = `${API}/rooms/${roomId}/agents/${agentName}/files`
    Promise.all([
      fetch(`${base}/soul`).then(r => r.ok ? r.json() : { content: '' }).then(d => d.content || '').catch(() => ''),
      fetch(`${base}/agent`).then(r => r.ok ? r.json() : { content: '' }).then(d => d.content || '').catch(() => ''),
    ]).then(([s, a]) => { setSoul(s); setAgent(a); setLoading(false) })
  }, [roomId, agentName])

  const fileMap = { soul: { type: 'soul', value: soul, set: setSoul }, agent: { type: 'agent', value: agent, set: setAgent } }

  const save = async () => {
    setSaving(true)
    const { type, value } = fileMap[tab]
    await fetch(`${API}/rooms/${roomId}/agents/${agentName}/files/${type}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ content: value }) })
    setSaving(false)
    onClose()
  }

  return (
    <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4">
      <div className="bg-[var(--bg-secondary)] border border-[var(--border)] rounded-xl w-full max-w-2xl shadow-2xl flex flex-col" style={{ maxHeight: '80vh' }}>
        <div className="flex items-center justify-between px-5 py-4 border-b border-[var(--border)]">
          <span className="font-semibold">{agentName}</span>
          <button onClick={onClose} className="text-[var(--text-muted)] hover:text-[var(--text-primary)] transition-colors">
            <X className="w-4 h-4" />
          </button>
        </div>
        <div className="flex gap-1 px-5 pt-3">
          {(['soul', 'agent'] as const).map(t => (
            <button key={t} onClick={() => setTab(t)}
              className={`px-4 py-1.5 rounded text-sm transition-colors ${tab === t ? 'bg-[var(--accent)] text-white' : 'hover:bg-[var(--bg-hover)] text-[var(--text-secondary)]'}`}>
              {t === 'soul' ? '人设' : '工作流'}
            </button>
          ))}
        </div>
        <div className="flex-1 overflow-hidden p-5">
          {loading ? (
            <div className="flex items-center justify-center h-full">
              <Loader2 className="w-5 h-5 animate-spin text-[var(--text-muted)]" />
            </div>
          ) : (
            <MarkdownEditor
              value={fileMap[tab].value}
              onChange={fileMap[tab].set}
              height={400}
            />
          )}
        </div>
        <div className="px-5 pb-4 flex justify-end">
          <button onClick={save} disabled={saving || loading}
            className="flex items-center gap-2 px-4 py-2 bg-[var(--accent)] text-white rounded-lg text-sm hover:opacity-90 transition-opacity disabled:opacity-50">
            {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
            保存
          </button>
        </div>
      </div>
    </div>
  )
}

function TeamDocModal({ roomId, onClose }: { roomId: string; onClose: () => void }) {
  const [content, setContent] = useState('')
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)

  useEffect(() => {
    fetch(`${API}/rooms/${roomId}/team-doc`)
      .then(r => r.json())
      .then(d => { setContent(d.content || ''); setLoading(false) })
      .catch(() => setLoading(false))
  }, [roomId])

  const save = async () => {
    setSaving(true)
    await fetch(`${API}/rooms/${roomId}/team-doc`, {
      method: 'PUT', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ content })
    })
    setSaving(false)
    onClose()
  }

  return (
    <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4">
      <div className="bg-[var(--bg-secondary)] border border-[var(--border)] rounded-xl w-full max-w-2xl shadow-2xl flex flex-col" style={{ maxHeight: '80vh' }}>
        <div className="flex items-center justify-between px-5 py-4 border-b border-[var(--border)]">
          <div className="flex items-center gap-2">
            <FileText className="w-5 h-5 text-[var(--accent)]" />
            <span className="font-semibold">团队文档</span>
          </div>
          <button onClick={onClose} className="text-[var(--text-muted)] hover:text-[var(--text-primary)] transition-colors">
            <X className="w-4 h-4" />
          </button>
        </div>
        <div className="flex-1 overflow-hidden p-5">
          {loading ? (
            <div className="flex items-center justify-center h-full">
              <Loader2 className="w-5 h-5 animate-spin text-[var(--text-muted)]" />
            </div>
          ) : (
            <MarkdownEditor value={content} onChange={setContent} height={400} />
          )}
        </div>
        <div className="px-5 pb-4 flex justify-end">
          <button onClick={save} disabled={saving || loading}
            className="flex items-center gap-2 px-4 py-2 bg-[var(--accent)] text-white rounded-lg text-sm hover:opacity-90 transition-opacity disabled:opacity-50">
            {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
            保存
          </button>
        </div>
      </div>
    </div>
  )
}

export function MemberList() {
  const { activeRoomId, rooms } = useStore()
  const [showModal, setShowModal] = useState(false)
  const [editingAgent, setEditingAgent] = useState<string | null>(null)
  const [showTeamDoc, setShowTeamDoc] = useState(false)

  const room = rooms.find(r => r.id === activeRoomId)

  // 进入没有团队的 room 时自动弹出
  useEffect(() => {
    if (room && !room.team) {
      setShowModal(true)
    } else {
      setShowModal(false)
    }
  }, [room?.id, room?.team])

  if (!room) {
    return (
      <div className="w-[200px] bg-[var(--channel-list-bg)] border-r border-[var(--border)] flex flex-col">
        <div className="h-12 px-4 border-b border-[var(--border)] flex items-center">
          <span className="text-sm font-semibold text-[var(--text-muted)]">成员</span>
        </div>
        <div className="flex-1 flex items-center justify-center text-[var(--text-muted)] text-xs">
          选择项目查看成员
        </div>
      </div>
    )
  }

  if (!room.team) {
    return (
      <>
        {showModal && <SelectTeamModal roomId={room.id} onClose={() => setShowModal(false)} />}
        <div className="w-[200px] bg-[var(--channel-list-bg)] border-r border-[var(--border)] flex flex-col">
          <div className="h-12 px-4 border-b border-[var(--border)] flex items-center">
            <span className="text-sm font-semibold text-[var(--text-muted)]">成员</span>
          </div>
          <div className="flex-1 flex flex-col items-center justify-center gap-3 px-4">
            <Users className="w-8 h-8 text-[var(--text-muted)] opacity-30" />
            <p className="text-xs text-[var(--text-muted)] text-center">未选择团队</p>
            <button
              onClick={() => setShowModal(true)}
              className="text-xs text-[var(--accent)] hover:underline"
            >
              选择团队
            </button>
          </div>
        </div>
      </>
    )
  }

  const memberAgents = room.members || []

  return (
    <>
      {showModal && <SelectTeamModal roomId={room.id} onClose={() => setShowModal(false)} />}
      {editingAgent && <AgentEditModal roomId={room.id} agentName={editingAgent} onClose={() => setEditingAgent(null)} />}
      {showTeamDoc && <TeamDocModal roomId={room.id} onClose={() => setShowTeamDoc(false)} />}
      <div className="w-[200px] bg-[var(--channel-list-bg)] border-r border-[var(--border)] flex flex-col overflow-hidden">
      <div className="h-12 px-4 border-b border-[var(--border)] flex items-center justify-between">
        <span className="text-sm font-semibold text-[var(--text-muted)]">成员 — {1 + memberAgents.length}</span>
        <div className="flex items-center gap-1">
          <button
            onClick={() => setShowTeamDoc(true)}
            title="团队文档"
            className="text-[var(--text-muted)] hover:text-[var(--accent)] transition-colors p-0.5"
          >
            <FileText className="w-3.5 h-3.5" />
          </button>
          <button
            onClick={() => setShowModal(true)}
            title="切换团队"
            className="text-[10px] text-[var(--text-muted)] hover:text-[var(--text-primary)] transition-colors"
          >
            {room.team}
          </button>
        </div>
      </div>

      <div className="flex-1 overflow-y-auto py-2 scrollbar-thin">
        <div className="px-2">
          <MemberItem
            name={room.master}
            role="master"
            status={room.status === 'thinking' ? 'thinking' : 'idle'}
            onClick={() => setEditingAgent(room.master)}
          />
          {memberAgents.map(name => (
            <MemberItem
              key={name}
              name={name}
              role="member"
              status={room.status === 'working' && room.activeAgent === name ? 'working' : 'idle'}
              onClick={() => setEditingAgent(name)}
            />
          ))}
        </div>
      </div>
    </div>
    </>
  )
}

function MemberItem({ name, role, status, onClick }: { name: string; role: string; status: string; onClick?: () => void }) {
  const dotClass = status === 'thinking'
    ? 'bg-[var(--color-warning)] animate-pulse'
    : status === 'working'
    ? 'bg-[var(--color-success)] animate-pulse'
    : 'bg-[var(--text-muted)]'

  const statusText = status === 'thinking' ? '思考中' : status === 'working' ? '工作中' : '空闲'

  return (
    <div onClick={onClick} className="flex items-center gap-2 py-1.5 px-2 rounded hover:bg-[var(--bg-hover)] transition-colors group mb-0.5 cursor-pointer">
      <div className="relative flex-shrink-0">
        <div className="w-8 h-8 rounded-full bg-[var(--accent)] flex items-center justify-center text-white text-xs font-semibold">
          {role === 'master' ? <Crown className="w-4 h-4" /> : name[0]?.toUpperCase()}
        </div>
        <div className={`absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full border-2 border-[var(--channel-list-bg)] ${dotClass}`} />
      </div>
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-1">
          {role === 'master' && <Crown className="w-3 h-3 text-[var(--color-warning)] flex-shrink-0" />}
          <span className="text-sm font-medium truncate">{name}</span>
        </div>
        <span className="text-[10px] text-[var(--text-muted)] opacity-0 group-hover:opacity-100 transition-opacity">
          {statusText}
        </span>
      </div>
    </div>
  )
}
