import { useState, useEffect } from 'react'
import { ShoppingCart, Github, Upload, Users, ArrowRight, Check, AlertCircle, Package, Zap, Star, Globe, Link as LinkIcon, Loader2 } from 'lucide-react'
import { useStore } from '../store'
import { TeamDetail } from './TeamDetail'

const API = '/api'

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

const PRESET_TEAMS: Team[] = [
  {
    id: 'legal-team',
    name: '法律咨询团队',
    description: '法律咨询团队，包含合同审查、法律风险评估和合规管理',
    author: 'Agent Team',
    repo_url: 'https://gitea.catter.cn/agent-teams/legal-team',
    agents: ['法律总监', '合同律师', '合规专员'],
    skills: ['合同审查', '法律知识库'],
    installed_at: '',
  },
  {
    id: 'writing-team',
    name: '网文编写团队',
    description: '专业网文创作团队，包含内容策划、素材搜索、文章编写和合规审查',
    author: 'Agent Team',
    repo_url: 'https://gitea.catter.cn/agent-teams/writing-team',
    agents: ['主编', '搜索员', '合规审查员'],
    skills: ['web-search'],
    installed_at: '',
  },
  {
    id: 'marketing-team',
    name: '营销团队',
    description: '营销团队，包含市场分析、竞品研究和内容策划',
    author: 'Agent Team',
    repo_url: 'https://gitea.catter.cn/agent-teams/marketing-team',
    agents: ['营销总监', '市场分析师', '内容策划师'],
    skills: ['数据分析', '用户画像'],
    installed_at: '',
  },
]

export function MarketPage() {
  const { fetchAgents } = useStore()
  const [tab, setTab] = useState<'featured' | 'install' | 'teams'>('featured')
  const [repo, setRepo] = useState('')
  const [status, setStatus] = useState<'idle' | 'loading' | 'done' | 'error'>('idle')
  const [errMsg, setErrMsg] = useState('')
  const [uploading, setUploading] = useState(false)
  const [teams, setTeams] = useState<Team[]>([])
  const [selectedTeam, setSelectedTeam] = useState<Team | null>(null)
  const [installingTeams, setInstallingTeams] = useState<Set<string>>(new Set())

  useEffect(() => {
    if (tab === 'teams') {
      fetchTeams()
    }
  }, [tab])

  const fetchTeams = async () => {
    const res = await fetch(`${API}/teams`)
    const data = await res.json()
    setTeams(data || [])
  }

  const installTeam = async (team: Team) => {
    if (!team.repo_url || installingTeams.has(team.name)) return
    setInstallingTeams(prev => new Set(prev).add(team.name))
    try {
      await fetch(`${API}/hub/install`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ repo: team.repo_url })
      })
      fetchAgents()
      fetchTeams()
    } finally {
      setInstallingTeams(prev => {
        const next = new Set(prev)
        next.delete(team.name)
        return next
      })
    }
  }

  const install = async () => {
    if (!repo.trim()) return
    setStatus('loading')
    setErrMsg('')
    try {
      const r = await fetch(`${API}/hub/install`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ repo: repo.trim() })
      })
      if (!r.ok) { const d = await r.json(); throw new Error(d.error) }
      setStatus('done')
      fetchAgents()
      fetchTeams()
    } catch (e: unknown) {
      const errMsg = e instanceof Error ? e.message : '安装失败'
      setErrMsg(errMsg)
      setStatus('error')
    }
  }

  const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return

    setUploading(true)
    setStatus('loading')
    setErrMsg('')

    const formData = new FormData()
    formData.append('file', file)

    try {
      const r = await fetch(`${API}/hub/install-zip`, {
        method: 'POST',
        body: formData,
      })
      if (!r.ok) { const d = await r.json(); throw new Error(d.error) }
      setStatus('done')
      fetchAgents()
      fetchTeams()
    } catch (e: unknown) {
      const errMsg = e instanceof Error ? e.message : '上传失败'
      setErrMsg(errMsg)
      setStatus('error')
    } finally {
      setUploading(false)
    }
  }

  const deleteTeam = async (name: string) => {
    if (!confirm(`确定要删除团队 "${name}" 吗？`)) return
    await fetch(`${API}/teams/${name}`, { method: 'DELETE' })
    fetchTeams()
  }

  return (
    <div className="flex-1 overflow-y-auto bg-[var(--bg-primary)]">
      <div className="max-w-4xl mx-auto p-6">
        {/* Header */}
        <div className="flex items-center gap-3 mb-6">
          <ShoppingCart className="w-7 h-7 text-[var(--accent)]" />
          <h2 className="text-2xl font-bold">团队市场</h2>
        </div>

        {/* Tabs */}
        <div className="flex border-b border-[var(--border)] mb-6">
          <button
            onClick={() => {
              setTab('featured')
              setSelectedTeam(null)
            }}
            className={`px-6 py-3 text-sm font-medium border-b-2 transition-colors ${
              tab === 'featured'
                ? 'border-[var(--accent)] text-[var(--accent)]'
                : 'border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)]'
            }`}
          >
            <Zap className="w-4 h-4 inline-block mr-2" />
            精选团队
          </button>
          <button
            onClick={() => setTab('install')}
            className={`px-6 py-3 text-sm font-medium border-b-2 transition-colors ${
              tab === 'install'
                ? 'border-[var(--accent)] text-[var(--accent)]'
                : 'border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)]'
            }`}
          >
            <Globe className="w-4 h-4 inline-block mr-2" />
            雇佣团队
          </button>
          <button
            onClick={() => { 
              setTab('teams')
              setSelectedTeam(null)
              fetchTeams()
            }}
            className={`px-6 py-3 text-sm font-medium border-b-2 transition-colors ${
              tab === 'teams'
                ? 'border-[var(--accent)] text-[var(--accent)]'
                : 'border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)]'
            }`}
          >
            <Package className="w-4 h-4 inline-block mr-2" />
            我的团队 ({teams.length})
          </button>
        </div>

        {selectedTeam && (
          <TeamDetail
            team={selectedTeam}
            installed={tab === 'teams' || teams.some(t => t.name === selectedTeam.name)}
            onBack={() => setSelectedTeam(null)}
            onInstalled={() => {
              setSelectedTeam(null)
              fetchTeams()
            }}
            onUninstalled={() => {
              setSelectedTeam(null)
              deleteTeam(selectedTeam.name)
              fetchTeams()
            }}
          />
        )}

        {selectedTeam ? null : (
          <>
            {/* Featured teams */}
            {tab === 'featured' && (
              <div>
                <div className="text-sm text-[var(--text-muted)] mb-4">
                  官方精选团队，快速开始使用
                </div>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                  {PRESET_TEAMS.map(team => {
                    const isInstalled = teams.some(t => t.name === team.name)
                    const isInstalling = installingTeams.has(team.name)
                    return (
                      <div
                        key={team.name}
                        className={`bg-[var(--bg-secondary)] border border-[var(--border)] rounded-xl p-4 hover:border-[var(--accent)] transition-all ${
                          isInstalled ? 'ring-2 ring-[var(--accent)] ring-offset-2' : ''
                        }`}
                      >
                        <div className="flex items-start justify-between mb-3">
                          <div>
                            <h3 className="font-semibold mb-1">{team.name}</h3>
                            <p className="text-xs text-[var(--text-muted)]">{team.description}</p>
                          </div>
                          {isInstalled ? (
                            <div className="w-8 h-8 bg-[var(--color-success)] rounded-full flex items-center justify-center text-white">
                              <Check className="w-4 h-4" />
                            </div>
                          ) : (
                            <div className="text-[var(--accent)]">
                              <Globe className="w-5 h-5" />
                            </div>
                          )}
                        </div>
                        <div className="flex items-center text-xs gap-2 text-[var(--text-secondary)] mb-3">
                          <Star className="w-3.5 h-3.5 text-yellow-500 fill-current" />
                          <span>专业级</span>
                        </div>
                        <div className="flex items-center gap-3 text-xs text-[var(--text-secondary)] mb-3">
                          <span className="flex items-center gap-1">
                            <Users className="w-3.5 h-3.5" />
                            {team.agents?.length || 0} 成员
                          </span>
                          <span className="flex items-center gap-1">
                            <Package className="w-3.5 h-3.5" />
                            {team.skills?.length || 0} Skills
                          </span>
                        </div>
                        <div className="flex items-center gap-2">
                          {team.repo_url && (
                            <a
                              href={team.repo_url}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="text-xs text-[var(--accent)] hover:underline flex items-center gap-1"
                            >
                              <LinkIcon className="w-3.5 h-3.5" />
                              查看详情
                            </a>
                          )}
                          {!isInstalled && team.repo_url && (
                            <button
                              onClick={() => installTeam(team)}
                              disabled={isInstalling}
                              className="ml-auto flex items-center gap-1.5 bg-[var(--accent)] hover:bg-[var(--accent-hover)] disabled:opacity-50 px-3 py-1.5 rounded-lg text-xs font-medium text-white transition-colors"
                            >
                              {isInstalling ? (
                                <>
                                  <Loader2 className="w-3.5 h-3.5 animate-spin" />
                                  安装中...
                                </>
                              ) : (
                                <>
                                  <ShoppingCart className="w-3.5 h-3.5" />
                                  立即雇佣
                                </>
                              )}
                            </button>
                          )}
                        </div>
                      </div>
                    )
                  })}
                </div>
              </div>
            )}

            {/* Install tab */}
            {tab === 'install' && (
              <div className="space-y-6">
                {/* Install from git */}
                <div className="bg-[var(--bg-secondary)] border border-[var(--border)] rounded-xl p-6">
                  <div className="flex items-center gap-2 mb-4">
                    <Globe className="w-5 h-5 text-[var(--accent)]" />
                    <h3 className="font-semibold text-lg">从 Git 安装</h3>
                  </div>
                  <p className="text-sm text-[var(--text-muted)] mb-4">
                    输入任意 Git 仓库地址（GitHub、Gitee 等），团队包含 agents、skills 和知识库
                  </p>
                  <div className="flex gap-2">
                    <div className="relative flex-1">
                      <Github className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-[var(--text-muted)]" />
                      <input
                        className="w-full bg-[var(--bg-tertiary)] border border-[var(--border)] rounded-lg pl-10 pr-3 py-2.5 text-sm outline-none focus:border-[var(--accent)] transition-colors"
                        placeholder="git@github.com:username/repo.git 或 https://..."
                        value={repo}
                        onChange={e => setRepo(e.target.value)}
                        onKeyDown={e => e.key === 'Enter' && install()}
                      />
                    </div>
                    <button
                      onClick={install}
                      disabled={status === 'loading' || !repo.trim()}
                      className="bg-[var(--accent)] hover:bg-[var(--accent-hover)] disabled:opacity-50 px-5 py-2.5 rounded-lg text-sm font-medium flex items-center gap-2 transition-colors"
                    >
                      {status === 'loading' ? (
                        <>
                          <span className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                          安装中...
                        </>
                      ) : (
                        <>
                          安装
                          <ArrowRight className="w-4 h-4" />
                        </>
                      )}
                    </button>
                  </div>
                  {status === 'done' && (
                    <p className="text-[var(--color-success)] text-sm mt-3 flex items-center gap-1.5">
                      <Check className="w-4 h-4" />
                      安装成功！可在"我的团队"中查看
                    </p>
                  )}
                  {status === 'error' && (
                    <p className="text-[var(--color-error)] text-sm mt-3 flex items-center gap-1.5">
                      <AlertCircle className="w-4 h-4" />
                      {errMsg}
                    </p>
                  )}
                </div>

                {/* Upload ZIP */}
                <div className="bg-[var(--bg-secondary)] border border-[var(--border)] rounded-xl p-6">
                  <div className="flex items-center gap-2 mb-4">
                    <Upload className="w-5 h-5 text-[var(--accent)]" />
                    <h3 className="font-semibold text-lg">上传 ZIP 安装</h3>
                  </div>
                  <p className="text-sm text-[var(--text-muted)] mb-4">
                    上传团队压缩包，将自动解压并安装到本地
                  </p>
                  <div>
                    <label className="w-full">
                      <input
                        type="file"
                        accept=".zip"
                        onChange={handleUpload}
                        disabled={uploading}
                        className="hidden"
                      />
                      <div className={`w-full border-2 border-dashed border-[var(--border)] rounded-lg px-4 py-8 text-center cursor-pointer hover:border-[var(--accent)] transition-colors ${uploading ? 'opacity-50' : ''}`}>
                        {uploading ? (
                          <div>
                            <span className="w-8 h-8 border-4 border-[var(--accent)] border-t-transparent rounded-full animate-spin block mx-auto" />
                            <p className="text-sm text-[var(--text-muted)] mt-2">上传中...</p>
                          </div>
                        ) : (
                          <>
                            <Upload className="w-8 h-8 mx-auto mb-2 text-[var(--text-muted)]" />
                            <p className="text-sm text-[var(--text-muted)]">点击或拖拽 ZIP 文件到这里</p>
                            <p className="text-xs text-[var(--text-muted)] mt-1">支持 .zip 格式</p>
                          </>
                        )}
                      </div>
                    </label>
                  </div>
                </div>
              </div>
            )}

            {/* Teams tab */}
            {tab === 'teams' && (
              <div>
                {teams.length === 0 ? (
                  <div className="text-center py-16">
                    <Package className="w-16 h-16 mx-auto mb-4 text-[var(--text-muted)] opacity-30" />
                    <p className="text-[var(--text-muted)] mb-2">暂无已安装的团队</p>
                    <button
                      onClick={() => setTab('featured')}
                      className="text-[var(--accent)] text-sm hover:underline"
                    >
                      去精选团队中安装
                    </button>
                  </div>
                ) : (
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    {teams.map(team => (
                      <div
                        key={team.name}
                        onClick={() => setSelectedTeam(team)}
                        className="bg-[var(--bg-secondary)] border border-[var(--border)] rounded-xl p-4 hover:border-[var(--accent)] transition-all cursor-pointer ring-2 ring-[var(--accent)] ring-offset-2"
                      >
                        <div className="flex items-start justify-between mb-3">
                          <div>
                            <h3 className="font-semibold mb-1">{team.name}</h3>
                            <p className="text-xs text-[var(--text-muted)]">{team.description || '暂无描述'}</p>
                          </div>
                          <div className="w-8 h-8 bg-[var(--color-success)] rounded-full flex items-center justify-center text-white">
                            <Check className="w-4 h-4" />
                          </div>
                        </div>
                        <div className="flex items-center gap-3 text-xs text-[var(--text-secondary)] mb-3">
                          <span className="flex items-center gap-1">
                            <Users className="w-3.5 h-3.5" />
                            {team.agents?.length || 0} 成员
                          </span>
                          <span className="flex items-center gap-1">
                            <Package className="w-3.5 h-3.5" />
                            {team.skills?.length || 0} Skills
                          </span>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            )}
          </>
        )}
      </div>
    </div>
  )
}
