import { useState, useEffect, useRef, useCallback } from 'react'
import { useLocation, useNavigate, useParams } from 'react-router-dom'
import {
  getAppBasicInfo,
  getAccessStatus,
  createAccessRequest
} from '@/service/business'
import emojiMartData from '@emoji-mart/data'

// 解析 emoji icon
const isNativeEmoji = (str) => /[\uD800-\uDBFF][\uDC00-\uDFFF]/.test(str || '')
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)
}

// 时间戳（秒）转 yyyy-MM-dd HH:mm
const formatDateTime = (ts) => {
  if (!ts && ts !== 0) return '-'
  const d = new Date(typeof ts === 'number' && ts < 1e12 ? ts * 1000 : ts)
  if (Number.isNaN(d.getTime())) return '-'
  const pad = (n) => String(n).padStart(2, '0')
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
}

// 状态 -> 文案 + 视觉类型
const STATUS_META = {
  not_requested: { label: '未申请', tone: 'neutral', help: '该智能体需要申请权限后才能使用' },
  pending:        { label: '审核中', tone: 'pending', help: '申请已提交，正在等待管理员审核' },
  approved:       { label: '已通过', tone: 'success', help: '申请已通过，可进入执行页' },
  rejected:       { label: '已拒绝', tone: 'rejected', help: '申请被拒绝，可调整理由后重新申请' },
  has_permission: { label: '已有权限', tone: 'success', help: '你已拥有该智能体的使用权限' },
  no_permission:  { label: '无权限', tone: 'rejected', help: '该智能体为私有，暂不开放申请' }
}

// 申请权限枚举 -> 友好文案
const PERMISSION_LABEL = {
  public: '公开',
  partial: '指定用户',
  private: '私有'
}

function AgentApply() {
  const { appId } = useParams()
  const location = useLocation()
  const navigate = useNavigate()
  const passedAgent = location.state?.agent || { id: appId, name: '智能体' }

  // ===== 数据状态 =====
  const [appInfo, setAppInfo] = useState(null)            // basic-info 返回
  const [status, setStatus] = useState(null)              // access-status.status
  const [accessRequest, setAccessRequest] = useState(null) // access-status.request
  const [hasPermission, setHasPermission] = useState(false)
  const [progress, setProgress] = useState('')            // 进度描述
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  // ===== 申请表单 =====
  const [reason, setReason] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [submitError, setSubmitError] = useState('')

  // ===== 轮询（仅 pending 时启用） =====
  const pollTimerRef = useRef(null)
  const stopPolling = useCallback(() => {
    if (pollTimerRef.current) {
      clearInterval(pollTimerRef.current)
      pollTimerRef.current = null
    }
  }, [])

  // 加载 basic-info + access-status
  const loadAll = useCallback(async (showLoading = true) => {
    if (!appId) return
    if (showLoading) setLoading(true)
    setError('')
    try {
      const [basicRes, statusRes] = await Promise.all([
        getAppBasicInfo(appId),
        getAccessStatus(appId)
      ])

      // basic-info: 后端可能直接返回对象，也可能 {data: {...}}
      const basic = basicRes?.data || basicRes || {}
      setAppInfo({
        id: basic.id || appId,
        name: basic.name || passedAgent.name || '智能体',
        description: basic.description || '',
        introduction: basic.introduction || '',
        icon: resolveIcon(basic.icon),
        iconBackground: basic.icon_background || '#FFEAD5',
        mode: basic.mode || '',
        version: basic.version || '',
        versionDescription: basic.version_description || '',
        listedAt: basic.listed_at,
        createdAt: basic.created_at,
        updatedAt: basic.updated_at,
        appPermission: basic.app_permission || '',
        isListed: Boolean(basic.is_listed)
      })

      // access-status
      const st = statusRes?.data || statusRes || {}
      setStatus(st.status || '')
      setProgress(st.progress || st.status || '')
      setHasPermission(Boolean(st.has_permission))
      setAccessRequest(st.request || null)
    } catch (e) {
      setError(e?.message || '加载申请信息失败')
    } finally {
      if (showLoading) setLoading(false)
    }
  }, [appId, passedAgent.name])

  // 首次加载
  useEffect(() => {
    loadAll(true)
    return () => stopPolling()
  }, [loadAll, stopPolling])

  // pending 时启动轮询
  useEffect(() => {
    stopPolling()
    if (status === 'pending') {
      pollTimerRef.current = setInterval(() => {
        // 静默刷新，不触发 loading
        loadAll(false)
      }, 8000)
    }
    return stopPolling
  }, [status, loadAll, stopPolling])

  // ===== 提交申请 =====
  const handleSubmit = async () => {
    if (!reason.trim()) {
      setSubmitError('请填写使用理由')
      return
    }
    setSubmitting(true)
    setSubmitError('')
    try {
      const res = await createAccessRequest(appId, reason.trim())
      const payload = res?.data || res || {}
      // 重新拉一次最新状态
      await loadAll(false)
      if (payload.status === 'already_has_permission') {
        setStatus('has_permission')
        setHasPermission(true)
      } else {
        setStatus('pending')
        setProgress('pending')
      }
      if (payload.request) {
        setAccessRequest(payload.request)
      }
    } catch (e) {
      setSubmitError(e?.message || '提交申请失败')
    } finally {
      setSubmitting(false)
    }
  }

  // ===== 重新申请（被拒绝后） =====
  const handleReapply = () => {
    setStatus('not_requested')
    setAccessRequest(null)
    setReason('')
    setSubmitError('')
  }

  // 跳到执行页
  const goExecute = () => {
    navigate(`/agents/execute/${appId}`, {
      state: { agent: appInfo ? { ...passedAgent, ...appInfo } : passedAgent }
    })
  }

  // ===== 渲染辅助 =====
  const meta = STATUS_META[status] || { label: status || '未知', tone: 'neutral', help: '' }
  const showApplyForm = status === 'not_requested'
  const showPending   = status === 'pending'
  const showRejected  = status === 'rejected'
  const showApproved  = status === 'approved' || status === 'has_permission'
  const showNoPerm    = status === 'no_permission'

  return (
    <div className="agent-apply">
      {/* 页头 */}
      <div className="page-header">
        <button className="back-btn" onClick={() => navigate(-1)}>‹ 返回广场</button>
      </div>

      {/* 智能体详情卡（含版本） */}
      <div className="apply-card apply-detail-card">
        <div className="apply-agent-info">
          <div className="apply-agent-icon" style={{ background: appInfo?.iconBackground || passedAgent.iconBackground || '#FFEAD5' }}>
            {appInfo?.icon || passedAgent.icon || '🤖'}
          </div>
          <div className="apply-agent-meta">
            <div className="apply-agent-name">
              {loading ? '加载中…' : (appInfo?.name || passedAgent.name || '智能体')}
            </div>
            <div className="apply-agent-sub">
              {appInfo?.mode && <span className="apply-tag">{appInfo.mode}</span>}
              {appInfo?.appPermission && (
                <span className={`apply-tag apply-perm-${appInfo.appPermission}`}>
                  {PERMISSION_LABEL[appInfo.appPermission] || appInfo.appPermission}
                </span>
              )}
              {appInfo?.version && <span className="apply-tag apply-tag-version">v{appInfo.version}</span>}
              {appInfo?.isListed && <span className="apply-tag apply-tag-listed">已上架</span>}
            </div>
            {(appInfo?.description || passedAgent.desc) && (
              <div className="apply-agent-desc">{appInfo?.description || passedAgent.desc}</div>
            )}
          </div>
        </div>

        {/* 版本说明 */}
        {appInfo?.versionDescription && (
          <div className="apply-version-block">
            <div className="apply-version-head">
              <span className="apply-version-label">版本说明</span>
              <span className="apply-version-time">
                上架时间：{formatDateTime(appInfo.listedAt || appInfo.updatedAt)}
              </span>
            </div>
            <div className="apply-version-desc">{appInfo.versionDescription}</div>
          </div>
        )}

        {/* 介绍（长描述） */}
        {appInfo?.introduction && (
          <div className="apply-intro-block">
            <div className="apply-intro-label">智能体介绍</div>
            <div className="apply-intro-desc">{appInfo.introduction}</div>
          </div>
        )}

        {error && <div className="apply-error-tip">⚠ {error}（已使用基础信息）</div>}
      </div>

      {/* 申请进度区 */}
      <div className={`apply-card apply-status-card apply-tone-${meta.tone}`}>
        <div className="apply-status-row">
          <div className="apply-status-icon">
            {meta.tone === 'success' && '✅'}
            {meta.tone === 'pending' && '⏳'}
            {meta.tone === 'rejected' && '❌'}
            {meta.tone === 'neutral' && 'ℹ️'}
          </div>
          <div className="apply-status-meta">
            <div className="apply-status-label">当前状态：{meta.label}</div>
            <div className="apply-status-help">{meta.help}</div>
          </div>
          {showPending && <div className="apply-status-polling">轮询中…</div>}
        </div>

        {/* 申请详情（pending / approved / rejected 都展示） */}
        {accessRequest && (showPending || showApproved || showRejected) && (
          <div className="apply-request-block">
            <div className="apply-request-row">
              <span className="apply-request-key">申请编号</span>
              <span className="apply-request-val apply-mono">{accessRequest.id}</span>
            </div>
            <div className="apply-request-row">
              <span className="apply-request-key">提交时间</span>
              <span className="apply-request-val">{formatDateTime(accessRequest.created_at)}</span>
            </div>
            {accessRequest.reason && (
              <div className="apply-request-row">
                <span className="apply-request-key">申请理由</span>
                <span className="apply-request-val">{accessRequest.reason}</span>
              </div>
            )}
            {accessRequest.review_message && (
              <div className="apply-request-row">
                <span className="apply-request-key">审核备注</span>
                <span className="apply-request-val">{accessRequest.review_message}</span>
              </div>
            )}
            {accessRequest.reviewer_name && (
              <div className="apply-request-row">
                <span className="apply-request-key">审核人</span>
                <span className="apply-request-val">{accessRequest.reviewer_name} · {formatDateTime(accessRequest.reviewed_at)}</span>
              </div>
            )}
          </div>
        )}

        {/* 表单 / 操作按钮 */}
        <div className="apply-form">
          {showApplyForm && (
            <label className="apply-label">
              <span>使用场景 / 申请理由 <em>*</em></span>
              <textarea
                className="apply-textarea"
                rows={5}
                value={reason}
                onChange={e => { setReason(e.target.value); setSubmitError('') }}
                placeholder="请描述你计划如何使用该智能体，以便审批人快速评估..."
              />
              {submitError && <div className="apply-field-error">{submitError}</div>}
            </label>
          )}

          <div className="apply-actions">
            {showApplyForm && (
              <>
                <button className="apply-secondary-btn" onClick={() => navigate(-1)}>取消</button>
                <button
                  className="apply-primary-btn"
                  onClick={handleSubmit}
                  disabled={!reason.trim() || submitting}
                >
                  {submitting ? '提交中...' : '提交申请'}
                </button>
              </>
            )}
            {showPending && (
              <button className="apply-secondary-btn" onClick={() => navigate(-1)}>返回广场</button>
            )}
            {showApproved && (
              <>
                <button className="apply-secondary-btn" onClick={() => navigate('/plaza')}>返回广场</button>
                <button className="apply-primary-btn" onClick={goExecute}>前往执行页</button>
              </>
            )}
            {showRejected && (
              <>
                <button className="apply-secondary-btn" onClick={() => navigate('/plaza')}>返回广场</button>
                <button className="apply-primary-btn" onClick={handleReapply}>重新申请</button>
              </>
            )}
            {showNoPerm && (
              <button className="apply-secondary-btn" onClick={() => navigate('/plaza')}>返回广场</button>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}

export default AgentApply
