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

type Props = {
  // 站点数据
  item: any;
  // 渲染 key
  itemKey: string | number;
  // 图标资源
  iconSrc: string;
  // 星标资源
  starSrc: string;
  // 未星标资源
  noStarSrc: string;
  // 是否显示距离
  showDistance?: boolean;
  // 选择站点回调
  onSelect: (item: any) => void;
  // 高亮文本渲染器
  renderHighlightedText: (text: string, className: string) => any;
  // 是否展示场站子站点信息
  showStationChildren?: boolean;
};

// 站点列表单项
export default function SiteListItem({
  item,
  itemKey,
  iconSrc,
  starSrc,
  noStarSrc,
  showDistance = true,
  onSelect,
  renderHighlightedText,
  showStationChildren = false
}: Props) {
  const MAX_COLLECT_COUNT = 50;
  const MAX_VISIBLE_STATION_CHILDREN = 4; // 场站模式默认最多展示子站点数量
  const [isCollected, setIsCollected] = useState(!!item.isCollected);
  const [expandStationChildren, setExpandStationChildren] = useState(false); // 是否展开全部场站子站点

  useEffect(() => {
    setIsCollected(item.isCollect === 1);
  }, [item.isCollect]);

  useEffect(() => {
    setExpandStationChildren(false);
  }, [item?.id, item?.pointId, item?.stationId]);

  const isStationItem = Number(item?.itemType) === 2; // 当前条目是否场站
  const stationChildren = Array.isArray(item?.children) ? item.children : []; // 场站子站点列表
  const shouldShowStationChildren = showStationChildren && isStationItem && stationChildren.length > 0; // 是否渲染场站子站点盒子
  const visibleStationChildren = expandStationChildren
    ? stationChildren
    : stationChildren.slice(0, MAX_VISIBLE_STATION_CHILDREN);

  /**
   * 获取子站点展示名称。
   */
  const getStationChildName = (child: any) => {
    return child?.name || child?.pointName || '--';
  };

  /**
   * 组装场站子站点选择结果，补齐 stationId。
   */
  const getSelectedStationChild = (child: any) => {
    return {
      ...child,
      stationId: item?.stationId || child?.stationId
    };
  };

  /**
   * 点击主列表项：场站默认选择首个子站点，普通站点按原逻辑选择。
   */
  const handleSelectMainItem = () => {
    if (!isStationItem) {
      onSelect(item);
      return;
    }
    const firstSite = stationChildren[0];
    if (!firstSite) {
      showToast({
        title: '此场站无有效站点',
        icon: 'none'
      });
      return;
    }
    onSelect(getSelectedStationChild(firstSite));
  };

  /**
   * 点击场站子站点：按子站点直接选择。
   */
  const handleSelectStationChild = (child: any) => {
    onSelect(getSelectedStationChild(child));
  };

  const checkCollectLimit = async () => {
    // 只取总数即可
    const res = await getCollectPoints({
      pageNum: 1,
      pageSize: 999,
    });

    if (Number(res?.total) >= MAX_COLLECT_COUNT) {
      showToast({
        title: `最多收藏${MAX_COLLECT_COUNT}个站点`,
        icon: 'none'
      });
      return false;
    }

    return true;
  };

  const handleCollect = async (e: any) => {
    e.stopPropagation();
    try {
      const type = isCollected ? 2 : 1; // 1=收藏 2=取消收藏

      if (type === 1) {
        const canCollect = await checkCollectLimit();
        if (!canCollect) {
          return;
        }
      }

      const currentItemType = Number(item?.itemType); // 当前条目类型（1=站点，2=场站）
      const payload: any = {
        itemType: currentItemType === 2 ? 2 : 1, // 收藏类型参数
        type: type
      };

      // 场站收藏：不传经纬度，仅传 stationId
      if (currentItemType === 2) {
        payload.stationId = item.stationId;
      } else if (item.pointId) {
        // 站点收藏：传 pointId + 经纬度
        payload.pointId = item.pointId;
        payload.latitude = item.latitude;
        payload.longitude = item.longitude;
      } else if (item.id) {
        // 兼容 id 字段作为 pointId 的场景
        payload.pointId = item.id;
        payload.latitude = item.latitude;
        payload.longitude = item.longitude;
      }

      await collectPoint(payload);

      setIsCollected(!isCollected);
      showToast({
        title: isCollected ? '已取消收藏' : '收藏成功',
        icon: 'none'
      });
    } catch (error) {
      console.log('收藏操作失败', error);
    }
  };

  return (
    <View className='site-list-item'>
      <View hoverClass='common-hover-class' onClick={handleSelectMainItem} className='history-item' key={itemKey}>
        <Image className='history-icon' src={iconSrc}></Image>
        <View className='history-info'>
          {renderHighlightedText(item.name || '_', 'history-name')}
          <View className='history-address-box'>
            {renderHighlightedText(item.address || '-', 'history-address')}
          </View>
        </View>
        {showDistance ?
          <View
            className='collect-box'
            hoverStopPropagation
            onClick={(e) => {
              e.stopPropagation();
              handleCollect(e);
            }}>
            <Image className='collect-icon' src={isCollected ? starSrc : noStarSrc} />
            {renderHighlightedText(item.distance || '-', 'history-distance')}
          </View>
          : null}
      </View>
      {shouldShowStationChildren && (
        <View className='site-gate'>
          {visibleStationChildren.map((child: any, index: number) => {
            const isMoreSlot = !expandStationChildren
              && stationChildren.length > MAX_VISIBLE_STATION_CHILDREN
              && index === MAX_VISIBLE_STATION_CHILDREN - 1;
            if (isMoreSlot) {
              return (
                <View
                  hoverClass='common-hover-class'
                  key='station-more'
                  className='site-gate-item-more'
                  onClick={() => setExpandStationChildren(true)}
                >
                  <View>更多</View>
                  <Image className='site-gate-more-icon' src="https://s.xiaopeng.com/xp-fe/robot-taxi/imgs/T-up.png" />
                </View>
              );
            }
            return (
              <View
                hoverClass='common-hover-class'
                key={child?.id || child?.pointId || `${child?.latitude}_${child?.longitude}_${index}`}
                onClick={() => handleSelectStationChild(child)}
              >
                {getStationChildName(child)}
              </View>
            );
          })}
        </View>
      )}
    </View>
  );
}
