import {useEffect, useMemo, useState} from 'react'
import Taro from '@tarojs/taro'
import {NavBar, Button} from '@nutui/nutui-react-taro'
import {ArrowLeft} from '@nutui/icons-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 [statusBarHeight, setStatusBarHeight] = useState<number>(0)

  const [boundStoreId, setBoundStoreId] = useState<number | undefined>(undefined)
  const store = useMemo(() => getSelectedStoreFromStorage(), [])
  const storeId = boundStoreId || store?.id

  useEffect(() => {
    Taro.getSystemInfo({
      success: (res) => setStatusBarHeight(res.statusBarHeight ?? 0)
    })
  }, [])

  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
    })
  }, [])

  return (
    <View className="bg-gray-50 min-h-screen">
      <View style={{height: `${statusBarHeight || 0}px`, backgroundColor: '#ffffff'}}></View>
      <NavBar
        fixed
        style={{marginTop: `${statusBarHeight || 0}px`, backgroundColor: '#ffffff'}}
        left={<ArrowLeft onClick={() => Taro.navigateBack()}/>}
      >
        <span>门店订单</span>
      </NavBar>

      <View className="pt-14 px-3">
        <View className="bg-white rounded-lg p-3 mb-3">
          <Text className="text-sm text-gray-600">当前门店：</Text>
          <Text className="text-base font-medium">{store?.name || (boundStoreId ? `门店ID: ${boundStoreId}` : '未选择门店')}</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}} readOnly />
        )}
      </View>
    </View>
  )
}
