import { Button, Text, View } from '@tarojs/components'
import Taro, { useDidShow, useLoad } from '@tarojs/taro'
import { useState } from 'react'
import { backend, type BackendStaffWorkbench, type BackendStaffWorkbenchModule } from '@/api/backend'
import { Field, Page } from '@/components/ui'
import { clearStaffToken, getStaffToken, saveStaffToken } from '@/stores/storage'
import { safeMiniappPath } from '@/utils/nav'

const moduleCopy: Record<string, { subtitle: string; fallbackEntry: string }> = {
  checkin: { subtitle: '活动 / 课程名单、扫码、补录', fallbackEntry: '/pages/checkin/events/index' },
  tasks: { subtitle: '待资料、待接单、处理中、待确认', fallbackEntry: '/pages/staff/tasks/index' },
  consulting: { subtitle: '沟通、方案、报价、完成反馈', fallbackEntry: '/pages/staff/consulting/index' },
  'data-service': { subtitle: '联系、报价、交付文件、完成服务', fallbackEntry: '/pages/staff/data-services/index' },
  orders: { subtitle: '订单流水只读', fallbackEntry: '/pages/staff/orders/index' },
}

function moduleCountText(module: BackendStaffWorkbenchModule) {
  const counts = module.counts || {}
  if (module.key === 'checkin') return `${counts.pending || 0} 待核销`
  if (module.key === 'orders') return `${counts.paid || 0} 已支付`
  if (counts.pool !== undefined || counts.mine !== undefined) return `${counts.pool || 0} 待接单 / ${counts.mine || 0} 我负责`
  return ''
}

export default function StaffWorkbenchPage() {
  const [token, setToken] = useState(getStaffToken())
  const [phone, setPhone] = useState('')
  const [code, setCode] = useState('')
  const [redirect, setRedirect] = useState('')
  const [workbench, setWorkbench] = useState<BackendStaffWorkbench | null>(null)
  const [loading, setLoading] = useState(false)

  async function loadWorkbench(currentToken = token) {
    if (!currentToken) return
    setLoading(true)
    try {
      setWorkbench(await backend.staffWorkbench(currentToken))
    } catch (error) {
      clearStaffToken()
      setToken('')
      setWorkbench(null)
      Taro.showToast({ title: error instanceof Error ? error.message : '工作台加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  async function sendCode() {
    try {
      await backend.sendPhoneCode(phone)
      Taro.showToast({ title: '验证码已发送', icon: 'success' })
    } catch (error) {
      Taro.showToast({ title: error instanceof Error ? error.message : '验证码发送失败', icon: 'none' })
    }
  }

  async function login() {
    try {
      const result = await backend.staffLoginByPhone(phone, code)
      saveStaffToken(result.token)
      setToken(result.token)
      const nextWorkbench = await backend.staffWorkbench(result.token)
      setWorkbench(nextWorkbench)
      Taro.showToast({ title: '登录成功', icon: 'success' })
      if (redirect) Taro.redirectTo({ url: redirect })
    } catch (error) {
      Taro.showToast({ title: error instanceof Error ? error.message : '登录失败', icon: 'none' })
    }
  }

  function logout() {
    clearStaffToken()
    setToken('')
    setWorkbench(null)
  }

  function openModule(module: BackendStaffWorkbenchModule) {
    const entry = safeMiniappPath(module.entry || moduleCopy[module.key]?.fallbackEntry, '')
    if (!entry) return
    Taro.navigateTo({ url: entry })
  }

  useLoad((query) => {
    setRedirect(query.redirect ? safeMiniappPath(decodeURIComponent(String(query.redirect)), '') : '')
  })

  useDidShow(() => {
    const stored = getStaffToken()
    setToken(stored)
    void loadWorkbench(stored)
  })

  if (!token || !workbench) {
    return (
      <Page title="内部工作台" subtle="员工与核销统一入口">
        <View className="staff-login">
          <Field label="员工手机号" value={phone} onInput={setPhone} placeholder="请输入员工手机号" />
          <Field label="验证码" value={code} onInput={setCode} placeholder="请输入验证码" />
          <Button className="primary-btn staff-submit" onClick={sendCode}>获取验证码</Button>
          <Button className="primary-btn staff-submit" onClick={login}>登录内部工作台</Button>
        </View>
      </Page>
    )
  }

  const modules = workbench.modules || []

  return (
    <Page title="内部工作台" subtle={loading ? '正在同步权限' : `${workbench.account.displayName} · ${workbench.account.role}`}>
      <View className="staff-top">
        <Text className="staff-top-title">今日工作</Text>
        <Text className="staff-top-sub">后台角色决定可用模块。</Text>
      </View>

      <View className="staff-module-list">
        {modules.map((module) => {
          const copy = moduleCopy[module.key] || { subtitle: '', fallbackEntry: module.entry }
          const countText = moduleCountText(module)
          return (
            <View key={module.key} className="staff-module-card" onClick={() => openModule(module)}>
              <View>
                <Text className="staff-module-title">{module.title}</Text>
                <Text className="staff-module-sub">{copy.subtitle}</Text>
              </View>
              {!!countText && <View className="staff-module-count"><Text>{countText}</Text></View>}
            </View>
          )
        })}
        {!modules.length && <View className="staff-empty">暂无内部权限，请联系管理员配置角色</View>}
      </View>

      <View className="staff-logout" onClick={logout}>退出内部工作台</View>
    </Page>
  )
}
