import { View, Text, ScrollView } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { useState, useEffect } from 'react';
import { getMyExchangeList, cancelExchange } from '@/api/shop/shopMemberBenefit';
import EmptyState from '@/components/common/EmptyState';
import './index.scss';

definePageConfig({
  navigationBarTitleText: '兑换记录',
});

const TABS = [
  { label: '全部', value: -1 },
  { label: '待处理', value: 0 },
  { label: '已发货', value: 1 },
  { label: '已完成', value: 2 },
];

const STATUS_TEXT: Record<number, string> = {
  0: '待处理',
  1: '已发货',
  2: '已完成',
  3: '已取消',
};

const STATUS_CLASS: Record<number, string> = {
  0: 'pending',
  1: 'shipped',
  2: 'done',
  3: 'cancelled',
};

export default function BenefitExchangeListPage() {
  const [activeTab, setActiveTab] = useState(-1);
  const [list, setList] = useState<any[]>([]);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    loadList(true);
  }, [activeTab]);

  const loadList = async (isRefresh = false) => {
    if (loading) return;
    setLoading(true);
    const currentPage = isRefresh ? 1 : page;
    try {
      const params: any = { page: currentPage, limit: 20 };
      if (activeTab >= 0) params.status = activeTab;
      const res = await getMyExchangeList(params);
      if (res.code === 200) {
        const newList = res.data.list || [];
        setList(isRefresh ? newList : [...list, ...newList]);
        setPage(currentPage + 1);
        setHasMore(newList.length >= 20);
      }
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = (item: any) => {
    Taro.showModal({
      title: '取消兑换',
      content: '确认取消该兑换申请吗？',
      success: async (res) => {
        if (!res.confirm) return;
        const res2 = await cancelExchange(item.id);
        if (res2.code === 200) {
          Taro.showToast({ title: '已取消', icon: 'success' });
          loadList(true);
        }
      },
    });
  };

  const handleTrack = (item: any) => {
    if (item.expressNo) {
      Taro.setClipboardData({ data: item.expressNo });
      Taro.showToast({ title: '快递单号已复制', icon: 'none' });
    }
  };

  return (
    <View className="exchange-list-page">
      {/* 标签栏 */}
      <View className="tab-bar">
        {TABS.map((tab) => (
          <View
            key={tab.value}
            className={`tab-item ${activeTab === tab.value ? 'active' : ''}`}
            onClick={() => setActiveTab(tab.value)}
          >
            {tab.label}
          </View>
        ))}
      </View>

      <ScrollView
        className="list-scroll"
        scrollY
        onScrollToLower={() => hasMore && loadList()}
      >
        {!loading && list.length === 0 && (
          <EmptyState description="暂无兑换记录" />
        )}

        {list.map((item) => (
          <View key={item.id} className="exchange-card">
            <View className="card-header">
              <Text className="pkg-name">{item.packageName}</Text>
              <Text className={`status-tag ${STATUS_CLASS[item.status]}`}>
                {STATUS_TEXT[item.status]}
              </Text>
            </View>

            <View className="cost-row">
              {item.pointsCost > 0 && (
                <Text className="cost-text">消耗 {item.pointsCost} 积分</Text>
              )}
              {item.balanceCost > 0 && (
                <Text className="cost-text">消耗 ¥{item.balanceCost}</Text>
              )}
            </View>

            {item.addressSnapshot && (
              <View className="address-row">
                <Text className="addr-label">收货地址：</Text>
                <Text className="addr-val">
                  {(() => {
                    try {
                      const addr = JSON.parse(item.addressSnapshot);
                      return `${addr.name} ${addr.phone}  ${addr.province}${addr.city}${addr.district}${addr.detail}`;
                    } catch {
                      return item.addressSnapshot;
                    }
                  })()}
                </Text>
              </View>
            )}

            {item.status === 1 && item.expressNo && (
              <View className="express-row" onClick={() => handleTrack(item)}>
                <Text className="express-label">快递：</Text>
                <Text className="express-val">
                  {item.expressCompany} {item.expressNo}
                </Text>
                <Text className="copy-btn">复制</Text>
              </View>
            )}

            <View className="card-footer">
              <Text className="create-time">{item.createTime}</Text>
              {item.status === 0 && (
                <View className="cancel-btn" onClick={() => handleCancel(item)}>
                  取消兑换
                </View>
              )}
            </View>
          </View>
        ))}

        {loading && (
          <View className="loading-tip">加载中...</View>
        )}
      </ScrollView>
    </View>
  );
}
