import {useEffect, useState} from "react";
import {Image, Button, Cell, CellGroup, Input, Space} from '@nutui/nutui-react-taro'
import {Location, ArrowRight} from '@nutui/icons-react-taro'
import Taro from '@tarojs/taro'
import {ShopGoods} from "@/api/shop/shopGoods/model";
import {getShopGoods} from "@/api/shop/shopGoods";
import {View} from '@tarojs/components';
import {listShopUserAddress} from "@/api/shop/shopUserAddress";
import {ShopUserAddress} from "@/api/shop/shopUserAddress/model";
import './index.scss'
import {useCart} from "@/hooks/useCart";
import Gap from "@/components/Gap";

const OrderConfirm = () => {
  const [goods, setGoods] = useState<ShopGoods | null>(null);
  const [address, setAddress] = useState<ShopUserAddress>()
  const router = Taro.getCurrentInstance().router;
  const goodsId = router?.params?.goodsId;

  const {
    cartItems
  } = useCart();

  const reload = async () => {
    const address = await listShopUserAddress({isDefault: true});
    if (address.length > 0) {
      console.log(address, '111')
      setAddress(address[0])
    }
  }

  useEffect(() => {
    if (goodsId) {
      getShopGoods(Number(goodsId)).then(res => {
        setGoods(res);
      }).catch(error => {
        console.error("Failed to fetch goods detail:", error);
      });
    }
    reload().then()
  }, [goodsId]);

  if (!goods) {
    return <div>加载中...</div>;
  }

  return (
    <div className={'order-confirm-page'}>
      <CellGroup>
        {
          address && (
            <Cell className={'address-bottom-line'} onClick={() => Taro.navigateTo({url: '/user/address/index'})}>
              <Space>
                <Location/>
                <View className={'flex flex-col w-full justify-between items-start'}>
                  <Space className={'flex flex-row w-full font-medium'}>
                    <View className={'flex-wrap text-nowrap whitespace-nowrap'}>送至</View>
                    <View style={{width: '64%'}}
                          className={'line-clamp-1 relative'}>{address.province} {address.city} {address.region} {address.address}
                    </View>
                  </Space>
                  <View className={'pt-1 pb-3 text-gray-500'}>{address.name} {address.phone}</View>
                </View>
              </Space>
            </Cell>
          )
        }
        {!address && (
          <Cell className={''} onClick={() => Taro.navigateTo({url: '/user/address/index'})}>
            <Space>
              <Location/>
              添加收货地址
            </Space>
          </Cell>
        )}
      </CellGroup>

      <CellGroup>
        {cartItems.map((goods, _) => (
          <Cell key={goods.goodsId}>
            <Space>
              <Image src={goods.image} mode={'aspectFill'} style={{
                width: '80px',
                height: '80px',
              }} lazyLoad={false}/>
              <View className={'flex flex-col'}>
                <View className={'font-medium w-full'}>{goods.name}</View>
                <View className={'number text-gray-400 text-sm py-2'}>80g/袋</View>
                <Space className={'flex justify-start items-center'}>
                  <View className={'text-red-500'}>￥{goods.price}</View>
                  <View className={'text-gray-500 text-sm'}>x {goods.quantity}</View>
                </Space>
              </View>
            </Space>
          </Cell>
        ))}
      </CellGroup>

      <CellGroup>
        <Cell title={'商品总价（共3件）'} extra={<View className={'font-medium'}>{'￥' + goods.price}</View>}/>
        <Cell title={'优惠券'} extra={(
          <View className={'flex justify-between items-center'}>
            <View className={'text-red-500 text-sm mr-1'}>-￥10.00</View>
            <ArrowRight className={'text-gray-400'} size={14}/>
          </View>
        )}/>
        {/*<Cell title={'配送费'} extra={'￥' + 10}/>*/}
        <Cell title={'订单备注'} extra={(
          <Input placeholder={'选填，请先和商家协商一致'} style={{ padding: '0'}}/>
        )}/>
      </CellGroup>

      <Gap height={50} />

      <div className={'fixed z-50 bg-white w-full bottom-0 left-0 pt-4 pb-10'} style={{
        boxShadow: '0 -2px 4px 0 rgba(0,0,0,0.10)'
      }}>
        <View className={'btn-bar flex justify-between items-center'}>
          <div className={'flex justify-center items-center mx-4'}>
              <span className={'total-price text-sm text-gray-500'}>实付金额：</span>
              <span className={'text-red-500 text-xl font-bold'}>￥{goods.price}</span>
          </div>
          <div className={'buy-btn mx-4'}>
            <Button type="success" size="large">立即付款</Button>
          </div>
        </View>
      </div>
    </div>
  );
};

export default OrderConfirm;
