import { useState, useEffect, useRef } from 'react'
import { ChevronLeft, Users, Package, BookOpen, ChevronDown, ChevronRight, Save, Check, Loader2, Trash2, Plus, ExternalLink, Upload } from 'lucide-react'
import { MarkdownEditor } from './MarkdownEditor'

const API = '/api'

interface Team {
  id: string
  name: string
  description: string
  author: string
  repo_url: string
  agents: string[]
  skills: string[]
  installed_at: string
}

interface TeamDetailProps {
  team: Team
  installed: boolean
  onBack: () => void
  onInstalled?: () => void
  onUninstalled?: () => void
}

function SkillUploadButton({ teamId, onInstalled }: { teamId: string; onInstalled: (name: string) => void }) {
  const fileRef = useRef<HTMLInputElement>(null)
  const [uploading, setUploading] = useState(false)

  const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return
    setUploading(true)
    const form = new FormData()
    form.append('file', file)
    form.append('team', teamId)
    try {
      const res = await fetch(`${API}/skills/install-zip`, { method: 'POST', body: form })
      const data = await res.json()
      if (res.ok) {
        onInstalled(data.name)
      } else {
        alert(data.error || '安装失败')
      }
    } catch {
      alert('上传失败')
    }
    setUploading(false)
    if (fileRef.current) fileRef.current.value = ''
  }

  return (
    <>
      <input ref={fileRef} type="file" accept=".zip" className="hidden" onChange={handleUpload} />
      <button
        onClick={() => fileRef.current?.click()}
        disabled={uploading}
        className="flex items-center gap-1 px-3 py-1.5 border border-dashed border-[var(--border)] rounded-lg text-sm text-[var(--text-muted)] hover:border-[var(--accent)] hover:text-[var(--accent)] transition-colors disabled:opacity-50"
      >
        {uploading ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Upload className="w-3.5 h-3.5" />}
        安装 Skill
      </button>
    </>
  )
}

export function TeamDetail({ team, installed, onBack, onInstalled, onUninstalled }: TeamDetailProps) {
  const [expandedAgent, setExpandedAgent] = useState<string | null>(null)
  const [agentFile, setAgentFile] = useState<string>('')
  const [agentContent, setAgentContent] = useState('')
  const [knowledge, setKnowledge] = useState<string[]>([])
  const [selectedKnowledge, setSelectedKnowledge] = useState<string | null>(null)
  const [knowledgeContent, setKnowledgeContent] = useState('')
  const [newKnowledgeName, setNewKnowledgeName] = useState('')
  const [saving, setSaving] = useState(false)
  const [saveSuccess, setSaveSuccess] = useState(false)
  const [loading, setLoading] = useState(false)
  const [deleting, setDeleting] = useState(false)

  useEffect(() => {
    if (installed) {
      fetchKnowledge()
    }
  }, [team.id, installed])

  const fetchKnowledge = async () => {
    if (!installed) return
    setLoading(true)
    try {
      const res = await fetch(`${API}/teams/${team.id}/knowledge`)
      const data = await res.json()
      setKnowledge(data || [])
    } finally {
      setLoading(false)
    }
  }

  const loadAgentFile = async (agentName: string, file: string) => {
    if (!installed) return
    setLoading(true)
    try {
      const res = await fetch(`${API}/teams/${team.id}/agents/${agentName}/files/${file}`)
      const data = await res.json()
      setAgentContent(data.content || '')
      setAgentFile(file)
    } catch {
      setAgentContent('')
    } finally {
      setLoading(false)
    }
  }

  const saveAgentFile = async () => {
    if (!expandedAgent || !agentFile || !installed) return
    setSaving(true)
    try {
      const res = await fetch(`${API}/teams/${team.id}/agents/${expandedAgent}/files/${agentFile}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ content: agentContent })
      })
      if (res.ok) {
        setSaveSuccess(true)
        setTimeout(() => setSaveSuccess(false), 2000)
      }
    } finally {
      setSaving(false)
    }
  }

  const loadKnowledgeFile = async (fileName: string) => {
    if (!installed) return
    setLoading(true)
    try {
      const res = await fetch(`${API}/teams/${team.id}/knowledge/${fileName}`)
      const data = await res.json()
      setKnowledgeContent(data.content || '')
      setSelectedKnowledge(fileName)
    } catch {
      setKnowledgeContent('')
    } finally {
      setLoading(false)
    }
  }

  const saveKnowledgeFile = async () => {
    if (!selectedKnowledge || !installed) return
    setSaving(true)
    try {
      const res = await fetch(`${API}/teams/${team.id}/knowledge/${selectedKnowledge}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ content: knowledgeContent })
      })
      if (res.ok) {
        setSaveSuccess(true)
        setTimeout(() => setSaveSuccess(false), 2000)
      }
    } finally {
      setSaving(false)
    }
  }

  const createKnowledgeFile = async () => {
    if (!newKnowledgeName.trim() || !installed) return
    const name = newKnowledgeName.trim().endsWith('.md')
      ? newKnowledgeName.trim()
      : newKnowledgeName.trim() + '.md'
    await fetch(`${API}/teams/${team.id}/knowledge/${name}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ content: '# ' + name.replace('.md', '') + '\n\n' })
    })
    setNewKnowledgeName('')
    fetchKnowledge()
    loadKnowledgeFile(name)
  }

  const handleInstall = async () => {
    if (!team.repo_url) return
    
    setSaving(true)
    try {
      await fetch(`${API}/hub/install`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ repo: team.repo_url })
      })
      onInstalled?.()
    } finally {
      setSaving(false)
    }
  }

  const handleDelete = async () => {
    if (!confirm(`确定要卸载团队 "${team.name}" 吗？这将删除相关的 agents 和知识库。`)) return
    
    setDeleting(true)
    try {
      await fetch(`${API}/teams/${team.id}`, { method: 'DELETE' })
      onUninstalled?.()
    } finally {
      setDeleting(false)
    }
  }

  return (
    <div className="flex-1 flex flex-col overflow-hidden bg-[var(--bg-primary)] fixed inset-0 z-50 bg-black/50">
      <div className="flex flex-col max-w-4xl w-full mx-auto h-full bg-[var(--bg-secondary)] border border-[var(--border)] rounded-xl m-4 overflow-hidden">
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-[var(--border)]">
          <div className="flex items-center gap-3">
            <button
              onClick={onBack}
              className="flex items-center gap-1 text-[var(--text-muted)] hover:text-[var(--text-primary)] text-sm"
            >
              <ChevronLeft className="w-4 h-4" />
              返回
            </button>
            <span className="text-[var(--text-muted)]">/</span>
            <h2 className="font-semibold">{team.name}</h2>
          </div>
          {installed ? (
            <div className="flex items-center gap-2">
              {team.repo_url && (
                <a
                  href={team.repo_url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center gap-1.5 text-[var(--text-muted)] hover:text-[var(--accent)] text-sm px-3 py-1.5 rounded-lg hover:bg-[var(--bg-hover)]"
                >
                  <ExternalLink className="w-4 h-4" />
                  查看 GitHub
                </a>
              )}
              <button
                onClick={handleDelete}
                disabled={deleting}
                className="flex items-center gap-1.5 text-[var(--text-muted)] hover:text-[var(--color-error)] text-sm bg-red-900/20 hover:bg-red-900/30 px-3 py-1.5 rounded-lg"
              >
                {deleting ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : (
                  <Trash2 className="w-4 h-4" />
                )}
                卸载团队
              </button>
            </div>
          ) : (
            <button
              onClick={handleInstall}
              disabled={saving}
              className="flex items-center gap-1.5 text-white text-sm bg-blue-500 hover:bg-blue-600 px-3 py-1.5 rounded-lg"
            >
              {saving ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <Plus className="w-4 h-4" />
              )}
              安装团队
            </button>
          )}
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-6">
          <div className="space-y-6">
            {/* Team info */}
            <div className="bg-[var(--bg-secondary)] border border-[var(--border)] rounded-xl p-4">
              <p className="text-sm text-[var(--text-secondary)] mb-2">{team.description}</p>
              {team.author && (
                <div className="text-xs text-[var(--text-muted)]">
                  作者: {team.author}
                </div>
              )}
            </div>

            {/* Agents */}
            <section>
              <h3 className="flex items-center gap-2 text-sm font-semibold text-[var(--text-muted)] uppercase mb-3">
                <Users className="w-4 h-4" />
                成员 ({team.agents?.length || 0})
              </h3>
              {team.agents?.length === 0 ? (
                <p className="text-sm text-[var(--text-muted)]">暂无成员</p>
              ) : (
                <div className="space-y-2">
                  {team.agents?.map(agent => (
                    <div key={agent} className={`bg-[var(--bg-secondary)] border border-[var(--border)] rounded-lg overflow-hidden ${installed ? '' : 'opacity-50'}`}>
                      <button
                        onClick={() => {
                          if (!installed) return
                          if (expandedAgent === agent) {
                            setExpandedAgent(null)
                          } else {
                            setExpandedAgent(agent)
                            loadAgentFile(agent, 'SOUL.md')
                          }
                        }}
                        className={`w-full flex items-center justify-between px-4 py-3 hover:bg-[var(--bg-hover)] transition-colors ${installed ? '' : 'cursor-not-allowed'}`}
                      >
                        <span className="font-medium">{agent}</span>
                        {installed && expandedAgent === agent ? (
                          <ChevronDown className="w-4 h-4 text-[var(--text-muted)]" />
                        ) : installed ? (
                          <ChevronRight className="w-4 h-4 text-[var(--text-muted)]" />
                        ) : undefined}
                      </button>
                      {installed && expandedAgent === agent && (
                        <div className="border-t border-[var(--border)]">
                          {/* File tabs */}
                          <div className="flex items-center gap-1 px-4 py-2 bg-[var(--bg-tertiary)]">
                            {['SOUL.md', 'AGENT.md'].map(f => (
                              <button
                                key={f}
                                onClick={() => loadAgentFile(agent, f)}
                                className={`px-3 py-1 text-xs rounded transition-colors ${
                                  agentFile === f
                                    ? 'bg-[var(--accent)] text-white'
                                    : 'hover:bg-[var(--bg-hover)] text-[var(--text-secondary)]'
                                }`}
                              >
                                {f}
                              </button>
                            ))}
                          </div>
                          {/* Editor */}
                          <div className="border-t border-[var(--border)]">
                            {loading ? (
                              <div className="flex items-center justify-center h-64">
                                <Loader2 className="w-5 h-5 animate-spin text-[var(--accent)]" />
                              </div>
                            ) : (
                              <MarkdownEditor
                                value={agentContent}
                                onChange={(v: string) => setAgentContent(v)}
                                height={250}
                              />
                            )}
                          </div>
                          {/* Save button */}
                          <div className="flex justify-end px-4 py-2 bg-[var(--bg-tertiary)]">
                            <button
                              onClick={saveAgentFile}
                              disabled={saving}
                              className={`flex items-center gap-1.5 px-3 py-1.5 rounded text-xs font-medium text-white transition-colors ${
                                saveSuccess
                                  ? 'bg-green-500'
                                  : 'bg-[var(--accent)] hover:bg-[var(--accent-hover)]'
                              }`}
                            >
                              {saving ? <Loader2 className="w-3 h-3 animate-spin" /> : saveSuccess ? <Check className="w-3 h-3" /> : <Save className="w-3 h-3" />}
                              {saveSuccess ? '已保存' : '保存'}
                            </button>
                          </div>
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              )}
            </section>

            {/* Skills */}
            <section>
              <h3 className="flex items-center gap-2 text-sm font-semibold text-[var(--text-muted)] uppercase mb-3">
                <Package className="w-4 h-4" />
                Skills ({team.skills?.length || 0})
              </h3>
              <div className="flex flex-wrap gap-2 items-center">
                {team.skills?.length === 0 && (
                  <p className="text-sm text-[var(--text-muted)]">暂无 skills</p>
                )}
                {team.skills?.map(skill => (
                  <span
                    key={skill}
                    className={`px-3 py-1.5 border rounded-lg text-sm ${installed ? 'bg-[var(--bg-secondary)] border-[var(--border)]' : 'border-[var(--border)] opacity-50'}`}
                  >
                    {skill}
                  </span>
                ))}
                {installed && <SkillUploadButton teamId={team.id} onInstalled={(name) => {
                  if (!team.skills?.includes(name)) {
                    team.skills = [...(team.skills || []), name]
                  }
                  onInstalled?.()
                }} />}
              </div>
            </section>

            {/* Knowledge */}
            {installed && (
              <section>
                <h3 className="flex items-center gap-2 text-sm font-semibold text-[var(--text-muted)] uppercase mb-3">
                  <BookOpen className="w-4 h-4" />
                  知识库
                </h3>

                <div className="flex gap-4">
                  {/* File list */}
                  <div className="w-48 flex-shrink-0 space-y-1">
                    {knowledge.map(f => (
                      <button
                        key={f}
                        onClick={() => loadKnowledgeFile(f)}
                        className={`w-full text-left px-3 py-2 rounded-lg text-sm transition-colors ${
                          selectedKnowledge === f
                            ? 'bg-[var(--accent-muted)] text-[var(--text-primary)]'
                            : 'hover:bg-[var(--bg-hover)] text-[var(--text-secondary)]'
                        }`}
                      >
                        {f}
                      </button>
                    ))}
                    {/* Add new */}
                    <div className="flex items-center gap-1 mt-2">
                      <input
                        type="text"
                        value={newKnowledgeName}
                        onChange={e => setNewKnowledgeName(e.target.value)}
                        placeholder="新知识文件"
                        className="flex-1 bg-[var(--bg-tertiary)] border border-[var(--border)] rounded-lg px-2 py-1 text-xs outline-none focus:border-[var(--accent)]"
                        onKeyDown={e => e.key === 'Enter' && createKnowledgeFile()}
                      />
                      <button
                        onClick={createKnowledgeFile}
                        className="p-1.5 bg-[var(--accent)] rounded-lg text-white hover:bg-[var(--accent-hover)]"
                      >
                        <Plus className="w-3 h-3" />
                      </button>
                    </div>
                  </div>

                  {/* Editor */}
                  <div className="flex-1 flex flex-col border border-[var(--border)] rounded-lg overflow-hidden">
                    {selectedKnowledge ? (
                      <>
                        <div className="flex-1">
                          <MarkdownEditor
                            value={knowledgeContent}
                            onChange={(v: string) => setKnowledgeContent(v)}
                            height={320}
                          />
                        </div>
                        <div className="flex justify-end px-4 py-2 bg-[var(--bg-tertiary)]">
                          <button
                            onClick={saveKnowledgeFile}
                            disabled={saving}
                            className={`flex items-center gap-1.5 px-3 py-1.5 rounded text-xs font-medium text-white transition-colors ${
                              saveSuccess
                                ? 'bg-green-500'
                                : 'bg-[var(--accent)] hover:bg-[var(--accent-hover)]'
                            }`}
                          >
                            {saving ? <Loader2 className="w-3 h-3 animate-spin" /> : saveSuccess ? <Check className="w-3 h-3" /> : <Save className="w-3 h-3" />}
                            {saveSuccess ? '已保存' : '保存'}
                          </button>
                        </div>
                      </>
                    ) : (
                      <div className="flex items-center justify-center h-80 text-[var(--text-muted)] text-sm">
                        选择或创建知识文件
                      </div>
                    )}
                  </div>
                </div>
              </section>
            )}

            {!installed && (
              <div className="bg-[var(--bg-tertiary)] border border-[var(--border)] rounded-xl p-4">
                <p className="text-sm text-[var(--text-muted)] text-center">
                  此团队尚未安装。点击上方"安装"按钮来安装它。
                </p>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}
