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 } from 'react';
import { Easing } from 'react-native-reanimated'
import { useTeamAttendanceStore, useTeamCalendarStore, useAppStore } from '@/stores';
import { FlashList } from '@shopify/flash-list';

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

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

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

import dayjs from 'dayjs';

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

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

    // 订阅选中的日期
    const selectedDate = useTeamCalendarStore((state) => state.selectedDate);

    // 订阅团队打卡数据
    const teamCollection_day = useTeamAttendanceStore((state) => state.teamCollection_day);

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

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

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

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

    // 已打卡/未打卡 列表
    const checkInList = useMemo(() => ((teamCollection_day?.teamRealWorkInfo?.teamDatesWorkList || [])), [teamCollection_day]);
    const unCheckInList = useMemo(() => (teamCollection_day?.teamNoRealWorkInfo?.teamDatesWorkList || []), [teamCollection_day]);

    // 胶囊选项卡（根据原始数组长度派生，避免反复计算）
    const tabs = useMemo(() => [
        { key: 'checkIn', title: `${t('labels.clocked')} (${checkInList?.length || 0})` },
        { key: 'unCheckIn', title: `${t('labels.notClocked')} (${unCheckInList?.length || 0})` },
    ], [t, checkInList, unCheckInList]);

    // 过滤后的列表
    const filteredMembers = useMemo(() => (
        currentTab === 'checkIn' ? checkInList : unCheckInList
    ), [currentTab, checkInList, unCheckInList]);

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

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

    // 列表数值单位
    const valueUnit = useRef('')

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

    // 顶部文本内容
    const titleText = useMemo(() => {
        if (!selectedDate) return '';
        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 `${t('teamAttendance.statisticsDate')}：${dateStr}`;
    }, [selectedDate, i18n?.language, t]);

    // 顶部文本区域（使用 stickyHeaderIndices 固定在顶）
    const ListHeader = useCallback(() => (
        !hasHeader ? null : (
            <View>
                {!!titleText && (
                    <XStack style={styles.headerTitle}>
                        <CustomText style={styles.headerTitleText}>{titleText}</CustomText>
                    </XStack>
                )}
            </View>
        )
    ), [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('teamAttendance.checkInDetail')} />
                <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} />
                </View>
                <YStack style={styles.listContainer}>
                    <YStack style={styles.listContent}>
                        <ListHeader />
                        <FlashList
                            // 列表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 TeamCheckIn;

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',
    },
    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',
    },
});