import Toast, { showToast } from '../../components/toast';
import { View, Image, ScrollView } from '@tarojs/components';
import { useEffect, useState } from 'react';
import './index.less';
import { getCollectPoints, collectPoint } from '../../api/site-search';

export default function FavoriteSitesPage() {
  const [list, setList] = useState<any[]>([]);
  const [current, setCurrent] = useState(1);
  const [hasNextPage, setHasNextPage] = useState(false);
  const [loading, setLoading] = useState(false);

  const fetchData = async (page = 1) => {
    if (loading) return;
    setLoading(true);

    try {
      const res = await getCollectPoints({
        pageNum: page,
        pageSize: 20,
      });
      if (res && res.records) {
        setList(prev => page === 1 ? res.records : [...prev, ...res.records]);
        setHasNextPage(res.hasNextPage);
        setCurrent(res.current);
      }
    } catch (e) {
      console.log('获取收藏站点失败', e);
    } finally {
      setLoading(false);
    }
  };

  const handleScrollToLower = () => {
    if (hasNextPage && !loading) {
      fetchData(current + 1);
    }
  };

  const handleDelete = async (item: any) => {
    try {
      const currentItemType = Number(item?.itemType); // 删除项类型
      const payload: any = {
        type: 2, // 2=取消收藏
        itemType: currentItemType, 
      };

      if (currentItemType === 2) {
        payload.stationId = item?.stationId;
      } else {
        payload.pointId = item?.pointId || item?.id;
        payload.latitude = item?.latitude;
        payload.longitude = item?.longitude;
      }

      await collectPoint(payload);
      setList(prev => prev.filter(f => (f.id || f.pointId || f.stationId) !== (item.id || item.pointId || item.stationId)));
      showToast({ title: '已取消收藏', icon: 'none' });
    } catch (e) {
      console.log('取消收藏失败', e);
      showToast({ title: '取消收藏失败', icon: 'none' });
    }
  };

  useEffect(() => {
    fetchData(1);
  }, []);

  return (
    <View className='favorite-sites-page'>
      <ScrollView
        scrollY
        className='favorite-list'
        enhanced
        lowerThreshold={50}
        onScrollToLower={handleScrollToLower}
      >
        <View className='favorite-list-inner'>
          {list.map((item, index) => (
            <View key={item.id || index} className='favorite-item'>
              <View className='favorite-info'>
                <View className='favorite-name'>{item.pointName}</View>
                <View className='favorite-address'>{item.pointAddress}</View>
              </View>
              <Image 
                onClick={(e) => {
                  e.stopPropagation();
                  handleDelete(item);
                }} 
                className='delete-icon' 
                src="https://s.xiaopeng.com/xp-fe/robot-taxi/imgs/delete-icon.png" 
              />
            </View>
          ))}
          {list.length === 0 && !loading && (
            <View className='empty-tip'>暂无收藏站点</View>
          )}
        </View>
      </ScrollView>
      <Toast />
    </View>
  );
}
