import { Image, ScrollView, Text, View } from '@tarojs/components'
import Taro, { useDidShow, useTabItemTap } from '@tarojs/taro'
import { useMemo, useState } from 'react'
import {
  backend,
  mapUser,
  type BackendAccountMembership,
  type BackendConsultingRequest,
  type BackendCourseRegistration,
  type BackendDataServiceRequest,
  type BackendEventRegistration,
  type BackendExpertApplication,
  type BackendExpertBooking,
  type BackendExpertProfile,
  type BackendNotification,
  type BackendOrder,
} from '@/api/backend'
import { BottomDrawer, Page } from '@/components/ui'
import { ensureLoggedIn, getToken, saveUser } from '@/stores/storage'
import type { UserProfile } from '@/types'
import { tapMedium } from '@/utils/feedback'
import { createQrMatrix } from '@/utils/qr-code'

type AccountTodo = {
  id: string
  title: string
  meta: string
  tone?: 'brand' | 'orange' | 'muted'
  url: string
}

const crownIconBrand = `data:image/svg+xml;utf8,${encodeURIComponent(`
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#123E7C" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
  <path d="M11.562 3.266a.5.5 0 0 1 .876 0L15.39 8.87a1 1 0 0 0 1.516.294L21.183 5.5a.5.5 0 0 1 .798.519l-2.834 10.246a1 1 0 0 1-.956.734H5.81a1 1 0 0 1-.957-.734L2.02 6.02a.5.5 0 0 1 .798-.519l4.276 3.664a1 1 0 0 0 1.516-.294z"/>
  <path d="M5 21h14"/>
</svg>
`)}`

const crownIconWhite = `data:image/svg+xml;utf8,${encodeURIComponent(`
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#FFFFFF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
  <path d="M11.562 3.266a.5.5 0 0 1 .876 0L15.39 8.87a1 1 0 0 0 1.516.294L21.183 5.5a.5.5 0 0 1 .798.519l-2.834 10.246a1 1 0 0 1-.956.734H5.81a1 1 0 0 1-.957-.734L2.02 6.02a.5.5 0 0 1 .798-.519l4.276 3.664a1 1 0 0 0 1.516-.294z"/>
  <path d="M5 21h14"/>
</svg>
`)}`

const passportQrIcon = `data:image/svg+xml;utf8,${encodeURIComponent(`
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#123E7C" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
  <rect width="5" height="5" x="3" y="3" rx="1"/>
  <rect width="5" height="5" x="16" y="3" rx="1"/>
  <rect width="5" height="5" x="3" y="16" rx="1"/>
  <path d="M21 16h-3a2 2 0 0 0-2 2v3"/>
  <path d="M21 21v.01"/>
  <path d="M12 7v3a2 2 0 0 1-2 2H7"/>
  <path d="M3 12h.01"/>
  <path d="M12 3h.01"/>
  <path d="M12 16v.01"/>
  <path d="M16 12h1"/>
  <path d="M21 12v.01"/>
  <path d="M12 21v-1"/>
</svg>
`)}`

function lineIcon(path: string) {
  return `data:image/svg+xml;utf8,${encodeURIComponent(`
<svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#263241" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
  ${path}
</svg>
`)}`
}

const accountLineIcons = {
  consulting: lineIcon('<path d="M4 5.5h16v9.5H9l-5 4V5.5Z"/><path d="M8 9h8"/><path d="M8 12h5"/>'),
  agent: lineIcon('<rect x="5" y="6" width="14" height="12" rx="4"/><path d="M9 6V3"/><path d="M15 6V3"/><path d="M9.5 12h.01"/><path d="M14.5 12h.01"/><path d="M10 15h4"/>'),
  invoice: lineIcon('<path d="M7 3h10a2 2 0 0 1 2 2v16l-3-2-3 2-3-2-3 2-3-2V5a2 2 0 0 1 2-2Z"/><path d="M8 8h8"/><path d="M8 12h6"/><path d="M8 16h4"/>'),
  passport: lineIcon('<rect x="4" y="4" width="16" height="16" rx="3"/><path d="M8 9h3"/><path d="M8 13h8"/><path d="M8 17h6"/><path d="M15.5 8.5h.01"/>'),
  settings: lineIcon('<path d="M12 15.5a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7Z"/><path d="M19.4 15a1.8 1.8 0 0 0 .36 2l.05.05a2.1 2.1 0 0 1-2.97 2.97l-.05-.05a1.8 1.8 0 0 0-2-.36 1.8 1.8 0 0 0-1.09 1.65V21a2.1 2.1 0 0 1-4.2 0v-.08a1.8 1.8 0 0 0-1.09-1.65 1.8 1.8 0 0 0-2 .36l-.05.05a2.1 2.1 0 0 1-2.97-2.97l.05-.05a1.8 1.8 0 0 0 .36-2 1.8 1.8 0 0 0-1.65-1.09H2a2.1 2.1 0 0 1 0-4.2h.08a1.8 1.8 0 0 0 1.65-1.09 1.8 1.8 0 0 0-.36-2l-.05-.05a2.1 2.1 0 0 1 2.97-2.97l.05.05a1.8 1.8 0 0 0 2 .36h.02A1.8 1.8 0 0 0 9.45 2.1V2a2.1 2.1 0 0 1 4.2 0v.08a1.8 1.8 0 0 0 1.09 1.65 1.8 1.8 0 0 0 2-.36l.05-.05a2.1 2.1 0 0 1 2.97 2.97l-.05.05a1.8 1.8 0 0 0-.36 2v.02a1.8 1.8 0 0 0 1.65 1.09H21a2.1 2.1 0 0 1 0 4.2h-.08A1.8 1.8 0 0 0 19.4 15Z"/>'),
  notice: lineIcon('<path d="M18 8a6 6 0 0 0-12 0c0 7-3 7-3 9h18c0-2-3-2-3-9Z"/><path d="M10 21h4"/>'),
  security: lineIcon('<path d="M12 3 19 6v5c0 4.5-2.8 8.1-7 10-4.2-1.9-7-5.5-7-10V6l7-3Z"/><path d="m9.5 12 1.8 1.8L15.2 10"/>')
}

function levelName(level: number) {
  if (level === 2) return '高级会员'
  if (level === 1) return '初级会员'
  return '注册用户'
}

function membershipStatus(membership?: BackendAccountMembership | null) {
  if (!membership) return '同步中'
  if (membership.status === 'expired') return '已到期'
  if (membership.status === 'expiring') return '即将到期'
  if (membership.status === 'active') return membership.expiresAt ? `有效至 ${new Date(membership.expiresAt).toLocaleDateString('zh-CN')}` : '有效'
  return '未开通'
}

function orderStatusLabel(status: BackendOrder['status']) {
  if (status === 'pending_payment') return '待支付'
  if (status === 'closed') return '已关闭'
  return '已支付'
}

function dataStatusLabel(status: BackendDataServiceRequest['status']) {
  if (status === 'quoted') return '报价待确认'
  if (status === 'pending_payment') return '待支付'
  if (status === 'in_service') return '服务中'
  if (status === 'completed') return '已完成'
  if (status === 'cancelled') return '已取消'
  if (status === 'contacting') return '沟通中'
  return '等待联系'
}

function consultingStatusLabel(status: BackendConsultingRequest['status']) {
  if (status === 'proposal_ready') return '报价待确认'
  if (status === 'pending_payment') return '待支付'
  if (status === 'in_service') return '服务中'
  if (status === 'completed') return '已完成'
  if (status === 'cancelled') return '已取消'
  if (status === 'communicating') return '沟通中'
  if (status === 'planning') return '方案中'
  if (status === 'assigned') return '已接单'
  return '待受理'
}

function expertStatusLabel(status: BackendExpertBooking['status']) {
  if (status === 'pending_payment') return '待支付'
  if (status === 'pending_expert') return '待专家确认'
  if (status === 'confirmed') return '预约中'
  if (status === 'pending_user_confirm') return '待确认完成'
  if (status === 'disputed') return '争议处理中'
  if (status === 'completed') return '已完成'
  if (status === 'rejected') return '已拒绝'
  return '已取消'
}

function activityStatusLabel(status: BackendEventRegistration['status'] | BackendCourseRegistration['status']) {
  if (status === 'pending_payment') return '待支付'
  if (status === 'waitlisted') return '候补中'
  if (status === 'checked_in') return '已核销'
  if (status === 'registered') return '待核销'
  if (status === 'cancel_requested') return '取消处理中'
  if (status === 'cancelled') return '已取消'
  if (status === 'no_show') return '未到场'
  return '已关闭'
}

function shortDate(value?: string | null) {
  if (!value) return ''
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return ''
  return `${date.getMonth() + 1}月${date.getDate()}日`
}

function DefaultAvatar({ level }: { level: number }) {
  return (
    <View className="default-avatar-wrap">
      <View className={`default-avatar level-${level}`}>
        <View className="default-avatar-head" />
        <View className="default-avatar-eye left" />
        <View className="default-avatar-eye right" />
        <View className="default-avatar-mouth" />
        <View className="default-avatar-body" />
      </View>
      {level > 0 && (
        <View className={`default-avatar-badge level-${level}`}>
          <Image className="default-avatar-crown" src={level === 2 ? crownIconWhite : crownIconBrand} mode="aspectFit" />
        </View>
      )}
    </View>
  )
}

function PassportQr({ passportNo }: { passportNo?: string }) {
  const value = passportNo ? `https://bigdata.dtacloud.cn/p/${encodeURIComponent(passportNo)}` : 'NO-PASSPORT'
  const matrix = useMemo(() => createQrMatrix(value.length <= 78 ? value : passportNo || 'NO-PASSPORT'), [passportNo, value])
  const cellSize = `${100 / matrix.length}%`

  return (
    <View className="passport-qr-grid">
      {matrix.flatMap((row, y) => row.map((dark, x) => (
        <View key={`${x}-${y}`} className={dark ? 'passport-qr-cell dark' : 'passport-qr-cell'} style={{ width: cellSize, height: cellSize }} />
      )))}
    </View>
  )
}

function expertEntry(application: BackendExpertApplication | null, profile: BackendExpertProfile | null) {
  if (profile) return { label: '专家工作台', url: '/pages/account/expert-home/index', sub: '排期、预约处理和提现' }
  if (application?.status === 'pending') return { label: '专家申请审核中', url: '/pages/account/expert-home/index', sub: '查看审核状态与提交资料' }
  if (application?.status === 'rejected') return { label: '重新提交专家申请', url: '/pages/experts/join/index', sub: application.rejectReason || '补充资料后再次提交' }
  return { label: '申请成为专家', url: '/pages/experts/join/index', sub: '提交专家方向与资料' }
}

export default function AccountPage() {
  const [user, setUser] = useState<UserProfile | null>(null)
  const [membership, setMembership] = useState<BackendAccountMembership | null>(null)
  const [orders, setOrders] = useState<BackendOrder[]>([])
  const [dataRequests, setDataRequests] = useState<BackendDataServiceRequest[]>([])
  const [consultingRequests, setConsultingRequests] = useState<BackendConsultingRequest[]>([])
  const [expertBookings, setExpertBookings] = useState<BackendExpertBooking[]>([])
  const [courseRegistrations, setCourseRegistrations] = useState<BackendCourseRegistration[]>([])
  const [eventRegistrations, setEventRegistrations] = useState<BackendEventRegistration[]>([])
  const [application, setApplication] = useState<BackendExpertApplication | null>(null)
  const [profile, setProfile] = useState<BackendExpertProfile | null>(null)
  const [notifications, setNotifications] = useState<BackendNotification[]>([])
  const [loading, setLoading] = useState(false)
  const [showPassport, setShowPassport] = useState(false)
  const [showProfile, setShowProfile] = useState(false)
  useTabItemTap(tapMedium)

  async function loadAccount() {
    const current = ensureLoggedIn('/pages/account/index')
    const token = getToken()
    setUser(current)
    if (!current || !token) return
    setLoading(true)
    try {
      const remoteUser = await backend.me(token)
      const mappedUser = mapUser(remoteUser)
      saveUser(mappedUser)
      setUser(mappedUser)
    } catch {
      // Keep local profile when account sync is temporarily unavailable.
    }
    const [
      membershipResult,
      orderResult,
      dataResult,
      consultingResult,
      expertBookingResult,
      courseResult,
      eventResult,
      applicationResult,
      profileResult,
      notificationResult,
    ] = await Promise.allSettled([
      backend.accountMembership(token),
      backend.accountOrders(token),
      backend.accountDataServiceRequests(token),
      backend.accountConsultingRequests(token),
      backend.accountExpertBookings(token),
      backend.accountCourseRegistrations(token),
      backend.accountEventRegistrations(token),
      backend.accountExpertApplication(token),
      backend.accountExpertProfile(token),
      backend.accountNotifications(token, true),
    ])
    if (membershipResult.status === 'fulfilled') setMembership(membershipResult.value)
    if (orderResult.status === 'fulfilled') setOrders(orderResult.value.items)
    if (dataResult.status === 'fulfilled') setDataRequests(dataResult.value.items)
    if (consultingResult.status === 'fulfilled') setConsultingRequests(consultingResult.value.items)
    if (expertBookingResult.status === 'fulfilled') setExpertBookings(expertBookingResult.value.items.filter((item) => item.userId === current.id))
    if (courseResult.status === 'fulfilled') setCourseRegistrations(courseResult.value.items)
    if (eventResult.status === 'fulfilled') setEventRegistrations(eventResult.value.items)
    if (applicationResult.status === 'fulfilled') setApplication(applicationResult.value)
    if (profileResult.status === 'fulfilled') setProfile(profileResult.value)
    if (notificationResult.status === 'fulfilled') setNotifications(notificationResult.value.items)
    setLoading(false)
  }

  useDidShow(() => {
    void loadAccount()
  })

  if (!user) return <Page />

  const activityCount = courseRegistrations.length + eventRegistrations.length
  const agentCount = orders.reduce((sum, order) => sum + order.items.filter((item) => item.productType === 'agent').length, 0)
  const displayName = user.name && user.name !== user.phone ? user.name : '研究院用户'
  const levelLabel = levelName(user.membershipLevel)
  const membershipText = membershipStatus(membership)
  const serviceStats = [
    { label: '订单', value: orders.length, url: '/pages/account/orders/index' },
    { label: '课程活动', value: activityCount, url: '/pages/account/courses/index' },
    { label: '数据服务', value: dataRequests.length, url: '/pages/account/reports/index' },
    { label: '专家预约', value: expertBookings.length, url: '/pages/account/expert-bookings/index' },
  ]
  const menuItems = [
    { label: '我的咨询', sub: `${consultingRequests.length} 项进度`, icon: accountLineIcons.consulting, url: '/pages/account/consulting/index' },
    { label: '我的智能体', sub: `${agentCount} 项服务`, icon: accountLineIcons.agent, url: '/pages/account/agents/index' },
    { label: '我的发票', sub: '申请、处理与下载', icon: accountLineIcons.invoice, url: '/pages/account/invoices/index' },
    { label: '会员通行证', sub: user.passportNo || '用于身份与会员核验', icon: accountLineIcons.passport, action: () => setShowPassport(true) },
    { label: '内部工作台', sub: '员工、核销、交付', icon: accountLineIcons.security, url: '/pages/staff/index/index' },
    { label: '消息通知', sub: notifications.length ? `${notifications.length} 条未读` : '暂无未读消息', icon: accountLineIcons.notice, url: '/pages/account/notifications/index' },
    { label: '账号设置', sub: '更改信息、协议规则、AI 助手与账号操作', icon: accountLineIcons.settings, url: '/pages/account/settings/index', smallIcon: true },
  ]
  const profileRows = [
    ['姓名', displayName],
    ['账号状态', loading ? '同步中' : '已登录'],
    ['会员等级', levelLabel],
    ['会员状态', membershipText],
    ['手机号', user.phone || '未绑定'],
    ['服务联系人', user.contactPhone || user.phone || '未填写'],
    ['所在单位', user.organization || '未填写'],
    ['职务', user.title || '未填写'],
    ['邮箱', user.email || '未填写'],
    ['所在城市', user.city || '未填写'],
    ['通行证编号', user.passportNo || '待生成'],
    ['发票抬头', user.invoiceTitle || '未填写'],
    ['发票邮箱', user.invoiceEmail || user.email || '未填写'],
  ]

  return (
    <Page>
      <View className="account-top-card">
        <View className="account-profile-row" onClick={() => setShowProfile(true)}>
          <View className="account-avatar-tap" onClick={(event) => { event.stopPropagation(); setShowPassport(true) }}>
            <DefaultAvatar level={user.membershipLevel} />
          </View>
          <View className="account-profile-main">
            <View className="account-name-line">
              <Text className="account-name">{displayName}</Text>
              <Text className="account-level-badge">{levelLabel}</Text>
            </View>
            <Text className="account-meta">{user.organization || '大连市大数据研究院用户'}</Text>
          </View>
          <Text className="account-profile-chevron">›</Text>
        </View>

        {notifications.length > 0 && (
          <View className="account-notice-bar" onClick={() => Taro.navigateTo({ url: '/pages/account/notifications/index' })}>
            <Text className="account-notice-title">{notifications[0].title}</Text>
            <Text className="account-notice-meta">{notifications.length} 条未读</Text>
          </View>
        )}

        <View className="account-member-strip" onClick={() => Taro.navigateTo({ url: '/pages/account/membership/index' })}>
          <View className="account-member-left">
            <Image className="account-member-crown" src={crownIconBrand} mode="aspectFit" />
            <Text className="account-member-title">会员权益</Text>
          </View>
          <View className="account-member-right">
            <Text className="account-member-expiry">{membershipText}</Text>
            <Text className="arrow">›</Text>
          </View>
        </View>

        <View className="account-stats">
          {serviceStats.map((item, index) => (
            <View key={item.label} className={`account-stat-cell ${index > 0 ? 'with-divider' : ''}`} onClick={() => Taro.navigateTo({ url: item.url })}>
              <Text className="stat-value">{item.value}</Text>
              <Text className="stat-label">{item.label}</Text>
            </View>
          ))}
        </View>
      </View>

      <View className="account-simple-menu">
        {menuItems.map((item) => (
          <View
            key={item.label}
            className="account-simple-row"
            onClick={() => item.action ? item.action() : item.url && Taro.navigateTo({ url: item.url })}
          >
            <View className={item.smallIcon ? 'account-simple-icon small' : 'account-simple-icon'}><Image className="account-simple-icon-image" src={item.icon} mode="aspectFit" /></View>
            <View className="account-simple-main">
              <Text className="account-menu-title">{item.label}</Text>
              <Text className="account-menu-sub">{item.sub}</Text>
            </View>
            <Text className="arrow">›</Text>
          </View>
        ))}
      </View>

      {showProfile && (
        <BottomDrawer title="账号信息" onClose={() => setShowProfile(false)} className="account-info-drawer">
          <ScrollView scrollY className="account-info-scroll">
            {profileRows.map(([label, value]) => (
              <View key={label} className="account-info-row">
                <Text className="account-info-label">{label}</Text>
                <Text className="account-info-value">{value}</Text>
              </View>
            ))}
          </ScrollView>
        </BottomDrawer>
      )}

      {showPassport && (
        <BottomDrawer
          title="会员通行证"
          onClose={() => setShowPassport(false)}
          className="passport-drawer"
        >
          <View className="passport-drawer-body">
            <View className="passport-qr-card">
              <PassportQr passportNo={user.passportNo} />
            </View>
            <Text className="passport-drawer-no">{user.passportNo || '通行证待生成'}</Text>
            <Text className="passport-drawer-copy">用于核验用户身份、会员等级和服务记录。</Text>
          </View>
        </BottomDrawer>
      )}

    </Page>
  )
}
