import { View, Image, TouchableOpacity, StyleSheet } from 'react-native';
import Animated, { LinearTransition, Easing, useSharedValue, useAnimatedStyle, withTiming } from 'react-native-reanimated';
import CustomText from '@/components/common/CustomText';
import { ChevronRight } from '@tamagui/lucide-icons';
import { useEffect, useState, useMemo, memo } from 'react';
import { useRouter } from 'expo-router';
// 引入用户信息
import { useAuthStore } from '@/stores';

// 引入国际化
import { useTranslation } from 'react-i18next';
// 引入屏幕适配
import { wp, sp } from '@/utils/ui/screenUtils';
// 引入根据路径获取对象的值
import { getByPath } from '@/utils/business/attendanceUtils';

/**
 * 基本信息配置
 * - labelKey：国际化 key，用于展示左侧标签
 * - itemKey：从 userInfo 中取值的路径，支持嵌套路径（如 'leaderInfo.company'）或数组字段
 * - format：可选，针对复杂类型进行格式化为字符串
 */
const basics = [
    {
        labelKey: 'basicInfo.company',
        itemKey: 'leaderInfo.company',
    },
    {
        labelKey: 'basicInfo.department',
        itemKey: 'PositionUsers',
        format: v => Array.isArray(v) ? v.map(i => i.DepartmentName ?? i).join('、') : (v ?? ''),
    },
    {
        labelKey: 'basicInfo.position',
        itemKey: 'PositionUsers',
        format: v => Array.isArray(v) ? v.map(i => i.PositionName ?? i).join('、') : (v ?? ''),
    },
    {
        labelKey: 'basicInfo.supervisor',
        itemKey: 'leaderInfo.departmentLeaders',
        format: v => Array.isArray(v) ? v.map(i => i.userName ?? i).join('、') : (v ?? ''),
    },
    {
        labelKey: 'basicInfo.phone',
        itemKey: 'TelNum',
    },
    {
        labelKey: 'basicInfo.entryDate',
        itemKey: 'EnterDate',
    },
]

/**
 * 单条基本信息渲染项（折叠列表子项）
 * 使用 memo 包裹，确保在 props 不变时跳过重渲染
 */
const BasicInfoItem = memo(({ t, labelKey, value, singleValue, hasMultiple, isOpen, onToggle, onPress }) => {
    const rotation = useSharedValue(isOpen ? 90 : 0);
    
    useEffect(() => {
        rotation.value = withTiming(isOpen ? 90 : 0, {
            duration: 220,
            easing: Easing.out(Easing.cubic),
        });
    }, [isOpen]);

    const arrowAnimatedStyle = useAnimatedStyle(() => ({
        transform: [{ rotate: `${rotation.value}deg` }],
    }));

    return (
        <Animated.View layout={LinearTransition.duration(220).easing(Easing.out(Easing.cubic))}>
            <TouchableOpacity
                style={styles.accordionHeaderTrigger}
                activeOpacity={0.7}
                onPress={hasMultiple ? () => onToggle(labelKey) : onPress}
                disabled={!hasMultiple && !onPress}
            >
                <View style={styles.basicItem}>
                    <CustomText style={styles.basicItemLabel}>{t(labelKey)}</CustomText>
                    <View style={styles.basicItemValue}>
                        {!isOpen && <CustomText style={styles.basicItemValueText}>{singleValue || ''}</CustomText>}
                        {hasMultiple && (
                            <Animated.View style={[{ marginLeft: wp(10) }, arrowAnimatedStyle]}>
                                <ChevronRight size={wp(20)} color="#747474" />
                            </Animated.View>
                        )}
                    </View>
                </View>
            </TouchableOpacity>
            {hasMultiple && (
                <Animated.View
                    style={[styles.accordionContent, !isOpen && styles.accordionContentCollapsed]}
                    layout={LinearTransition.duration(220).easing(Easing.out(Easing.cubic))}
                >
                    <CustomText style={styles.basicItemValueText}>{value || ''}</CustomText>
                </Animated.View>
            )}
        </Animated.View>
    );
});

const BasicInfo = () => {
    // 国际化
    const { t } = useTranslation('personal');
    const router = useRouter();
    // 用户信息
    const userInfo = useAuthStore(state => state.getUser());
    const fetchLeaderInfo = useAuthStore(state => state.fetchLeaderInfo);
    useEffect(() => {
        // 首次挂载拉取主管/部门领导等信息，合并至 userInfo.leaderInfo
        fetchLeaderInfo();
    }, []);

    // 受控的展开状态（存 key）
    const [openValues, setOpenValues] = useState([]);
    /**
     * 通过 useMemo 预计算渲染所需的派生数据：
     * - value：最终展示字符串（可能由数组/对象格式化而来）
     * - singleValue：折叠时展示的第一项，避免多次 split
     * - hasMultiple：是否有多项，决定是否显示下拉箭头与是否可展开
     */
    const derivedBasics = useMemo(() => basics.map((basic) => {
        const raw = getByPath(userInfo, basic.itemKey);
        const value = basic.format ? basic.format(raw, userInfo) : (raw ?? '');
        const valueParts = typeof value === 'string' ? value.split('、') : [];
        return {
            ...basic,
            value,
            singleValue: valueParts.length > 0 ? valueParts[0] : value,
            hasMultiple: valueParts.length > 1,
        };
    }), [userInfo]);
    // 切换展开项（支持多项同时展开）
    const toggleOpen = (key) => {
        setOpenValues((prev) => prev.includes(key) ? prev.filter(k => k !== key) : [...prev, key]);
    };

    return (
        <View>
            <View style={styles.moduleItem}>
                <Image source={require('@/assets/images/personal/basicInfo.png')} style={styles.moduleItemIcon} />
                <CustomText style={styles.moduleItemTitle}>{t('modules.basicInfo')}</CustomText>
            </View>
            <View style={styles.basicInfo}>
                {derivedBasics.map((item) => {
                    const isOpen = openValues.includes(item.labelKey);
                    const onPress = item.labelKey === 'basicInfo.phone' ? () => router.push('/personal/changePhone') : undefined;
                    return (
                        <BasicInfoItem
                            key={item.labelKey}
                            t={t}
                            labelKey={item.labelKey}
                            value={item.value}
                            singleValue={item.singleValue}
                            hasMultiple={item.hasMultiple}
                            isOpen={isOpen}
                            onToggle={toggleOpen}
                            onPress={onPress}
                        />
                    );
                })}
            </View>
        </View>
    )
}

export default BasicInfo;

const styles = StyleSheet.create({
    moduleItem: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-start',
        paddingVertical: wp(18),
        paddingLeft: wp(6),

    },
    moduleItemIcon: {
        width: wp(20),
        height: wp(20),
    },
    moduleItemTitle: {
        fontSize: sp(14),
        fontFamily: 'Medium',
        color: '#191919',
        lineHeight: wp(20),
        marginLeft: wp(10),
    },
    basicInfo: {
        paddingLeft: wp(31),
    },
    basicItem: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        borderTopWidth: wp(1),
        borderTopColor: '#F8F8F8',
        paddingVertical: wp(7),
        paddingLeft: wp(4),
        paddingRight: wp(10),
    },
    basicItemLabel: {
        fontSize: sp(14),
        fontFamily: 'Medium',
        color: '#191919',
        lineHeight: wp(20),
    },
    basicItemValue: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-end',
        gap: wp(10),
    },
    basicItemValueText: {
        fontSize: sp(14),
        fontFamily: 'Medium',
        color: '#747474',
        lineHeight: wp(20),
        width: wp(220),
        textAlign: 'right',
    },
    accordionHeaderTrigger: {
        borderLeftWidth: 0,
        borderRightWidth: 0,
        borderTopWidth: 0,
        borderBottomWidth: 0,
        paddingTop: 0,
        paddingBottom: 0,
        paddingLeft: 0,
        paddingRight: 0,
        width: '100%',
    },
    accordionContent: {
        paddingLeft: wp(4),
        paddingRight: wp(10),
        paddingBottom: wp(7),
        overflow: 'hidden',
    },
    accordionContentCollapsed: {
        height: 0,
        paddingBottom: 0,
    },
})