import { useMemo, useState, useEffect } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import {
  Layout as ArcoLayout,
  Menu,
  Button,
  Avatar,
  Dropdown,
  Typography,
  Spin,
  Message,
} from '@arco-design/web-react'
import {
  IconApps,
  IconMenuFold,
  IconMenuUnfold,
  IconHistory,
  IconRobot,
  IconUser,
  IconSettings,
  IconQuestionCircle,
  IconExport,
  IconLock,
} from '@arco-design/web-react/icon'
import { useAuth } from '@/contexts/AuthContext'
import { logout as logoutService } from '@/service/auth'
import { useUserProfile } from '@/service/account'
import { clearTokens } from '@/utils/auth'
import { getMyRecommendedApps, getAppApiKey } from '@/service/business'
import { API_BASE_URL } from '@/config'
import emojiMartData from '@emoji-mart/data'
import ProfileModal from './ProfileModal'
import ApiKeyModal from './ApiKeyModal'
import '../App.css'

const { Sider, Header, Content } = ArcoLayout
const MenuItem = Menu.Item
const SubMenu = Menu.SubMenu
const SIDEBAR_COLLAPSED_KEY = 'sidebar_collapsed'

const isNativeEmoji = (str) => {
  if (!str) return false
  return /[\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)
}

const buildIconUrl = (icon) => {
  if (!icon) return ''
  if (/^https?:\/\//i.test(icon)) return icon
  if (icon.startsWith('/')) return `${API_BASE_URL}${icon}`
  return icon
}

function Layout({ children }) {
  const location = useLocation()
  const navigate = useNavigate()
  const { logout } = useAuth()
  const [showProfile, setShowProfile] = useState(false)
  const [showApiKey, setShowApiKey] = useState(false)
  const [collapsed, setCollapsed] = useState(() => {
    try { return localStorage.getItem(SIDEBAR_COLLAPSED_KEY) === '1' } catch { return false }
  })
  const [recommendedAgents, setRecommendedAgents] = useState([])
  const [recLoading, setRecLoading] = useState(false)
  const [recError, setRecError] = useState('')
  const [navClickingId, setNavClickingId] = useState(null)
  const [userProfile, setUserProfile] = useState(null)

  useEffect(() => {
    let cancelled = false
    const fetchRecommended = async () => {
      setRecLoading(true)
      setRecError('')
      try {
        const res = await getMyRecommendedApps()
        if (cancelled) return
        const list = (res?.data || res || []).map(item => {
          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.target_id,
            name: item.name || '未命名',
            desc: item.description || '',
            icon: iconValue,
            iconBackground: item.icon_background || '#FFEAD5',
            mode: item.mode || '',
            targetType: item.target_type,
            sourceType: item.source_type,
            sourceAppId: item.source_app_id,
            sourceName: item.source_name,
          }
        })
        setRecommendedAgents(list)
      } catch (e) {
        if (!cancelled) setRecError(e?.message || '加载失败')
      } finally {
        if (!cancelled) setRecLoading(false)
      }
    }
    fetchRecommended()
    return () => { cancelled = true }
  }, [])

  useEffect(() => {
    let cancelled = false
    const fetchUserProfile = async () => {
      try {
        const profile = await useUserProfile()
        if (!cancelled) setUserProfile(profile?.data ?? profile ?? null)
      } catch (e) {
        if (!cancelled) setUserProfile(null)
      }
    }
    fetchUserProfile()
    return () => { cancelled = true }
  }, [])

  const selectedKeys = useMemo(() => {
    const pathname = location.pathname
    if (pathname === '/' || pathname === '/plaza') return ['plaza']
    if (pathname === '/history') return ['history']
    if (pathname === '/available') return ['available']
    if (pathname.startsWith('/agents/execute/')) return [`agent:${pathname.split('/').pop()}`]
    if (pathname.startsWith('/agents/external/')) return [`external:${pathname.split('/').pop()}`]
    return []
  }, [location.pathname])

  const headerInfo = useMemo(() => {
    const pathname = location.pathname
    if (pathname === '/' || pathname === '/plaza') return { kicker: '智能体广场', title: '发现并使用推荐智能体' }
    if (pathname === '/history') return { kicker: '历史记录', title: '查看最近的智能体执行记录' }
    if (pathname === '/available') return { kicker: '可用智能体', title: '管理已开通权限的智能体' }
    if (pathname.startsWith('/agents/execute/')) return { kicker: '智能体', title: '当前会话与任务执行' }
    if (pathname.startsWith('/agents/external/')) return { kicker: '外部智能体', title: '跳转并使用外部服务' }
    if (pathname.startsWith('/agents/apply/')) return { kicker: '权限申请', title: '申请智能体使用权限' }
    return { kicker: '工作台', title: 'AI Agent 智能体平台' }
  }, [location.pathname])

  const userDisplayName = userProfile?.name || userProfile?.email || '用户'

  const toggleSidebar = () => {
    setCollapsed(prev => {
      const next = !prev
      try { localStorage.setItem(SIDEBAR_COLLAPSED_KEY, next ? '1' : '0') } catch {}
      return next
    })
  }

  const handleAgentNavClick = async (agent) => {
    if (!agent?.id || navClickingId === agent.id) return
    setNavClickingId(agent.id)
    if (agent.sourceType === 'external') {
      navigate(`/agents/external/${agent.id}`, { state: { agent } })
      setNavClickingId(null)
      return
    }

    const appId = agent.sourceAppId || agent.id
    try {
      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 (err) {
      navigate(`/agents/apply/${appId}`, {
        state: { agent: { ...agent, id: appId }, error: err?.message || '权限校验失败' },
      })
    } finally {
      setNavClickingId(null)
    }
  }

  const handleLogout = async () => {
    try {
      await logoutService()
    } catch (e) {
      // Logout should still clear local state even when the server call fails.
    }
    clearTokens()
    logout()
    navigate('/login')
  }

  const handleAdmin = () => {
    Message.info('后台管理功能开发中')
  }

  const handleHelp = () => {
    Message.info('使用说明功能开发中')
  }

  const renderAgentIcon = (agent) => {
    if (agent.icon && typeof agent.icon === 'object' && agent.icon.type === 'image') {
      return (
        <span className="layout-agent-icon" style={{ background: agent.iconBackground || '#FFEAD5' }}>
          <img src={buildIconUrl(agent.icon.url)} alt="" />
        </span>
      )
    }
    return <span className="layout-agent-icon layout-agent-emoji">{resolveIcon(agent.icon)}</span>
  }

  const userMenu = (
    <Menu className="layout-user-menu">
      <MenuItem key="profile" onClick={() => setShowProfile(true)}>
        <IconUser /> 个人资料
      </MenuItem>
      <MenuItem key="apikey" onClick={() => setShowApiKey(true)}>
        <IconLock /> API Key
      </MenuItem>
      <MenuItem key="admin" onClick={handleAdmin}>
        <IconSettings /> 后台管理
      </MenuItem>
      <MenuItem key="help" onClick={handleHelp}>
        <IconQuestionCircle /> 使用说明
      </MenuItem>
      <MenuItem key="logout" className="layout-user-menu-danger" onClick={handleLogout}>
        <IconExport /> 退出登录
      </MenuItem>
    </Menu>
  )

  return (
    <ArcoLayout className="app arco-shell">
      <Sider
        className="arco-shell-sider"
        width={248}
        collapsed={collapsed}
        collapsedWidth={64}
        trigger={null}
      >
        <div className="arco-shell-brand" onClick={() => navigate('/plaza')}>
          <img src="/logo.png" alt="Logo" className="arco-shell-logo" />
          {!collapsed && (
            <div className="arco-shell-brand-text">
              <Typography.Text className="arco-shell-brand-name">AI agentic</Typography.Text>
              <Typography.Text className="arco-shell-brand-subtitle">智能体平台</Typography.Text>
            </div>
          )}
        </div>

        <Menu
          className="arco-shell-menu"
          selectedKeys={selectedKeys}
          defaultOpenKeys={['agents', 'my']}
          collapse={collapsed}
          autoOpen
          hasCollapseButton={false}
        >
          <MenuItem key="plaza" onClick={() => navigate('/plaza')}>
            <IconApps />
            <span>广场</span>
          </MenuItem>

          <SubMenu key="agents" title={<><IconRobot /><span>智能体</span></>}>
            {recLoading && (
              <MenuItem key="agents-loading" disabled>
                <Spin size={14} /> 加载中
              </MenuItem>
            )}
            {!recLoading && recError && (
              <MenuItem key="agents-error" disabled>{recError}</MenuItem>
            )}
            {!recLoading && !recError && recommendedAgents.length === 0 && (
              <MenuItem key="agents-empty" disabled>暂无推荐智能体</MenuItem>
            )}
            {!recLoading && !recError && recommendedAgents.map(agent => {
              const targetAppId = agent.sourceAppId || agent.id
              const menuKey = agent.sourceType === 'external' ? `external:${agent.id}` : `agent:${targetAppId}`
              return (
                <MenuItem key={menuKey} onClick={() => handleAgentNavClick(agent)}>
                  {renderAgentIcon(agent)}
                  <span className="layout-agent-name">{agent.name}</span>
                  {navClickingId === agent.id && <Spin size={12} />}
                </MenuItem>
              )
            })}
          </SubMenu>

          {/* <SubMenu key="my" title={<><IconUser /><span>我的</span></>}>
            <MenuItem key="history" onClick={() => navigate('/history')}>
              <IconHistory />
              <span>历史记录</span>
            </MenuItem>
            <MenuItem key="available" onClick={() => navigate('/available')}>
              <IconRobot />
              <span>可用智能体</span>
            </MenuItem>
          </SubMenu> */}
        </Menu>

        <div className="arco-shell-sider-footer">
          <Button
            type="text"
            className="arco-shell-collapse"
            icon={collapsed ? <IconMenuUnfold /> : <IconMenuFold />}
            onClick={toggleSidebar}
          >
            {!collapsed && '收起菜单'}
          </Button>
        </div>
      </Sider>

      <ArcoLayout className="arco-shell-body">
        <Header className="arco-shell-header">
          <div className="arco-shell-header-title">
            <Typography.Text className="arco-shell-kicker">{headerInfo.kicker}</Typography.Text>
            <Typography.Title heading={5} className="arco-shell-title">{headerInfo.title}</Typography.Title>
          </div>
          <Dropdown droplist={userMenu} position="br" trigger="click">
            <Button type="text" className="arco-shell-user">
              <Avatar size={32} className="arco-shell-avatar"><IconUser /></Avatar>
              <span className="arco-shell-user-name">{userDisplayName}</span>
            </Button>
          </Dropdown>
        </Header>
        <Content className="main-content arco-shell-content">
          <div className="main-page-content arco-shell-page">
            {children}
          </div>
        </Content>
      </ArcoLayout>

      {showProfile && <ProfileModal onClose={() => setShowProfile(false)} />}
      {showApiKey && <ApiKeyModal onClose={() => setShowApiKey(false)} />}
    </ArcoLayout>
  )
}

export default Layout
