import React, { memo, useMemo, useCallback } from 'react';
import { StyleSheet, Pressable, ScrollView, TouchableOpacity } from 'react-native';
import { XStack, YStack } from 'tamagui';
import { ChevronRight } from '@tamagui/lucide-icons';
import { router } from 'expo-router';

// 自定义组件
import CustomAvatar from '@/components/ui/CustomAvatar';
import CustomText from '@/components/common/CustomText';

// 屏幕适配
import { wp, sp } from '@/utils/ui/screenUtils';

// 国际化
import { useTranslation } from '@/node_modules/react-i18next';

// 申请类型与打卡类型字典
import { applyTypes as applyTypesDict } from '@/constants/apply.js';
import { ATTENDANCE_STATUS_DEFS as cardTypesDict } from '@/constants/attendanceStatus.js';

// store
import { 
    useTeamAttendanceStore,
    useTeamCalendarStore,
    useStatisticsStore,
    useCalendarStore,
    useAppStore
} from '@/stores';

// 打卡类型的标签白名单
const ALLOWED_ACTION_TYPES = new Set([
    'outWork',
    'late',
    'outWorkLate',
    'outWorkBefore',
    'before',
]);

// TeamMember 列表项
const TeamMember = memo(function TeamMember({
    // 成员信息
    teamMember = {},
    // 当前成员的打卡类型数组
    actionTypes = [],
    // 申请类型数组（日统计下可点击按钮，周/月统计下仅展示标签）
    applyTypes = [],
    // 周/月模式下的统计展示
    num = 0,
    valueUnit = '',
    averageDuration = 0,
    // 点击事件
    onPress,
    onTagPress,
}) {
    // 当前激活的统计模式
    const { activeStatisticsMode } = useTeamAttendanceStore();

    // 设置要查看的指定考勤人员信息
    const { setViewTeamMember } = useTeamAttendanceStore();

    //获取主色
    const primaryColor = useAppStore(s => s.primary)

    // 打卡类型国际化标签
    const { t, i18n } = useTranslation('attendance');
    const actionKeyToLabelMap = useMemo(() => {
        const map = new Map();
        for (const item of cardTypesDict || []) {
            const key = item?.key;
            if (!key) continue;
            const labelKey = item?.labelKey;
            const label = labelKey ? t(labelKey, { defaultValue: key }) : key;
            map.set(key, label);
        }
        return map;
    }, [i18n.language]);

    // 申请类型国际化标签
    const valueToLabelMap = useMemo(() => {
        const map = new Map();
        for (const item of applyTypesDict || []) {
            const value = item?.value;
            if (!value) continue;
            const lk = item?.labelKey;
            const fallback = item?.label || String(value);
            const label = lk
                ? t(lk, { defaultValue: fallback })
                : t(`applyType.${value}`, { defaultValue: fallback });
            map.set(value, label);
        }
        return map;
    }, [i18n.language]);

    // 点击卡片
    const handlePress = useCallback(() => {
        if (onPress) {
            onPress(teamMember);
        } else {
            // 1) 预先快照当前“我的”个人统计/日历状态
            let personalSnapshot = null;
            try {
                const statsStore = useStatisticsStore.getState();
                const calStore = useCalendarStore.getState();
                personalSnapshot = {
                    activeStatisticsMode: statsStore?.activeStatisticsMode || 'day',
                    dayVisibleYM: calStore?.dayVisibleYM,
                    selectedDate: calStore?.selectedDate,
                    weekVisibleYM: calStore?.weekVisibleYM,
                    weekSelectedMonday: calStore?.weekSelectedMonday,
                    monthVisibleYM: calStore?.monthVisibleYM,
                    __savedAt: Date.now(),
                };
            } catch (_) { }

            // 2) 设置要查看的指定考勤人员信息（附带“我的”快照，供回退时恢复）
            try {
                setViewTeamMember(personalSnapshot ? { ...teamMember, __personalSnapshot: personalSnapshot } : teamMember);
            } catch (_) {
                setViewTeamMember(teamMember);
            }

            // 3) 在导航前，将“团队当前模式与日期锚点”同步到“个人统计/日历 store”
            try {
                const teamStore = useTeamAttendanceStore.getState();
                const teamCal = useTeamCalendarStore.getState();
                const statsStore = useStatisticsStore.getState();
                const calStore = useCalendarStore.getState();

                const mode = teamStore?.activeStatisticsMode || 'day';
                statsStore?.setActiveStatisticsMode?.(mode);

                if (mode === 'day') {
                    const dv = teamCal?.dayVisibleYM;
                    const sd = teamCal?.selectedDate;
                    if (dv?.year && dv?.month) calStore?.setDayVisibleYM?.(dv);
                    if (sd) calStore?.setSelectedDate?.(sd);
                } else if (mode === 'week') {
                    const wv = teamCal?.weekVisibleYM;
                    const wm = teamCal?.weekSelectedMonday;
                    if (wv?.year && wv?.month) calStore?.setWeekVisibleYM?.(wv);
                    if (wm) calStore?.setWeekSelectedMonday?.(wm);
                } else if (mode === 'month') {
                    const mv = teamCal?.monthVisibleYM;
                    if (mv?.year && mv?.month) calStore?.setMonthVisibleYM?.(mv);
                }
            } catch (e) { }

            // 4) 导航到个人考勤页
            router.push('/attendance/attendanceStatistics');
        }
    }, [onPress, teamMember]);

    // 点击申请类型标签按钮
    const handleTagPress = useCallback(
        (id) => {
            if (onTagPress) {
                onTagPress(id);
            } else {
                router.push({
                    pathname: '/webview',
                    params: {
                        url: `${process.env.EXPO_PUBLIC_H5_APPROVAL_URL}/#/pages/applyfor/components/details/index?ID=${id}&isMeCheck=false`,
                        ID: id,
                        isMeCheck: false,
                    }
                });
            }
        },
        [onTagPress]
    );

    // 计算打卡类型合并标签（日统计模式右侧文案）：过滤 + 去重 + 映射 + join('/')
    const actionTypeLabels = useMemo(() => {
        if (!Array.isArray(actionTypes) || actionTypes.length === 0) return '';
        const seen = new Set();
        const unique = [];
        for (const type of actionTypes) {
            if (!ALLOWED_ACTION_TYPES.has(type)) continue;
            const label = actionKeyToLabelMap.get(type) || type;
            if (!label) continue;
            if (!seen.has(label)) {
                seen.add(label);
                unique.push(label);
            }
        }
        return unique.length > 1 ? unique.join('/') : unique[0] || '';
    }, [actionTypes, actionKeyToLabelMap]);

    // 日统计：申请类型按钮数据（label+id 去重；用于可点击跳转）
    const applyTypeButtons = useMemo(() => {
        if (!Array.isArray(applyTypes) || applyTypes.length === 0) return [];
        const seen = new Set();
        const result = [];
        for (const item of applyTypes) {
            const value = item?.applyType ?? item;
            const label = valueToLabelMap.get(value) || String(value);
            const id = item?.id ?? value;
            if (!label) continue;
            const key = label + '|' + String(id);
            if (seen.has(key)) continue;
            seen.add(key);
            result.push({ id, label });
        }
        return result;
    }, [applyTypes, valueToLabelMap]);

    // 周/月统计：申请类型标签数据（按 label 去重；仅展示不可跳转）
    const applyTypeLabels = useMemo(() => {
        if (!Array.isArray(applyTypes) || applyTypes.length === 0) return [];
        const seen = new Set();
        const labels = [];
        for (const item of applyTypes) {
            const value = item?.applyType ?? item;
            const label = valueToLabelMap.get(value) || String(value);
            if (!label || seen.has(label)) continue;
            seen.add(label);
            labels.push(label);
        }
        return labels;
    }, [applyTypes, valueToLabelMap]);

    // 统计片段文案（周/月模式）：useMemo 组装，避免在 JSX 内拼接
    const statTexts = useMemo(() => {
        const unitHour = t('statisticsUnit.hour');
        const unitDay = t('statisticsUnit.day');
        const attendanceWord = t('statisticsWord.attendance');
        const avgText = averageDuration > 0 ? `${averageDuration}${unitHour}` : '';
        const daysText = averageDuration > 0 && num > 0 ? `${attendanceWord}${num}${unitDay}` : `${num}${valueUnit}`;
        return { avgText, daysText };
    }, [averageDuration, num, valueUnit, i18n.language]);

    const isDay = activeStatisticsMode === 'day';

    return (
        <TouchableOpacity onPress={handlePress} style={styles.container}>
            <XStack alignItems="center" gap={wp(8)}>
                <CustomAvatar
                    mode={1}
                    userName={teamMember?.name || '用户'}
                    avatar={teamMember?.avatar}
                    avatarKey={teamMember?.staffUID}
                    size={wp(48)}
                    circular={true}
                />

                <YStack flex={1}>
                    <XStack alignItems="center" justifyContent="space-between" gap={wp(8)}>
                        <XStack alignItems="center" gap={wp(8)} flex={1}>
                            <CustomText style={styles.name} numberOfLines={1}>
                                {teamMember?.name || ''}
                            </CustomText>
                            <ScrollView
                                horizontal
                                showsHorizontalScrollIndicator={false}
                                nestedScrollEnabled
                                style={styles.tagScroll}
                                contentContainerStyle={styles.tagScrollContent}
                            >
                                {isDay && applyTypeButtons.length > 0 && (
                                    <XStack gap={wp(8)}>
                                        {applyTypeButtons.map((item) => (
                                            <TouchableOpacity
                                                key={String(item.id)}
                                                onPress={(e) => {
                                                    e.stopPropagation?.();
                                                    handleTagPress(item.id);
                                                }}
                                                style={styles.tagButton}
                                            >
                                                <CustomText style={styles.tagButtonText}>{item.label}</CustomText>
                                            </TouchableOpacity>
                                        ))}
                                    </XStack>
                                )}
                                {!isDay && applyTypeLabels.length > 0 && (
                                    <XStack gap={wp(8)}>
                                        {applyTypeLabels.map((label) => (
                                            <Pressable key={label} style={styles.tagLabel}>
                                                <CustomText style={styles.tagLabelText}>{label}</CustomText>
                                            </Pressable>
                                        ))}
                                    </XStack>
                                )}
                            </ScrollView>
                        </XStack>
                        {isDay && !!actionTypeLabels && (
                            <CustomText style={[
                                styles.checkInDetail,
                                { color: primaryColor }
                            ]} numberOfLines={1}>
                                {actionTypeLabels}
                            </CustomText>
                        )}

                        {!isDay && (
                            <XStack gap={wp(10)} alignItems="center" justifyContent="flex-end">
                                <CustomText style={[
                                    styles.statText,
                                    { color: primaryColor }
                                ]} numberOfLines={1}>{statTexts.avgText}</CustomText>
                                <CustomText style={[
                                    styles.statText,
                                    { flexShrink: 1, color: primaryColor }
                                ]}
                                    numberOfLines={1}
                                    ellipsizeMode="tail"
                                >{statTexts.daysText}</CustomText>
                            </XStack>
                        )}
                    </XStack>
                    <XStack alignItems="center" justifyContent="space-between" gap={wp(8)}>
                        <CustomText style={styles.company} numberOfLines={1}>
                            {teamMember?.company || ''}
                        </CustomText>
                        <ChevronRight size={wp(12)} color="#999999" />
                    </XStack>
                </YStack>
            </XStack>
        </TouchableOpacity>
    );
});

export default TeamMember;

const styles = StyleSheet.create({
    container: {
        paddingVertical: wp(12),
        borderBottomColor: '#f8f8f8',
        borderBottomWidth: 1,
    },
    name: {
        fontSize: sp(16),
        lineHeight: wp(22),
        fontFamily: 'SemiBold',
        color: '#191919',
        maxWidth: wp(140),
    },
    tagScroll: {
        flexShrink: 1,
    },
    tagScrollContent: {
        alignItems: 'center',
        paddingRight: wp(8),
    },
    tagButton: {
        backgroundColor: '#1f80f0',
        paddingVertical: wp(3),
        paddingHorizontal: wp(6),
        borderRadius: wp(4),
    },
    tagButtonText: {
        fontSize: sp(12),
        color: '#fff',
    },
    tagLabel: {
        backgroundColor: '#1f80f0',
        paddingVertical: wp(3),
        paddingHorizontal: wp(6),
        borderRadius: wp(4),
    },
    tagLabelText: {
        fontSize: sp(12),
        color: '#fff',
        lineHeight: wp(16),
    },
    checkInDetail: {
        fontSize: sp(12),
        color: '#1f80f0',
        maxWidth: wp(160),
    },
    company: {
        fontSize: sp(14),
        lineHeight: wp(20),
        color: '#999999',
        flexShrink: 1,
    },
    statText: {
        fontSize: sp(12),
        color: '#1f80f0',
        flexShrink: 0,
        textAlign: 'right',
        maxWidth: wp(140),
    },
});