import { useState, useEffect, useMemo } from 'react'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { getHottestApps, getLatestApps, getBusinessAppsList, getAgentPros, getAppApiKey } from '@/service/business'
import { API_BASE_URL } from '@/config'
import emojiMartData from '@emoji-mart/data'

// 检查是否是 Unicode emoji 字符
const isNativeEmoji = (str) => {
  if (!str) return false
  return /[\uD800-\uDBFF][\uDC00-\uDFFF]/.test(str)
}

// 通过 emoji-mart data 把 emoji 名称转换为 native Unicode 字符
const emojiNameToNative = (name) => {
  if (!name) return '🤖'
  const emoji = emojiMartData.emojis?.[name]
  return emoji?.skins?.[0]?.native || '🤖'
}

const resolveIcon = (icon) => {
  if (!icon) return '🤖'
  if (isNativeEmoji(icon)) return icon
  return emojiNameToNative(icon)
}

// 把后端返回的 icon 路径拼成完整可访问 URL
//   - 已经是 http(s):// 开头 → 原样返回
//   - 以 / 开头（相对路径）→ 前面拼上 API_BASE_URL
//   - 其它（名字/emoji）→ 原样返回
const buildIconUrl = (icon) => {
  if (!icon) return ''
  if (/^https?:\/\//i.test(icon)) return icon
  if (icon.startsWith('/')) return `${API_BASE_URL}${icon}`
  return icon
}

// 数字格式化
const formatNumber = (num) => {
  if (!num && num !== 0) return '0'
  return Number(num).toLocaleString('en-US')
}

// 时间分级(复用 Plaza 的逻辑)
const formatRelativeTime = (timestamp) => {
  if (!timestamp) return ''
  const ts = timestamp * 1000
  const startOfToday = new Date()
  startOfToday.setHours(0, 0, 0, 0)
  const startOfYesterday = new Date(startOfToday)
  startOfYesterday.setDate(startOfYesterday.getDate() - 1)
  const startOfThreeDaysAgo = new Date(startOfToday)
  startOfThreeDaysAgo.setDate(startOfThreeDaysAgo.getDate() - 3)

  if (ts >= startOfToday.getTime()) return '今日'
  if (ts >= startOfYesterday.getTime()) return '昨日'
  if (ts >= startOfThreeDaysAgo.getTime()) return '近三天'
  const d = new Date(ts)
  const pad = (n) => String(n).padStart(2, '0')
  return `${pad(d.getMonth() + 1)}/${pad(d.getDate())}`
}

// 模式选项(从后端 mode 枚举)
const MODE_OPTIONS = [
  { value: '', label: '全部模式' },
  { value: 'workflow', label: '工作流' },
  { value: 'advanced-chat', label: '对话流' },
  { value: 'chat', label: '基础对话' },
  { value: 'agent-chat', label: 'Agent 对话' },
  { value: 'completion', label: '文本生成' },
]

// 排序选项
const SORT_OPTIONS = [
  { value: 'default', label: '综合' },
  { value: 'heat', label: '热度最高' },
  { value: 'latest', label: '最新发布' },
  { value: 'recommend', label: '推荐优先' },
  { value: 'name', label: '名称 A-Z' },
]

// 标题映射
const TYPE_META = {
  hot: {
    title: '热门智能体',
    subtitle: '按近 7 天调用热度排序,看看平台最受欢迎的智能体',
  },
  latest: {
    title: '最新智能体',
    subtitle: '按上架时间排序,发现平台最新发布的智能体',
  },
  system: {
    title: '系统智能体',
    subtitle: '平台预置的系统级智能体,涵盖多种业务场景',
  },
  all: {
    title: '智能体列表',
    subtitle: '浏览所有可用的智能体,选择适合您需求的工具',
  },
}

// 数据标准化(兼容接口字段差异)
const normalize = (item) => {
  const iconType = item.icon_type || 'emoji'
  let iconValue = '🤖'
  if (iconType === 'image') {
    const raw = item.icon || item.icon_url || item.logo || ''
    iconValue = { type: 'image', url: buildIconUrl(raw) }
  } else {
    iconValue = resolveIcon(item.icon)
  }
  return {
    id: item.id,
    name: item.name || '',
    desc: item.description || item.introduction || '',
    icon: iconValue,
    iconType,
    iconBackground: item.icon_background || '#FFEAD5',
    heat: item.heat ?? item.call_count ?? 0,
    mode: item.mode || '',
    created_at: item.created_at,
    updated_at: item.updated_at,
    recommend_score: item.recommend_score ?? 0,
    tags: item.tags || [],
    // 系统智能体专属字段:用于点击时按 source_type 分流
    sourceType: item.source_type,
    sourceAppId: item.source_app_id,
  }
}

function AgentList() {
  const navigate = useNavigate()
  const [searchParams] = useSearchParams()
  const type = searchParams.get('type') || 'all'   // hot | latest | all
  const meta = TYPE_META[type] || TYPE_META.all

  const [agents, setAgents] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [clickingId, setClickingId] = useState(null)

  // 筛选条件
  const [keyword, setKeyword] = useState('')
  const [modeFilter, setModeFilter] = useState('')
  const [sortBy, setSortBy] = useState(() => {
    if (type === 'latest') return 'latest'
    if (type === 'hot') return 'heat'
    if (type === 'system') return 'recommend'
    return 'default'
  })

  useEffect(() => {
    let cancelled = false
    const fetchList = async () => {
      setLoading(true)
      setError('')
      try {
        // 根据 type 选择不同的接口:
        //   hot    → /business/apps/hottest
        //   latest → /business/apps/latest
        //   all    → /business/apps/list
        let res
        if (type === 'hot') {
          res = await getHottestApps()
        } else if (type === 'latest') {
          res = await getLatestApps()
        } else if (type === 'system') {
          // 系统智能体:GET /business/agent-pros(返回 {data:[...], has_more})
          res = await getAgentPros()
        } else {
          res = await getBusinessAppsList()
        }
        if (cancelled) return
        const list = (res?.data || res || []).map(normalize)
        setAgents(list)
      } catch (e) {
        if (!cancelled) setError(e?.message || '加载失败')
      } finally {
        if (!cancelled) setLoading(false)
      }
    }
    fetchList()
    return () => { cancelled = true }
  }, [type])

  // type 切换时同步默认排序,避免用户从 /agents?type=all 点"查看更多"后 sortBy 仍是 default
  useEffect(() => {
    if (type === 'latest') setSortBy('latest')
    else if (type === 'hot') setSortBy('heat')
    else if (type === 'system') setSortBy('recommend')
  }, [type])

  // 客户端筛选 + 排序
  const filtered = useMemo(() => {
    let list = agents.slice()
    // 关键词
    if (keyword.trim()) {
      const kw = keyword.trim().toLowerCase()
      list = list.filter(a => (a.name || '').toLowerCase().includes(kw) || (a.desc || '').toLowerCase().includes(kw))
    }
    // 模式
    if (modeFilter) {
      list = list.filter(a => a.mode === modeFilter)
    }
    // 排序
    switch (sortBy) {
      case 'heat':
        list.sort((a, b) => (b.heat || 0) - (a.heat || 0))
        break
      case 'latest':
        list.sort((a, b) => (b.created_at || 0) - (a.created_at || 0))
        break
      case 'recommend':
        list.sort((a, b) => (b.recommend_score || 0) - (a.recommend_score || 0))
        break
      case 'name':
        list.sort((a, b) => (a.name || '').localeCompare(b.name || ''))
        break
      default:
        // 综合:保持原顺序
        break
    }
    return list
  }, [agents, keyword, modeFilter, sortBy])

  // 点击卡片:按 source_type 分流
  //   - external → ExternalMock 占位页
  //   - 其它 → 用 sourceAppId(兜底 target_id)走权限校验后跳 execute/apply
  const handleCardClick = async (agent) => {
    if (!agent?.id || clickingId === agent.id) return
    setClickingId(agent.id)
    try {
      if (agent.sourceType === 'external') {
        navigate(`/agents/external/${agent.id}`, { state: { agent } })
        return
      }
      const appId = agent.sourceAppId || agent.id
      const res = await getAppApiKey(appId)
      const payload = res?.data ?? res ?? {}
      if (payload.has_permission) {
        navigate(`/agents/execute/${appId}`, {
          state: { agent: { ...agent, id: appId }, apiKey: payload.api_key || '' },
        })
      } else {
        navigate(`/agents/apply/${appId}`, { state: { agent: { ...agent, id: appId } } })
      }
    } catch (e) {
      navigate(`/agents/apply/${agent.sourceAppId || agent.id}`, {
        state: { agent, error: e?.message || '权限校验失败' },
      })
    } finally {
      setClickingId(null)
    }
  }

  const handleBack = () => {
    navigate('/')
  }

  // 模式标签友好显示
  const MODE_LABEL = {
    workflow: '工作流',
    'advanced-chat': '对话流',
    chat: '基础对话',
    'agent-chat': 'Agent',
    completion: '文本生成',
  }

  return (
    <div className="agent-list-page">
      {/* 页头 */}
      <div className="page-header agent-list-header">
        <button type="button" className="agent-list-back" onClick={handleBack} title="返回广场">
          <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
            <polyline points="15 18 9 12 15 6" />
          </svg>
          <span>返回广场</span>
        </button>
        <h1 className="page-title">{meta.title}</h1>
        <p className="page-subtitle">{meta.subtitle}</p>
      </div>

      {/* 筛选条 */}
      <div className="agent-list-filters">
        <div className="agent-list-search">
          <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <circle cx="11" cy="11" r="7" />
            <line x1="21" y1="21" x2="16.65" y2="16.65" />
          </svg>
          <input
            type="text"
            placeholder="搜索智能体名称或描述"
            value={keyword}
            onChange={e => setKeyword(e.target.value)}
          />
          {keyword && (
            <button type="button" className="agent-list-search-clear" onClick={() => setKeyword('')} title="清空">
              ×
            </button>
          )}
        </div>

        <div className="agent-list-select">
          <select value={modeFilter} onChange={e => setModeFilter(e.target.value)}>
            {MODE_OPTIONS.map(opt => (
              <option key={opt.value} value={opt.value}>{opt.label}</option>
            ))}
          </select>
        </div>

        <div className="agent-list-select">
          <select value={sortBy} onChange={e => setSortBy(e.target.value)}>
            {SORT_OPTIONS.map(opt => (
              <option key={opt.value} value={opt.value}>{opt.label}</option>
            ))}
          </select>
        </div>

        <div className="agent-list-result-count">
          共 <strong>{filtered.length}</strong> 个智能体
        </div>
      </div>

      {/* 列表 */}
      {loading ? (
        <div className="agent-list-status">加载中...</div>
      ) : error ? (
        <div className="agent-list-status agent-list-error">{error}</div>
      ) : filtered.length === 0 ? (
        <div className="agent-list-status agent-list-empty">暂无符合条件的智能体</div>
      ) : (
        <div className="card-grid agent-list-grid">
          {filtered.map(agent => {
            const isImageIcon = agent.icon && typeof agent.icon === 'object' && agent.icon.type === 'image'
            return (
              <div
                key={agent.id}
                className={`card agent-list-card ${clickingId === agent.id ? 'is-loading' : ''}`}
                onClick={() => handleCardClick(agent)}
              >
                <div className="card-header">
                  <div
                    className="card-icon"
                    style={isImageIcon ? { background: agent.iconBackground, overflow: 'hidden' } : undefined}
                  >
                    {isImageIcon ? (
                      <img src={agent.icon.url} alt={agent.name} className="card-icon-img" />
                    ) : (
                      agent.icon
                    )}
                  </div>
                  <div className="agent-list-card-meta">
                    <div className="card-title">{agent.name}</div>
                    {agent.mode && <span className="agent-list-mode-tag">{MODE_LABEL[agent.mode] || agent.mode}</span>}
                  </div>
                  {clickingId === agent.id && <span className="agent-list-card-checking">校验中…</span>}
                </div>
                <div className="card-description">{agent.desc || '暂无描述'}</div>
                <div className="agent-list-card-foot">
                  {type === 'hot' || (sortBy === 'heat' && agent.heat > 0) ? (
                    <span className="agent-list-stat">
                      <span className="agent-list-stat-icon">🔥</span>
                      <span>{formatNumber(agent.heat)} 次使用</span>
                    </span>
                  ) : null}
                  {agent.created_at ? (
                    <span className="agent-list-stat agent-list-stat-time">
                      <span className="agent-list-stat-icon">🕒</span>
                      <span>{formatRelativeTime(agent.created_at)}</span>
                    </span>
                  ) : null}
                </div>
              </div>
            )
          })}
        </div>
      )}
    </div>
  )
}

export default AgentList