import { View, XStack, YStack, Image } from 'tamagui';
import { StyleSheet, Platform } from 'react-native';
import { Image as ExpoImage } from 'expo-image';
import { useRef, useCallback, useMemo, useState, useEffect } from 'react';
import { Easing } from 'react-native-reanimated'
import { useTeamAttendanceStore, useTeamCalendarStore, useAppStore } from '@/stores';
import { useLocalSearchParams } from 'expo-router'
import { FlashList } from '@shopify/flash-list';

// 自定义组件
import { CustomSafeArea } from '@/components/common/CustomSafeArea';
import { CustomHeader } from '@/components/common/CustomHeader';

// UI组件
import TeamMember from '@/components/attendance/teamAttendance/teamMember';
import TabsPager from '@/components/ui/TabsPager';
import CustomText from '@/components/common/CustomText';

// 引入屏幕适配
import { wp, sp } from '@/utils/ui/screenUtils';
// 国际化
import { useTranslation } from '@/node_modules/react-i18next';

import dayjs from 'dayjs';
// 团队考勤统计、考勤详情数据映射配置
import { TEAM_ATTENDANCE_DATA_DEF } from '@/constants/attendanceStatus';
// 引入团队考勤模块工具函数
import { buildTeamStatisticsItems } from '@/utils/business/attendanceUtils';

// 胶囊高度
const segmentHeight = wp(34);
// 胶囊之间的间距
const GAP = wp(10);
// 统一动画配置（UI 线程）
const TAB_TIMING = { duration: 240, easing: Easing.out(Easing.cubic) };

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

    // 通过 expo-router 接收路由参数
    const params = useLocalSearchParams()
    const activeKey = params?.activeKey;
    const valueUnit = params?.valueUnit;

    // 订阅选中的日期 (日统计)
    const selectedDate = useTeamCalendarStore((state) => state.selectedDate);
    // 订阅选中的日期（周/月统计 裁剪后）
    const clippedDates = useTeamAttendanceStore((state) => state.clippedDates || []);
    const [startDate, endDate] = useMemo(() => {
        if (clippedDates.length === 0) return ['', '']
        return [clippedDates[0], clippedDates[clippedDates.length - 1]]
    }, [clippedDates])

    // 国际化
    const { t, i18n } = useTranslation('attendance');

    // 当前激活的索引
    const [activeIndex, setActiveIndex] = useState(0);
    const [currentTab, setCurrentTab] = useState('checkIn');

    // 从团队考勤store读取数据
    const activeStatisticsMode = useTeamAttendanceStore(s => s.activeStatisticsMode)
    const teamStatisticsData_day = useTeamAttendanceStore(s => s.teamStatisticsData_day)
    const teamStatisticsData_week = useTeamAttendanceStore(s => s.teamStatisticsData_week)
    const teamStatisticsData_month = useTeamAttendanceStore(s => s.teamStatisticsData_month)

    // 统计标签国际化映射（仅在语言变化时重算）
    const statsConfig = useMemo(() =>
        TEAM_ATTENDANCE_DATA_DEF.map(d => ({
            ...d,
            label: t(d.labelKey),
            labelUnit: t(d.labelUnitKey),
            valueUnit: t(d.valueUnitKey),
        })),
        [t]
    );

    // 当前模式的统计数据
    const statisticsData = useMemo(() => {
        if (activeStatisticsMode === 'day') return teamStatisticsData_day || [];
        if (activeStatisticsMode === 'week') return teamStatisticsData_week || [];
        if (activeStatisticsMode === 'month') return teamStatisticsData_month || [];
        return [];
    }, [activeStatisticsMode, teamStatisticsData_day, teamStatisticsData_week, teamStatisticsData_month]);

    // 日模式仅显示 外勤/迟到/早退 三个统计项；周/月显示全部
    const effectiveConfig = useMemo(() => {
        if (activeStatisticsMode === 'day') {
            const dayOrder = ['teamOutWorkNum', 'teamLateNum', 'teamBeforeNum'];
            const mapByKey = new Map(statsConfig.map(cfg => [cfg.key, cfg]));
            return dayOrder.map(k => mapByKey.get(k)).filter(Boolean);
        }
        return statsConfig;
    }, [activeStatisticsMode, statsConfig]);

    // 统计视图
    const statisticsViews = useMemo(() => buildTeamStatisticsItems(statisticsData, effectiveConfig), [statisticsData, effectiveConfig]);

    // 根据路由参数 activeKey 设置初始选中项
    useEffect(() => {
        if (!Array.isArray(statisticsViews) || statisticsViews.length === 0) return;
        const idx = statisticsViews.findIndex(v => v.key === activeKey);
        const nextIndex = idx >= 0 ? idx : 0;
        if (nextIndex !== activeIndex) setActiveIndex(nextIndex);
        const nextKey = statisticsViews[nextIndex]?.key;
        if (nextKey && nextKey !== currentTab) setCurrentTab(nextKey);
    }, [activeKey, statisticsViews]);

    // 切换选项卡
    const handleIndexChange = (i) => {
        setActiveIndex(i);
        const modeKey = tabs?.[i]?.key;
        if (modeKey) {
            setCurrentTab(modeKey)
        }
    }

    // 列表ref
    const listRef = useRef(null);

    // 根据统计模式数据动态生成胶囊选项卡
    const tabs = useMemo(() => (
        Array.isArray(statisticsViews)
            ? statisticsViews.map(v => ({ key: v.key, title: `${v.label}${v.key === 'teamAverageHour' ? '' : ` (${v.value || 0})`}` }))
            : []
    ), [statisticsViews]);

    // 当前选中统计项的明细列表
    const filteredMembers = useMemo(() => {
        const cur = statisticsViews.find(v => v.key === currentTab);
        const arr = Array.isArray(cur?.items) ? cur.items : [];
        return arr;
    }, [statisticsViews, currentTab]);

    // 顶部区域是否显示（只有列表有数据时显示）
    const hasHeader = useMemo(() => (filteredMembers?.length ?? 0) > 0, [filteredMembers]);

    // 列表key
    const keyExtractor = useCallback((item, index) => String(item?.staff?.staffUID ?? index), []);

    // 当前选中项的单位：优先使用统计项的 valueUnit，其次回退路由参数 valueUnit
    const selectedValueUnit = useMemo(() => {
        const cur = statisticsViews.find(v => v.key === currentTab);
        return cur?.valueUnit || valueUnit || '';
    }, [statisticsViews, currentTab, valueUnit]);

    // 渲染Item
    const renderItem = useCallback(({ item }) => {
        return (
            <TeamMember
                teamMember={item?.staff || {}}
                actionTypes={item?.actionTypes || []}
                applyTypes={item?.applyTypes || []}
                num={item?.num || 0}
                valueUnit={selectedValueUnit}
                averageDuration={item?.averageDuration || 0}
            />
        )
    }, [selectedValueUnit]);

    // 顶部文本内容
    const titleText = useMemo(() => {
        if (selectedDate && activeStatisticsMode === 'day') {
            const d = dayjs(selectedDate);
            const y = d.format('YYYY');
            const m = d.format('MM');
            const dd = d.format('DD');
            const lang = i18n?.language || 'zh-CN';
            const dateStr = lang.startsWith('zh')
                ? `${y}${t('attendanceDimension.year')}${m}${t('attendanceDimension.month')}${dd}${t('attendanceDimension.day')}`
                : d.format('YYYY.MM.DD');
            return (
                <XStack style={styles.headerTitle}>
                    <CustomText style={styles.headerTitleText}>{`${t('teamAttendance.statisticsDate')}：${dateStr}`}</CustomText>
                </XStack>
            );
        }
        if (startDate && endDate && activeStatisticsMode !== 'day' && currentTab === 'teamAverageHour') return (
            <XStack style={styles.headerTitle}>
                <XStack style={styles.headerTitleTextContainer}>
                    <CustomText style={styles.headerTitleText}>{`${dayjs(startDate).format('YYYY.MM.DD')} - ${dayjs(endDate).format('YYYY.MM.DD')}`}</CustomText>
                    <CustomText style={styles.headerTitleText}>{`${t('teamAttendance.averageHour')}`}</CustomText>
                    <CustomText style={styles.headerTitleText}>{`${statisticsData?.teamAverageHour || 0}${t('statisticsUnit.hour')}`}</CustomText>
                </XStack>
            </XStack>
        );
    }, [activeStatisticsMode, currentTab, selectedDate, startDate, endDate, statisticsData?.teamAverageHour, t, i18n?.language]);

    // 顶部文本区域（使用 stickyHeaderIndices 固定在顶）
    const ListHeader = useCallback(() => (
        hasHeader && !!titleText ? titleText : null
    ), [titleText, hasHeader]);

    // 空组件
    const Empty = useCallback(() => (
        <YStack alignItems="center" justifyContent="center" flex={1}>
            <Image source={require('@/assets/images/approve/5424.png')} style={styles.emptyImage} />
            <CustomText style={styles.emptyText}>{t('teamAttendance.noData')}</CustomText>
        </YStack>
    ), []);

    // 性能参数
    // 初始渲染数
    const initialNumToRender = 8;
    // 批量渲染数
    const maxToRenderPerBatch = 6;
    // 批量渲染时间间隔(ms)
    const updateCellsBatchingPeriod = 50; // 约一帧
    // 渲染窗口大小
    const windowSize = 6; // 可视窗口上下各 3 屏

    return (
        <View flex={1}>
            <ExpoImage
                source={require('@/assets/images/backgrounds/home-bg.webp')}
                style={StyleSheet.absoluteFill}
                contentFit="cover"
                transition={0}
                pointerEvents="none"
                cachePolicy="memory-disk"
            />
            <CustomSafeArea>
                <CustomHeader title={t('pageTitle.statisticsDetail')} />
                <View style={[styles.tabsPagerContainer, { height: segmentHeight + GAP * 2 }]}>
                    <TabsPager
                        tabs={tabs}
                        activeIndex={activeIndex}
                        onIndexChange={handleIndexChange}
                        primaryColor={primaryColor}
                        height={segmentHeight}
                        gap={GAP}
                        timing={TAB_TIMING}
                        gestureEnabled={false}
                        enableScroll={true}
                        adaptiveWidth={true} />
                </View>
                <YStack style={styles.listContainer}>
                    <YStack style={styles.listContent}>
                        <ListHeader />
                        <FlashList
                            key={currentTab}
                            // 列表ref
                            ref={listRef}
                            // 列表数据
                            data={filteredMembers}
                            // 列表key
                            keyExtractor={keyExtractor}
                            // 渲染Item
                            renderItem={renderItem}
                            // 空组件
                            ListEmptyComponent={Empty}
                            // 列表内容容器样式
                            contentContainerStyle={styles.contentContainerStyle}

                            // 性能参数
                            // 初始渲染数
                            initialNumToRender={initialNumToRender}
                            // 批量渲染数
                            maxToRenderPerBatch={maxToRenderPerBatch}
                            // 批量渲染时间间隔(ms)
                            updateCellsBatchingPeriod={updateCellsBatchingPeriod}
                            // 渲染窗口大小
                            windowSize={windowSize}
                            // 移除屏幕外的子视图
                            removeClippedSubviews={Platform.OS === 'android'}
                            // 显示滚动条
                            showsVerticalScrollIndicator={false}
                        />
                    </YStack>
                </YStack>
            </CustomSafeArea>
        </View>
    )
}

export default TeamStatistics;

const styles = StyleSheet.create({
    tabsPagerContainer: {
        paddingVertical: wp(10),
    },
    listContainer: {
        flex: 1,
        paddingHorizontal: wp(16),
    },
    headerTitle: {
        paddingVertical: wp(8),
        borderBottomWidth: wp(1),
        borderBottomColor: '#F8F8F8',
        backgroundColor: '#fff',
    },
    headerTitleText: {
        color: '#999999',
        fontSize: sp(14),
        lineHeight: wp(20),
        fontFamily: 'Regular',
    },
    headerTitleTextContainer: {
        alignItems: 'center',
        justifyContent: 'flex-start',
        gap: wp(6),
        flexWrap: 'wrap',
    },
    listContent: {
        backgroundColor: '#fff',
        borderRadius: wp(4),
        flex: 1,
        boxShadow: '0px 3px 6px 1px rgba(188, 188, 188, 0.08)',
        paddingHorizontal: wp(8),
    },
    contentContainerStyle: {
        flexGrow: 1,
    },
    emptyImage: {
        width: wp(238),
        height: wp(131),
    },
    emptyText: {
        color: '#999999',
        fontSize: sp(14),
        lineHeight: wp(20),
        fontFamily: 'Regular',
    },
});
