import Taro from '@tarojs/taro';
import { showToast } from '../../../../../components/toast';
import { View, Image } from '@tarojs/components';
import { useEffect, useRef, useState } from 'react';
import { querySeatHv, setSeatHv } from '../../../../../api/seat-hv';
import type { SeatHvItem, SeatSetItem } from '../../../../../api/types/seat-hv';
import { getOrderId } from '../../../../../utils/order';
import { TripStatus } from '../../../../../constants/trip-status';
import '../../css-folder/seat-hv-control.less';

const SEAT_BG_URL = 'https://s.xiaopeng.com/xp-fe/robot-taxi/imgs/v2/seat_bg_0715.png';
const IMG_BASE = 'https://s.xiaopeng.com/xp-fe/robot-taxi/imgs/v2/';
const LOADING_ICON_URL = 'https://s.xiaopeng.com/xp-fe/robot-taxi/imgs/v2/T-switch-loading-20260715.png';
const NO_SEAT_TIP = '座椅调节暂不可用';
const APPLY_FAIL_TEXT = '网络异常，请重试';

type SeatKind = 'ventilation' | 'heating';

/**
 * 按档位取座椅通风/加热图标：seat_air_gray_level{n} / seat_heat_gray_level{n}（n=0~3）。
 */
function resolveSeatIcon(kind: SeatKind, level: number): string {
    const safeLevel = Math.max(0, Math.min(3, level || 0));
    const name = kind === 'ventilation' ? 'seat_air_gray_level' : 'seat_heat_gray_level';
    return `${IMG_BASE}${name}${safeLevel}@2x.png`;
}

type Props = {
    tripStatus: TripStatus;
    orderId?: string;
    pageDidShowVersion?: number;
    /** 后端推送：当前被指派车辆是否仍在执行上一单（连环单） */
    hasPreviousOrder?: boolean;
    /** 面板是否可见（可见时才查询，避免无谓请求） */
    active?: boolean;
};

/**
 * 计算下一档位：0 → 1 → … → levels → 0。
 */
function nextLevel(current: number, levels: number): number {
    if (levels <= 0) {
        return 0;
    }
    return current >= levels ? 0 : current + 1;
}

/**
 * 座椅通风/加热区域（内嵌于「温度调节」面板，无独立入口/弹窗）。
 */
export default function SeatHvArea({ tripStatus, orderId, pageDidShowVersion = 0, hasPreviousOrder = false, active = true }: Props) {
    const [seats, setSeats] = useState<SeatHvItem[]>([]);
    // 正在下发的按钮标识 `${position}:${kind}`（该按钮显示 loading，其余按钮置灰防重复），空串表示无
    const [applyingKey, setApplyingKey] = useState('');
    const querySeqRef = useRef(0);
    // 记录本次接驾态周期内已查询过座椅状态的订单 ID，避免重复请求（同一订单在初始化恢复
    // 流程中 tripStatus/orderId/hasPreviousOrder 会分批异步更新，触发本 effect 多次）。
    const queriedOrderIdRef = useRef('');

    const hasSeats = seats.length > 0;

    // 进入接驾态且面板可见时查询座椅状态；连环单不查询、不展示
    useEffect(() => {
        if (!active || tripStatus !== TripStatus.VehicleApproaching || hasPreviousOrder) {
            // 面板隐藏或离开接驾态：重置去重标记，允许下次可见/进入接驾态时重新查询一次。
            queriedOrderIdRef.current = '';
            return;
        }
        const targetOrderId = getOrderId(orderId);
        if (!targetOrderId) {
            return;
        }
        // 去重：同一订单在本次接驾态周期内只查询一次。
        if (queriedOrderIdRef.current === targetOrderId) {
            return;
        }
        queriedOrderIdRef.current = targetOrderId;
        const snapshotSeq = ++querySeqRef.current;
        querySeatHv(targetOrderId).then((res: any) => {
            if (querySeqRef.current !== snapshotSeq) {
                return;
            }
            const list: SeatHvItem[] = Array.isArray(res?.seats) ? res.seats : [];
            setSeats(list);
        }).catch(() => {
            if (querySeqRef.current !== snapshotSeq) {
                return;
            }
            setSeats([]);
        });
    }, [active, tripStatus, orderId, pageDidShowVersion, hasPreviousOrder]);

    // 点击座椅通风/加热按钮：档位循环 + 互斥联动 + 即时下发（仅该座椅）
    const handleSeatClick = async (seat: SeatHvItem, kind: SeatKind) => {
        if (applyingKey) {
            return;
        }
        const levels = kind === 'ventilation' ? seat.ventilationLevels : seat.heatingLevels;
        if (levels <= 0) {
            return; // 该能力不支持
        }
        const targetOrderId = getOrderId(orderId);
        if (!targetOrderId) {
            return;
        }

        // 计算目标档位 + 互斥：开一方则另一方归 0
        let nextVentilation = seat.ventilation;
        let nextHeating = seat.heating;
        if (kind === 'ventilation') {
            nextVentilation = nextLevel(seat.ventilation, seat.ventilationLevels);
            if (nextVentilation > 0) {
                nextHeating = 0;
            }
        } else {
            nextHeating = nextLevel(seat.heating, seat.heatingLevels);
            if (nextHeating > 0) {
                nextVentilation = 0;
            }
        }

        const payloadSeat: SeatSetItem = {
            position: seat.position,
            ventilationLevel: nextVentilation,
            heatingLevel: nextHeating
        };

        setApplyingKey(`${seat.position}:${kind}`);
        try {
            await setSeatHv({ orderId: targetOrderId, seats: [payloadSeat] });
            // 下发成功后更新该座椅本地状态
            setSeats((prev) => prev.map((item) => (
                item.position === seat.position
                    ? { ...item, ventilation: nextVentilation, heating: nextHeating }
                    : item
            )));
        } catch (error) {
            showToast({ title: APPLY_FAIL_TEXT, icon: 'none' });
        } finally {
            setApplyingKey('');
        }
    };

    if (!hasSeats) {
        return <View className='seat-hv-empty'>{NO_SEAT_TIP}</View>;
    }

    return (
        <View className='seat-hv-area'>
            <Image className='seat-hv-bg' src={SEAT_BG_URL} mode='widthFix' />
            <View className='seat-hv-list'>
                {seats.map((seat) => {
                    const showVentilation = seat.ventilationLevels > 0;
                    const showHeating = seat.heatingLevels > 0;
                    // 通风、加热都不支持 → 该座椅不显示任何按钮
                    if (!showVentilation && !showHeating) {
                        return null;
                    }
                    const ventilationKey = `${seat.position}:ventilation`;
                    const heatingKey = `${seat.position}:heating`;
                    const ventilationLoading = applyingKey === ventilationKey;
                    const heatingLoading = applyingKey === heatingKey;
                    // 有按钮正在下发时，其余按钮置灰防重复
                    const ventilationDisabled = !!applyingKey && !ventilationLoading;
                    const heatingDisabled = !!applyingKey && !heatingLoading;
                    // 仅加热（不支持通风，如三排）→ 单圆形按钮；支持通风 → 胶囊双图标
                    const isPillLayout = showVentilation && showHeating;
                    return (
                        <View className={`seat-hv-node seat-hv-node-${seat.position}`} key={seat.position}>
                            <View className={`seat-hv-ctrl ${isPillLayout ? 'is-pill' : 'is-single'}`}>
                                {showVentilation && (
                                    <View
                                        className={`seat-hv-btn ${seat.ventilation > 0 ? 'active' : ''} ${ventilationDisabled ? 'disabled' : ''}`}
                                        onClick={() => handleSeatClick(seat, 'ventilation')}
                                    >
                                        {ventilationLoading
                                            ? <Image className='seat-hv-btn-icon seat-hv-btn-loading' src={LOADING_ICON_URL} />
                                            : <Image className='seat-hv-btn-icon' src={resolveSeatIcon('ventilation', seat.ventilation)} />}
                                    </View>
                                )}
                                {isPillLayout && <View className='seat-hv-divider'></View>}
                                {showHeating && (
                                    <View
                                        className={`seat-hv-btn ${seat.heating > 0 ? 'active' : ''} ${heatingDisabled ? 'disabled' : ''}`}
                                        onClick={() => handleSeatClick(seat, 'heating')}
                                    >
                                        {heatingLoading
                                            ? <Image className='seat-hv-btn-icon seat-hv-btn-loading' src={LOADING_ICON_URL} />
                                            : <Image className='seat-hv-btn-icon' src={resolveSeatIcon('heating', seat.heating)} />}
                                    </View>
                                )}
                            </View>
                        </View>
                    );
                })}
            </View>
        </View>
    );
}
