import { Card, YStack, ZStack, Image } from 'tamagui';
import CustomText from '@/components/common/CustomText';
import React, { useEffect, useState, useMemo } from 'react';
import { StyleSheet } from 'react-native';
import { Image as ExpoImage } from 'expo-image';
import { getLastAvatarUrl, setLastAvatarUrl } from '@/utils/business/avatarCache';
import { useAuthStore } from '@/stores';
import { ServeUpdateAvatar } from '@/api/chat';
import { showSuccess, showError } from '@/utils/ui/toast';

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

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

const ResetAvatarScreen = () => {
    // 国际化
    const { t } = useTranslation('personal');
    const { t: tCommon } = useTranslation('common');

    // 当前登录用户信息（用于上传表单附加字段）
    const userInfo = useAuthStore(state => state.getUser());
    const { setUser } = useAuthStore();

    // 用户头像
    const [userAvatar, setUserAvatar] = useState('');

    // 读取上次成功的头像 URL（按当前登录用户作用域 + 用户ID）
    const lastAvatarUrl = useMemo(() => {
        return getLastAvatarUrl(userInfo?.ID)
    }, [userInfo?.ID]);

    useEffect(() => {
        let isActive = true;
        if (!userInfo?.ID) {
            return;
        }
        setUserAvatar(userInfo?.Avatar || '');
        return () => { isActive = false; };
    }, [userInfo]);

    // 上传配置：接口、方法、文件字段与表单附加参数（绑定当前用户）
    const uploadOptions = {
        url: `${process.env.EXPO_PUBLIC_API_BASE_URL}/upload/img`,
        method: 'POST',
        field: 'file',
        formDataExtra: {
            type: 'image',
            source: 'oa',
            mask: userInfo?.ID,
            is_compress: 0
        },
    };

    // 上传结果处理
    const onUploadResult = (result) => {
        if (result?.status === Number(0)) {
            showSuccess(tCommon('upload.success'));
            // 更新用户头像
            if (result?.data?.ori_url) {
                ServeUpdateAvatar({
                    erpUserId: userInfo.ID,
                    avatar: result.data?.ori_url,
                    type: "erp"
                }).then(res => {
                    setUserAvatar(result.data?.ori_url || '');
                    setUser({ ...userInfo, Avatar: result.data?.ori_url });
                }).catch(err => {
                    showError(err?.msg || err?.err || err?.error || tCommon('upload.failed'));
                });
            } else {
                showError(result.msg || result.err || result.error || tCommon('upload.failed'));
            }
        } else {
            showError(result.msg || result.err || result.error || tCommon('upload.failed'));
        }
    }

    return (
        <ZStack flex={1}>
            <ExpoImage
                source={require('@/assets/images/backgrounds/photo-bg.webp')}
                style={{ width: '100%', height: '100%' }}
                contentFit="cover"
                contentPosition="bottom center"
            />
            <CustomSafeArea>
                <CustomHeader title={t('userAvatar.modifyHeadImg')} />
                <YStack style={styles.container}>
                    <Card style={styles.card}>
                        {userAvatar ? (
                            <ExpoImage
                                source={{ uri: userAvatar }}
                                style={styles.photoImage}
                                contentFit="cover"
                                cachePolicy="disk"
                                recyclingKey={userAvatar}
                                placeholder={lastAvatarUrl ? { uri: lastAvatarUrl } : require('@/assets/images/chat/avatar/user.jpg')}
                                placeholderContentFit={lastAvatarUrl ? "cover" : "scale-down"}
                                placeholderContentPosition="center"
                                transition={lastAvatarUrl && lastAvatarUrl === userAvatar ? 0 : 300}
                                onLoad={() => {
                                    try {
                                        if (userInfo?.ID && userAvatar) {
                                            setLastAvatarUrl(userInfo.ID, userAvatar)
                                        }
                                    } catch { }
                                }}
                            />
                        ) : (
                            <YStack style={styles.photoContainer}>
                                <Image source={require('@/assets/images/personal/noPhoto.png')} style={styles.noPhotoImage} />
                                <CustomText style={styles.noPhotoText}>{t('userAvatar.noAvatar')}</CustomText>
                            </YStack>
                        )}
                    </Card>
                    <CustomUploader
                        uploadPhotoButtonStyle={styles.uploadPhotoButton}
                        mediaTypes={['images']}
                        selectionLimit={1}
                        uploadOptions={uploadOptions}
                        onUploadResult={onUploadResult}
                        uploadBtnText={tCommon('buttons.modify')} />
                </YStack>
            </CustomSafeArea>
        </ZStack>
    )
}

export default ResetAvatarScreen;

const styles = StyleSheet.create({
    container: {
        paddingVertical: wp(94),
        paddingHorizontal: wp(47),
        alignItems: 'center',
        justifyContent: 'center',
    },
    card: {
        paddingVertical: wp(26),
        paddingHorizontal: wp(26),
        boxShadow: '0px 3px 6px 1px rgba(0, 0, 0, 0.16)',
    },
    photoContainer: {
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#FAFAFA',
        width: wp(230),
        height: wp(230),
    },
    photoDesc: {
        fontSize: sp(12),
        fontFamily: 'Regular',
        color: '#747474',
        lineHeight: wp(17),
        marginTop: wp(10),
    },
    photoImage: {
        width: wp(230),
        height: wp(230),
    },
    noPhotoImage: {
        width: wp(100),
        height: wp(50),
    },
    noPhotoText: {
        fontSize: sp(11),
        fontFamily: 'Medium',
        color: '#BABABA',
        lineHeight: wp(17),
        marginTop: wp(14),
    },
    uploadPhotoButton: {
        marginTop: wp(60),
        width: wp(213),
        height: wp(38),
    },
});