import { View, Text, ScrollView } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { useState, useEffect } from 'react';
import { getCommissionStats, getMyCommissionList } from '@/api/shop/shopCommissionRecord';
import EmptyState from '@/components/common/EmptyState';
import { Loading } from '@nutui/nutui-react-taro';

import './index.scss';

definePageConfig({
  navigationBarTitleText: '我的佣金',
});

export default function CommissionPage() {
  const [stats, setStats] = useState<any>({});
  const [list, setList] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [activeTab, setActiveTab] = useState(0); // 0待结算/1已结算

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

  const loadStats = async () => {
    try {
      const res = await getCommissionStats();
      if (res.code === 200) {
        setStats(res.data);
      }
    } catch (error) {
      console.error('加载统计失败', error);
    }
  };

  const loadList = async (isRefresh = false) => {
    if (loading) return;
    setLoading(true);

    try {
      const currentPage = isRefresh ? 1 : page;
      const res = await getMyCommissionList({
        status: activeTab,
        page: currentPage,
        limit: 20
      });

      if (res.code === 200) {
        const newList = res.data.list || [];
        setList(isRefresh ? newList : [...list, ...newList]);
        setPage(currentPage + 1);
        setHasMore(newList.length >= 20);
      }
    } catch (error) {
      console.error('加载列表失败', error);
    } finally {
      setLoading(false);
    }
  };

  const handleTabChange = (tab: number) => {
    setActiveTab(tab);
    setPage(1);
    setHasMore(true);
    loadList(true);
  };

  const handleWithdraw = () => {
    Taro.navigateTo({ url: '/pages/user/withdraw/index' });
  };

  const getStatusText = (status: number) => {
    const map: Record<number, string> = {
      0: '待结算',
      1: '已结算',
      2: '已失效'
    };
    return map[status] || '未知';
  };

  return (
    <View className="commission-page">
      {/* 统计区域 */}
      <View className="stats-card">
        <View className="stats-row">
          <View className="stats-item">
            <Text className="stats-label">待结算佣金(元)</Text>
            <Text className="stats-value pending">{stats.pendingTotal || '0.00'}</Text>
          </View>
          <View className="stats-item">
            <Text className="stats-label">已结算佣金(元)</Text>
            <Text className="stats-value settled">{stats.settledTotal || '0.00'}</Text>
          </View>
        </View>
        <View className="withdraw-btn" onClick={handleWithdraw}>
          去提现
        </View>
      </View>

      {/* 标签页 */}
      <View className="tab-bar">
        <View
          className={`tab-item ${activeTab === 0 ? 'active' : ''}`}
          onClick={() => handleTabChange(0)}
        >
          待结算({stats.pendingCount || 0})
        </View>
        <View
          className={`tab-item ${activeTab === 1 ? 'active' : ''}`}
          onClick={() => handleTabChange(1)}
        >
          已结算({stats.settledCount || 0})
        </View>
      </View>

      {/* 列表 */}
      <ScrollView
        className="commission-list"
        scrollY
        onScrollToLower={() => hasMore && loadList()}
      >
        {list.length === 0 && !loading ? (
          <EmptyState description="暂无佣金记录" />
        ) : (
          list.map((item) => (
            <View key={item.id} className="commission-item">
              <View className="commission-info">
                <Text className="commission-order">订单号: {item.orderNo}</Text>
                <Text className="commission-amount">+{item.commissionAmount}</Text>
              </View>
              <View className="commission-meta">
                <Text className="meta-text">订单金额: ¥{item.orderAmount}</Text>
                <Text className={`status-tag status-${item.status}`}>
                  {getStatusText(item.status)}
                </Text>
              </View>
              {item.settleTime && (
                <Text className="settle-time">
                  结算时间: {item.settleTime}
                </Text>
              )}
            </View>
          ))
        )}
        {loading && <Loading>加载中...</Loading>}
      </ScrollView>
    </View>
  );
}
