import {useEffect, useMemo, useState} from 'react'
import Taro from '@tarojs/taro'
import {Button} from '@nutui/nutui-react-taro'
import {View, Text} from '@tarojs/components'
import OrderList from '@/user/order/components/OrderList'
import {getSelectedStoreFromStorage} from '@/utils/storeSelection'
import {listShopStoreUser} from '@/api/shop/shopStoreUser'

export default function StoreOrders() {
  const [boundStoreId, setBoundStoreId] = useState<number | undefined>(undefined)

  const isLoggedIn = useMemo(() => {
    return !!Taro.getStorageSync('access_token') && !!Taro.getStorageSync('UserId')
  }, [])

  const selectedStore = useMemo(() => getSelectedStoreFromStorage(), [])
  const storeId = boundStoreId || selectedStore?.id

  useEffect(() => {
  }, [])

  useEffect(() => {
    // 优先按“店员绑定关系”确定门店归属：门店看到的是自己的订单
    const userId = Number(Taro.getStorageSync('UserId'))
    if (!Number.isFinite(userId) || userId <= 0) return
    listShopStoreUser({userId}).then(list => {
      const first = (list || []).find(i => i?.isDelete !== 1 && i?.storeId)
      if (first?.storeId) setBoundStoreId(first.storeId)
    }).catch(() => {
      // fallback to SelectedStore
    })
  }, [])

  if (!isLoggedIn) {
    return (
      <View className="bg-gray-50 min-h-screen p-4">
        <View className="bg-white rounded-lg p-4">
          <Text className="text-sm text-gray-700">请先登录</Text>
          <View className="mt-3">
            <Button type="primary" size="small" onClick={() => Taro.navigateTo({url: '/passport/login'})}>
              去登录
            </Button>
          </View>
        </View>
      </View>
    )
  }

  return (
    <View className="bg-gray-50 min-h-screen">

      <View className="px-3">
        <View className="bg-white rounded-lg p-3 mb-3">
          <Text className="text-sm text-gray-400">当前门店：</Text>
          <Text className="text-base font-medium">
            {boundStoreId
              ? (selectedStore?.id === boundStoreId ? (selectedStore?.name || `门店ID: ${boundStoreId}`) : `门店ID: ${boundStoreId}`)
              : (selectedStore?.name || '未选择门店')}
          </Text>
        </View>

        {!storeId ? (
          <View className="bg-white rounded-lg p-4">
            <Text className="text-sm text-gray-600">
              请先在首页左上角选择门店，再查看门店订单。
            </Text>
            <View className="mt-3">
              <Button
                type="primary"
                size="small"
                onClick={() => Taro.switchTab({url: '/pages/index/index'})}
              >
                去首页选择门店
              </Button>
            </View>
          </View>
        ) : (
          <OrderList mode="store" baseParams={{storeId}} />
        )}
      </View>
    </View>
  )
}
