import {useEffect, useState} from "react";
import {Image, Button, Cell, CellGroup, Input, TextArea, Space} from '@nutui/nutui-react-taro'
import {Location} 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'

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 reload = async () => {
    const address = await listShopUserAddress({isDefault: true});
    if(address.length > 0){
      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>
              <Space>
                <Location/>
                <View>送至</View>
                <View>{address.fullAddress}</View>
              </Space>
            </Cell>
          )
        }
        {!address && (
          <Cell className={''} onClick={() => Taro.navigateTo({url: '/user/address/index'})}>
            <Space>
              <Location/>
              添加收货地址
            </Space>
          </Cell>
        )}
      </CellGroup>

      <CellGroup>
        <Cell>
          <div className={'flex items-center'}>
            <Image src={goods.image} width="80" height="80"/>
            <div className={'ml-2'}>
              <div className={'text-sm font-bold'}>{goods.name}</div>
              <div className={'text-red-500 text-lg'}>￥{goods.price}</div>
            </div>
          </div>
        </Cell>
      </CellGroup>

      <CellGroup title="收货信息">
        <Cell title="收货人">
          <Input placeholder="请输入收货人姓名"/>
        </Cell>
        <Cell title="手机号">
          <Input placeholder="请输入手机号" type="tel"/>
        </Cell>
        <Cell title="收货地址">
          <TextArea placeholder="请输入详细收货地址"/>
        </Cell>
      </CellGroup>

      <CellGroup title="订单备注">
        <Cell>
          <TextArea placeholder="请输入订单备注"/>
        </Cell>
      </CellGroup>

      <div className={'fixed-bottom'}>
        <div className={'total-price'}>
          合计：<span className={'text-red-500 text-xl font-bold'}>￥{goods.price}</span>
        </div>
        <Button type="primary" size="large" className={'submit-btn'}>提交订单</Button>
      </div>
    </div>
  );
};

export default OrderConfirm;
