import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { Button, Card, Empty, Spin, Tag, Tooltip, Typography } from '@arco-design/web-react'
import { getRecommendedApps, getHottestApps, getLatestApps, getAgentPros, getAppApiKey } from '@/service/business'
import { API_BASE_URL } from '@/config'

// 把后端返回的 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
}
import emojiMartData from '@emoji-mart/data'
import './Plaza.css'

// 检查是否是 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 || '🤖'
}

// 把后端 icon 字段统一转换为 native Unicode emoji
const resolveIcon = (icon) => {
  if (!icon) return '🤖'
  if (isNativeEmoji(icon)) return icon
  return emojiNameToNative(icon)
}

// 数字格式化：19820431 -> "19,820,431"
const formatNumber = (num) => {
  if (!num && num !== 0) return '0'
  return Number(num).toLocaleString('en-US')
}

// 时间戳转 "03/03 14:30" 格式
const formatDate = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp * 1000)
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${month}/${day} ${hours}:${minutes}`
}

// 时间分级: 今日 / 昨日 / 仅三天(3天内) / 具体时间(MM/DD HH:mm)
//   同一份逻辑同时被"推荐智能体"和"最新智能体"使用
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 '近三天'
  return formatDate(timestamp)
}

const OverflowTip = ({ content, children }) => (
  <Tooltip content={content || '-'} position="top" mini>
    {children}
  </Tooltip>
)

// 模块级守卫：useRef 在 React.StrictMode dev 二次挂载时会被重置，
// 改用模块级变量可以跨过 StrictMode 的"卸载→重挂载"。
// 卸载时通过 cleanup 把 flag 清零，保证离开页面后再回来仍能重新请求。
let plazaInitStarted = false

function Plaza() {
  const navigate = useNavigate()
  const [hotModels, setHotModels] = useState([])      // 热门大模型
  const [hotAgents, setHotAgents] = useState([])       // 热门智能体
  const [newAgents, setNewAgents] = useState([])       // 最新智能体
  const [systemAgents, setSystemAgents] = useState([]) // 系统智能体（Agent Pro）
  const [loading, setLoading] = useState({ model: true, hot: true, latest: true, system: true })
  const [error, setError] = useState({})
  const [clickingId, setClickingId] = useState(null)   // 正在请求权限的智能体 id

  useEffect(() => {
    if (plazaInitStarted) return
    plazaInitStarted = true
    fetchRecommended()   // 推荐智能体：GET /business/apps/recommended
    fetchHot()           // 热门智能体：GET /business/apps/hottest
    fetchLatest()        // 最新智能体：GET /business/apps/latest
    fetchAgentPros()     // 系统智能体：GET /business/agent-pros
    return () => {
      // 离开 Plaza 后再回来，重新允许拉数据
      plazaInitStarted = false
    }
  }, [])

  // 点击智能体：调用权限接口，根据 has_permission 跳转
  const handleAgentClick = async (agent) => {
    // 调试：打印 agent 完整信息
    console.log('[handleAgentClick] agent →', agent)
    if (!agent?.id || clickingId === agent.id) return
    setClickingId(agent.id)
    try {
      const resp = await getAppApiKey(agent.id)
      console.log('[handleAgentClick] getAppApiKey resp →', resp)
      // 兼容多种返回结构：Dify 不同版本可能返回不同格式
      const apiKey = resp?.api_key
        ?? resp?.data?.api_key
        ?? resp?.key
        ?? resp?.data?.key
        ?? resp?.data
      console.log('[handleAgentClick] parsed apiKey →', apiKey)
      if (!apiKey) {
        throw new Error('getAppApiKey 未返回 api_key（请把上面 resp 贴给开发者）')
      }
      // ... 原有逻辑继续
      const hasPermission = resp?.has_permission ?? resp?.data?.has_permission
      if (hasPermission) {
        navigate(`/agents/execute/${agent.id}`, { state: { apiKey, agent } })
      } else {
        navigate(`/agents/apply/${agent.id}`, { state: { agent } })
      }
    } catch (err) {
      console.error('[handleAgentClick] error →', err)
      setClickingId(null)
    }
    try {
      const res = await getAppApiKey(agent.id)
      const payload = res?.data ?? res ?? {}
      if (payload.has_permission) {
        navigate(`/agents/execute/${agent.id}`, { state: { agent, apiKey: payload.api_key || '' } })
      } else {
        navigate(`/agents/apply/${agent.id}`, { state: { agent } })
      }
    } catch (e) {
      // 接口异常时默认跳转到申请页
      navigate(`/agents/apply/${agent.id}`, { state: { agent, error: e?.message || '权限校验失败' } })
    } finally {
      setClickingId(null)
    }
  }

  const handleData = (data) => {
    return (data?.data || data || []).map(item => ({
      id: item.id,
      name: item.name || '',
      desc: item.description || '',
      icon: resolveIcon(item.icon),
      iconBackground: item.icon_background || '#FFEAD5',
      heat: item.heat || item.call_count,
      created_at: item.created_at,
      // 最新智能体的"上架时间"独立字段,广场最新区展示用它
      listed_at: item.listed_at ?? item.created_at,
      author: item.author_name || item.created_by || item.creator || '',
      mode: item.mode
    }))
  }

  const fetchRecommended = async () => {
    try {
      const res = await getRecommendedApps()
      setHotModels(handleData(res))
    } catch (e) {
      setError(prev => ({ ...prev, model: e.message || '加载失败' }))
    } finally {
      setLoading(prev => ({ ...prev, model: false }))
    }
  }

  const fetchHot = async () => {
    try {
      const res = await getHottestApps()
      setHotAgents(handleData(res))
    } catch (e) {
      setError(prev => ({ ...prev, hot: e.message || '加载失败' }))
    } finally {
      setLoading(prev => ({ ...prev, hot: false }))
    }
  }

  const fetchLatest = async () => {
    try {
      const res = await getLatestApps()
      setNewAgents(handleData(res))
    } catch (e) {
      setError(prev => ({ ...prev, latest: e.message || '加载失败' }))
    } finally {
      setLoading(prev => ({ ...prev, latest: false }))
    }
  }

  // 系统智能体
  const handleSystemAgentData = (data) => {
    // 兼容 { data: [...] } / 直接数组 / 其它
    const list = data?.data || data || []
    return list.map(item => {
      // icon 兼容:
      //   icon_type === 'image' → 用 item.icon 当成相对/绝对路径,前面拼 API_BASE_URL
      //   icon_type === 'emoji' (或没声明) → 用 item.icon 当 emoji mart 名字或 native emoji
      const iconType = item.icon_type || 'emoji'
      let iconValue = '🤖'
      if (iconType === 'image') {
        const raw = item.icon || item.logo || ''
        iconValue = { type: 'image', url: buildIconUrl(raw) }
      } else if (typeof item.icon === 'string') {
        iconValue = item.icon
      }
      return {
        id: item.id,
        name: item.name || '',
        desc: item.description || '',
        icon: iconValue,
        iconType,
        iconBackground: item.icon_background || '#FFEAD5',
        // source_type / source_app_id 用于点击时按 Layout 同样的规则分流
        sourceType: item.source_type,
        sourceAppId: item.source_app_id,
      }
    })
  }

  // 点击系统智能体卡片:按 source_type 分流
  //   - external → ExternalMock 占位页
  //   - internal / 其它 → 用 source_app_id(兜底 target_id)走权限校验后跳 execute/apply
  const handleSystemAgentClick = 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 fetchAgentPros = async () => {
    try {
      const res = await getAgentPros()
      // 广场只展示前 6 个作为精选,完整列表在 AgentList(/agents)里
      setSystemAgents(handleSystemAgentData(res).slice(0, 6))
    } catch (e) {
      setError(prev => ({ ...prev, system: e.message || '加载失败' }))
    } finally {
      setLoading(prev => ({ ...prev, system: false }))
    }
  }

  const renderAgentRow = (agent, idx, rightInfo) => (
    <div
      key={agent.id}
      className={`plaza-table-row ${clickingId === agent.id ? 'plaza-row-loading' : ''}`}
      onClick={() => handleAgentClick(agent)}
    >
      <div className="plaza-row-rank">{idx + 1}</div>
      <div
        className="plaza-row-icon plaza-list-icon-native"
        style={{ background: agent.iconBackground }}
      >
        {agent.icon}
      </div>
      <div className="plaza-row-info">
        <OverflowTip content={agent.name}>
          <Typography.Text className="plaza-row-name">{agent.name}</Typography.Text>
        </OverflowTip>
      </div>
      <div className="plaza-row-extra">
        {clickingId === agent.id ? <span className="plaza-row-checking">校验中…</span> : rightInfo}
      </div>
    </div>
  )

  const renderListState = (type, list, renderContent) => {
    if (loading[type]) return <div className="plaza-status"><Spin size={20} tip="加载中..." /></div>
    if (error[type]) return <div className="plaza-status"><Empty description={error[type]} /></div>
    if (list.length === 0) return <div className="plaza-status"><Empty description="暂无数据" /></div>
    return renderContent()
  }

  return (
    <div className="plaza-container">
      <Card className="plaza-hero plaza-hero-compact" bordered>
        <div className="plaza-hero-content">
          <Typography.Title heading={3} className="plaza-hero-title">
            <span className="plaza-hero-icon">🤖</span>
            智能体广场
          </Typography.Title>
          <OverflowTip content="汇聚平台所有公开 AI 智能体，支持一键预览、体验、复用与收藏，实现优质智能体能力共享、快速赋能业务落地">
            <Typography.Text className="plaza-hero-desc">汇聚平台所有公开 AI 智能体，支持一键预览、体验、复用与收藏，实现优质智能体能力共享、快速赋能业务落地</Typography.Text>
          </OverflowTip>
        </div>
        <div className="plaza-hero-stats">
          <div><strong>{hotModels.length + hotAgents.length + newAgents.length}</strong><span>广场推荐</span></div>
          <div><strong>{systemAgents.length}</strong><span>系统精选</span></div>
        </div>
      </Card>

      <div className="plaza-section plaza-section-lists">
        <Card className="plaza-list-card" bordered>
          <div className="plaza-list-header">
            <span className="plaza-list-title">
              <span className="plaza-title-icon">👍</span>推荐智能体
            </span>
          </div>
          <div className="plaza-list">
            {renderListState('model', hotModels, () => hotModels.map((agent, idx) => {
                const relTime = formatRelativeTime(agent.created_at)
                return renderAgentRow(agent, idx,
                  <span className="plaza-extra-author-block">
                    {agent.author && (
                      <OverflowTip content={agent.author}>
                        <span className="plaza-extra-username">{agent.author}</span>
                      </OverflowTip>
                    )}
                    <span className={`plaza-extra-time plaza-time-${relTime}`}>{relTime}</span>
                  </span>
                )
              }))}
          </div>
        </Card>

        <Card className="plaza-list-card" bordered>
          <div className="plaza-list-header">
            <span className="plaza-list-title">
              <span className="plaza-title-icon">🔥</span>热门智能体<span className="plaza-title-badge">（近7d）</span>
            </span>
            <Button
              type="text"
              size="mini"
              className="plaza-list-more"
              onClick={() => navigate('/agents?type=hot')}
            >查看更多</Button>
          </div>
          <div className="plaza-list">
            {renderListState('hot', hotAgents, () => hotAgents.map((agent, idx) => renderAgentRow(agent, idx,
                <span className={`plaza-extra-heat-badge ${idx < 3 ? `plaza-heat-top plaza-heat-top-${idx + 1}` : 'plaza-heat-normal'}`}>
                  {idx < 3 && <span className="plaza-heat-fire">🔥</span>}
                  {formatNumber(agent.heat)}
                </span>
              )))}
          </div>
        </Card>

        <Card className="plaza-list-card" bordered>
          <div className="plaza-list-header">
            <span className="plaza-list-title">
              <span className="plaza-title-icon">✨</span>最新智能体
            </span>
            <Button
              type="text"
              size="mini"
              className="plaza-list-more"
              onClick={() => navigate('/agents?type=latest')}
            >查看更多</Button>
          </div>
          <div className="plaza-list">
            {renderListState('latest', newAgents, () => newAgents.map((agent, idx) => {
                const relTime = formatRelativeTime(agent.listed_at)
                return renderAgentRow(agent, idx,
                  <span className={`plaza-extra-time plaza-time-${relTime}`}>
                    {relTime}
                  </span>
                )
              }))}
          </div>
        </Card>
      </div>

      <div className="plaza-section">
        <div className="plaza-section-header">
          <Typography.Title heading={5} className="plaza-section-title">系统智能体</Typography.Title>
          <Button
            type="text"
            size="small"
            className="plaza-list-more"
            onClick={() => navigate('/agents?type=system')}
          >查看更多</Button>
        </div>
        <div className="plaza-system-grid">
          {loading.system ? (
            <div className="plaza-system-status plaza-system-loading"><Spin size={20} tip="加载中..." /></div>
          ) : error.system ? (
            <div className="plaza-system-status plaza-system-error"><Empty description={error.system} /></div>
          ) : systemAgents.length === 0 ? (
            <div className="plaza-system-status plaza-system-empty"><Empty description="暂无系统智能体" /></div>
          ) : (
            <>
              {systemAgents.map(agent => {
                const isImageIcon = agent.icon && typeof agent.icon === 'object' && agent.icon.type === 'image'
                return (
                  <Card
                    key={agent.id}
                    className="plaza-system-item plaza-system-card"
                    onClick={() => handleSystemAgentClick(agent)}
                    title={agent.desc || agent.name}
                    bordered
                  >
                    <div
                      className="plaza-system-icon"
                      style={isImageIcon ? { background: agent.iconBackground || '#FFEAD5' } : undefined}
                    >
                      {isImageIcon ? (
                        <img src={agent.icon.url} alt={agent.name} className="plaza-system-icon-img" />
                      ) : (
                        resolveIcon(agent.icon)
                      )}
                    </div>
                    <OverflowTip content={agent.name}>
                      <Typography.Text className="plaza-system-name">{agent.name}</Typography.Text>
                    </OverflowTip>
                    <OverflowTip content={agent.desc || '暂无介绍'}>
                      <Typography.Paragraph className="plaza-system-desc" ellipsis={{ rows: 2 }}>{agent.desc || '暂无介绍'}</Typography.Paragraph>
                    </OverflowTip>
                  </Card>
                )
              })}
            </>
          )}
        </div>
      </div>

      <div className="plaza-section">
        <div className="plaza-section-header">
          <Typography.Title heading={5} className="plaza-section-title">智能体列表</Typography.Title>
        </div>
        <div className="plaza-agent-grid">
          {[
            { id: 1, name: '代码助手 Pro', description: '智能代码生成、调试和优化，支持多种编程语言。', icon: '💻', tags: ['开发', '代码'] },
            { id: 2, name: '文档生成器', description: '自动生成技术文档、API文档和项目文档。', icon: '📚', tags: ['文档', '写作'] },
            { id: 3, name: '数据分析大师', description: '智能数据分析、可视化和报告生成。', icon: '📊', tags: ['数据', '分析'] },
            { id: 4, name: '内容创作专家', description: 'AI驱动的内容创作，支持文章、博客、营销文案。', icon: '✍️', tags: ['内容', '营销'] },
            { id: 5, name: '智能客服', description: '7x24小时智能客服，自动回答用户问题。', icon: '🎧', tags: ['客服'] },
            { id: 6, name: '翻译官', description: '多语言智能翻译，保持语义准确和语境连贯。', icon: '🌍', tags: ['翻译'] },
            { id: 7, name: '图像识别', description: '智能图像识别，支持物体检测、人脸识别。', icon: '🖼️', tags: ['图像'] },
            { id: 8, name: '语音助手', description: '智能语音识别与合成，准确率高达 99%。', icon: '🎙️', tags: ['语音'] }
          ].map(agent => (
            <Card key={agent.id} className="plaza-agent-card" bordered hoverable>
              <div className="plaza-agent-card-header">
                <div className="plaza-agent-card-icon">{agent.icon}</div>
                <div>
                  <OverflowTip content={agent.name}>
                    <Typography.Text className="plaza-agent-card-title">{agent.name}</Typography.Text>
                  </OverflowTip>
                </div>
              </div>
              <OverflowTip content={agent.description}>
                <Typography.Paragraph className="plaza-agent-card-description" ellipsis={{ rows: 2 }}>{agent.description}</Typography.Paragraph>
              </OverflowTip>
              <div className="plaza-agent-card-tags">
                {agent.tags.map((tag, idx) => (
                  <OverflowTip key={idx} content={tag}>
                    <Tag color="arcoblue">{tag}</Tag>
                  </OverflowTip>
                ))}
              </div>
            </Card>
          ))}
        </div>
      </div>
    </div>
  )
}

export default Plaza
