import {useEffect, useState} from "react";
import {Image, Tabs, Empty, Sticky} from '@nutui/nutui-react-taro'
import {Share} from '@nutui/icons-react-taro'
import {View, Text} from '@tarojs/components';
import Taro from "@tarojs/taro";
import {ShopGoods} from "@/api/shop/shopGoods/model";
import {pageShopGoods} from "@/api/shop/shopGoods";

const BestSellers = (props: {onStickyChange?: (isSticky: boolean) => void}) => {
  const [tab1value, setTab1value] = useState<string | number>('0')
  const [list, setList] = useState<ShopGoods[]>([])
  const [goods, setGoods] = useState<ShopGoods>()
  const [stickyStatus, setStickyStatus] = useState<boolean>(false)

  const reload = () => {
    pageShopGoods({}).then(res => {
      setList(res?.list || []);
    })
  }

  // 处理分享点击
  const handleShare = (item: ShopGoods) => {
    setGoods(item);

    console.log(goods)

    // 显示分享选项菜单
    Taro.showActionSheet({
      itemList: ['分享给好友'],
      success: (res) => {
        if (res.tapIndex === 0) {
          // 分享给好友 - 触发转发
          Taro.showShareMenu({
            withShareTicket: true,
            success: () => {
              // 提示用户点击右上角分享
              Taro.showToast({
                title: '请点击右上角分享给好友',
                icon: 'none',
                duration: 2000
              });
            }
          });
        }
      },
      fail: (err) => {
        console.log('显示分享菜单失败', err);
      }
    });
  }

  // 处理粘性布局状态变化
  const onStickyChange = (isSticky: boolean) => {
    setStickyStatus(isSticky)
    // 通知父组件粘性状态变化
    props.onStickyChange?.(isSticky)
    console.log('Tabs 粘性状态:', isSticky ? '已固定' : '取消固定')
  }

  // 获取小程序系统信息
  const getSystemInfo = () => {
    const systemInfo = Taro.getSystemInfoSync()
    // 状态栏高度 + 导航栏高度 (一般为44px)
    return (systemInfo.statusBarHeight || 0) + 44
  }

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

  return (
    <>
      <View className={'py-3'} style={{paddingTop: '0'}}>
        {/* Tabs粘性布局组件 */}
        <Sticky
          threshold={getSystemInfo()}
          onChange={onStickyChange}
          style={{
            zIndex: 999,
            backgroundColor: stickyStatus ? '#ffffff' : 'transparent',
            boxShadow: stickyStatus ? '0 2px 8px rgba(0,0,0,0.1)' : 'none',
            transition: 'all 0.3s ease',
            marginTop: stickyStatus ? '0' : '-12px'
          }}
        >
          <Tabs
            value={tab1value}
            className={'w-full'}
            onChange={(value) => {
              setTab1value(value)
            }}
            style={{
              backgroundColor: 'transparent',
              paddingTop: stickyStatus ? '0' : '8px',
              paddingBottom: stickyStatus ? '8px' : '0',
            }}
            activeType="smile"
          >
            <Tabs.TabPane title="今日主推">
            </Tabs.TabPane>
            <Tabs.TabPane title="即将到期">
            </Tabs.TabPane>
            <Tabs.TabPane title="活动预告">
            </Tabs.TabPane>
          </Tabs>
        </Sticky>

        <View className={'flex flex-col justify-between items-center rounded-lg px-2 mt-2'}>
          {/* 今日主推 */}
          {tab1value == '0' && list?.map((item, index) => {
            return (
              <View key={index} className={'flex flex-col rounded-lg bg-white shadow-sm w-full mb-5'}>
                <Image src={item.image} mode={'aspectFit'} lazyLoad={false}
                       radius="10px 10px 0 0" height="180"
                       onClick={() => Taro.navigateTo({url: '/shop/goodsDetail/index?id=' + item.goodsId})}/>
                <View className={'flex flex-col p-2 rounded-lg'}>
                  <View>
                    <View className={'car-no text-sm'}>{item.name}</View>
                    <View className={'flex justify-between text-xs py-1'}>
                      <Text className={'text-orange-500'}>{item.comments}</Text>
                      <Text className={'text-gray-400'}>已售 {item.sales}</Text>
                    </View>
                    <View className={'flex justify-between items-center py-2'}>
                      <View className={'flex text-red-500 text-xl items-baseline'}>
                        <Text className={'text-xs'}>￥</Text>
                        <Text className={'font-bold text-2xl'}>{item.price}</Text>
                        <Text className={'text-xs px-1'}>会员价</Text>
                        <Text className={'text-xs text-gray-400 line-through'}>￥{item.salePrice}</Text>
                      </View>
                      <View className={'buy-btn'}>
                        <View className={'cart-icon items-center hidden'}>
                          <View
                            className={'flex flex-col justify-center items-center text-white px-3 gap-1 text-nowrap whitespace-nowrap cursor-pointer'}
                            onClick={() => handleShare(item)}
                          >
                            <Share size={20}/>
                          </View>
                        </View>
                        <Text className={'text-white pl-4 pr-5'}
                              onClick={() => Taro.navigateTo({url: '/shop/goodsDetail/index?id=' + item.goodsId})}>购买
                        </Text>
                      </View>
                    </View>
                  </View>
                </View>
              </View>
            )
          })}

          {/* 即将到期 */}
          {tab1value == '1' && (
            <Empty
              size={'small'}
              description="暂无即将到期的商品"
              style={{
                background: 'transparent',
              }}
            />
          )}

          {/* 活动预告 */}
          {tab1value == '2' && (
            <Empty
              size={'small'}
              description="暂无活动预告"
              style={{
                background: 'transparent',
              }}
            />
          )}
        </View>
      </View>
    </>
  )
}
export default BestSellers
