import {
  ContainerOutlined,
  LogoutOutlined,
  ShoppingOutlined,
  UserOutlined,
} from '@ant-design/icons'
import { App, Button, Layout, Menu, Typography } from 'antd'
import type { MenuProps } from 'antd'
import { Outlet, useLocation, useNavigate } from 'react-router'

import { logoutWorker } from '@/services/worker'
import { useIsMobile } from '@/utils/use-is-mobile'
import { clearWorkerSession, getWorkerStatus, getWorkerUsername } from '@/utils/worker-auth'

const menuItems: MenuProps['items'] = [
  { key: '/hall', icon: <ShoppingOutlined />, label: '抢单大厅' },
  { key: '/orders', icon: <ContainerOutlined />, label: '我的订单' },
  { key: '/profile', icon: <UserOutlined />, label: '个人中心' },
]

const tabItems = [
  { key: '/hall', icon: ShoppingOutlined, label: '抢单大厅' },
  { key: '/orders', icon: ContainerOutlined, label: '我的订单' },
  { key: '/profile', icon: UserOutlined, label: '个人中心' },
]

export default function WorkerLayout() {
  const navigate = useNavigate()
  const location = useLocation()
  const isMobile = useIsMobile()
  const { message, modal } = App.useApp()
  const username = getWorkerUsername() || '打手'
  const status = getWorkerStatus()
  const currentKey = resolveSelectedKey(location.pathname)

  async function submitLogout() {
    try {
      await logoutWorker()
    } catch {
      // 接单端退出为无状态操作，本地清理优先。
    } finally {
      clearWorkerSession()
      message.success('已退出登录')
      void navigate('/', { replace: true })
    }
  }

  function confirmLogout() {
    modal.confirm({
      title: '确认退出登录',
      content: '退出后需要重新登录才能继续抢单和处理订单。',
      okText: '确认退出',
      cancelText: '取消',
      okButtonProps: { danger: true },
      onOk: submitLogout,
    })
  }

  if (isMobile) {
    return (
      <div className="worker-mobile-shell">
        <header className="worker-mobile-header">
          <div className="worker-mobile-brand">
            <span className="worker-mobile-brand-badge">锤</span>
            <div className="worker-mobile-brand-text">
              <strong>王大锤接单</strong>
            </div>
          </div>
          <div className="worker-mobile-user-area">
            <Button
              type="text"
              size="small"
              icon={<LogoutOutlined />}
              className="worker-mobile-logout-btn"
              onClick={confirmLogout}
              title="退出登录"
            />
          </div>
        </header>

        <main className="worker-mobile-content">
          <Outlet />
        </main>

        <nav className="worker-mobile-tabbar" aria-label="移动端底部导航">
          {tabItems.map((item) => {
            const Icon = item.icon
            const isActive = currentKey === item.key
            return (
              <button
                key={item.key}
                type="button"
                className={`worker-mobile-tab-item ${isActive ? 'active' : ''}`}
                onClick={() => navigate(item.key)}
              >
                <div className="worker-mobile-tab-icon">
                  <Icon />
                </div>
                <span className="worker-mobile-tab-label">{item.label}</span>
              </button>
            )
          })}
        </nav>
      </div>
    )
  }

  return (
    <Layout className="admin-shell worker-shell">
      <Layout.Sider width={220} className="admin-sider" trigger={null}>
        <div className="admin-sider-inner">
          <div className="admin-brand">
            <div className="admin-brand-copy">
              <strong>王大锤</strong>
              <span>接单平台</span>
            </div>
          </div>
          <div className="admin-sidebar-profile">
            <Typography.Text strong>{username}</Typography.Text>
            <Typography.Text type="secondary">{formatWorkerStatus(status)}</Typography.Text>
          </div>
          <Menu
            mode="inline"
            inlineIndent={16}
            selectedKeys={[currentKey]}
            items={menuItems}
            className="admin-menu"
            onClick={({ key }) => navigate(String(key))}
          />
          <div className="admin-sider-footer">
            <Button block icon={<LogoutOutlined />} onClick={submitLogout}>
              退出登录
            </Button>
          </div>
        </div>
      </Layout.Sider>
      <Layout className="admin-main-shell">
        <Layout.Content className="admin-content">
          <Outlet />
        </Layout.Content>
      </Layout>
    </Layout>
  )
}

function resolveSelectedKey(pathname: string) {
  if (pathname.startsWith('/orders')) return '/orders'
  if (pathname.startsWith('/profile')) return '/profile'
  return '/hall'
}

function formatWorkerStatus(status: string) {
  if (status === 'active') return '已审核'
  if (status === 'pending_review') return '待审核'
  if (status === 'rejected') return '审核未通过'
  if (status === 'disabled') return '已停用'
  return '未登录'
}
