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 { ServeEmployeeFileList, ServeUserUpdate } from '@/api/personal';
import { showSuccess, showError } from '@/utils/ui/toast';
import { useAppStore } from '@/stores';

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

// UI组件
import LoadingSpinner from '@/components/ui/LoadingSpinner';

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

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

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

    // 最近上传的照片
    const [recentImg, setRecentImg] = useState('');
    // 请求是否完成标记
    const [hasFetched, setHasFetched] = useState(false);

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

    useEffect(() => {
        let isActive = true;
        if (!userInfo?.ID) {
            return;
        }
        const fetchRecent = async () => {
            try {
                const res = await ServeEmployeeFileList({ userID: userInfo.ID });
                if (!isActive) return;
                if (res?.status === 0) {
                    const url = res?.data?.employeeFileList?.[0]?.recentImg;
                    const normalized = typeof url === 'string' ? url.trim() : '';
                    setRecentImg(normalized && normalized !== 'null' && normalized !== 'undefined' ? normalized : '');
                } else {
                    showError(res.msg || res.err || res.error);
                }
            } catch (err) {
                if (!isActive) return;
                showError(err?.msg || err?.message || err?.error);
            } finally {
                if (isActive) setHasFetched(true);
            }
        };
        fetchRecent();
        return () => { isActive = false; };
    }, [userInfo?.ID]);

    // 读取上次成功的最近照片 URL（按当前用户作用域 + 固定键）
    const lastRecentUrl = useMemo(() => {
        return getLastAvatarUrl('recent-photo')
    }, [userInfo?.ID]);

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

    // 上传结果处理
    const onUploadResult = (result) => {
        if (result?.status === Number(0)) {
            showSuccess(tCommon('upload.success'));
            // 更新最近上传的照片
            if (result?.data?.file) {
                ServeUserUpdate({ ID: userInfo.ID, RecentImg: result.data?.file }).then(res => {
                    if (res?.status === Number(0)) {
                        setRecentImg(result.data?.file || '');
                    } else {
                        showError(res.msg || res.err || res.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('settingsAndPrivacy.personalPhoto')} />
                <YStack style={styles.container}>
                    <Card style={styles.card}>
                        {recentImg ? (
                            <ExpoImage
                                source={{ uri: recentImg }}
                                style={styles.photoImage}
                                contentFit="cover"
                                cachePolicy="disk"
                                recyclingKey={recentImg}
                                placeholder={lastRecentUrl ? { uri: lastRecentUrl } : require('@/assets/images/personal/noPhoto.png')}
                                placeholderContentFit={lastRecentUrl ? "cover" : "scale-down"}
                                placeholderContentPosition="center"
                                transition={lastRecentUrl && lastRecentUrl === recentImg ? 0 : 300}
                                onLoad={() => {
                                    try {
                                        if (recentImg) {
                                            setLastAvatarUrl('recent-photo', recentImg)
                                        }
                                    } catch { }
                                }}
                                onError={() => setRecentImg('')}
                            />
                        ) : (
                            <YStack style={styles.photoContainer}>
                                {hasFetched ? (
                                    <>
                                        <Image source={require('@/assets/images/personal/noPhoto.png')} style={styles.noPhotoImage} />
                                        <CustomText style={styles.noPhotoText}>{t('recentPhoto.noPhoto')}</CustomText>
                                    </>
                                ) : (
                                    <LoadingSpinner size={wp(40)} color={primaryColor} />
                                )}
                            </YStack>
                        )}
                    </Card>
                    <CustomText style={styles.photoDesc}>*{t('recentPhoto.uploadPhotoDesc')}</CustomText>
                    <CustomUploader
                        uploadPhotoButtonStyle={styles.uploadPhotoButton}
                        mediaTypes={['images']}
                        selectionLimit={1}
                        uploadOptions={uploadOptions}
                        onUploadResult={onUploadResult} />
                </YStack>
            </CustomSafeArea>
        </ZStack>
    )
}

export default RecentPhotoScreen;

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(30),
        width: wp(213),
        height: wp(38),
    },
});
