import { FileStatus } from '@/components/file-upload/file-uploader';
import Choice from '@/components/user-message.tsx/choice';
import Done from '@/components/user-message.tsx/done';
import Look from '@/components/user-message.tsx/look';
import UserName from '@/components/user-message.tsx/userName';
import { fetchApi } from '@/lib/server-api-util';
import { User } from '@/types/user';
import { useEffect, useState } from 'react';
import { View } from 'react-native';
export type Steps = "userName" | "look" | "choice" | "done";

export default function UserMessage() {
    //   步骤
    const [steps, setSteps] = useState<Steps>("userName")
    const [username, setUsername] = useState('')
    const [avatar, setAvatar] = useState('')
    const [fileData, setFileData] = useState<FileStatus[]>([])
    const [isLoading, setIsLoading] = useState(false);
    const [userInfo, setUserInfo] = useState<User | null>(null);
    // 获取用户信息
    const getUserInfo = async () => {
        const res = await fetchApi<User>("/iam/user-info");
        setUserInfo(res);
        setUsername(res?.nickname || '');
        setAvatar(res?.avatar_file_url || '');
    }

    const handleUser = () => {
        setIsLoading(true);
        fetchApi("/iam/user/info", {
            method: "POST",
            body: JSON.stringify({
                username,
                avatar_file_id: fileData?.[0]?.id
            })
        }).then(() => {
            setIsLoading(false);
            getUserInfo();
            setSteps('done');
        }).catch(() => {
            setIsLoading(false);
        });
    };
    useEffect(() => {
        getUserInfo();
    }, []);

    return (
        <View className="h-screen" key={steps}>
            <View className="h-screen" key={steps}>
                {(() => {
                    const components = {
                        userName: (
                            <UserName
                                setSteps={setSteps}
                                username={username}
                                setUsername={setUsername}
                            />
                        ),
                        look: (
                            <Look
                                setSteps={setSteps}
                                fileData={fileData}
                                setFileData={setFileData}
                                isLoading={isLoading}
                                handleUser={handleUser}
                                avatar={avatar}
                            />
                        ),
                        choice: <Choice setSteps={setSteps} />,
                        done: <Done setSteps={setSteps} />
                    };

                    return components[steps as keyof typeof components] || null;
                })()}
            </View>
        </View>
    );
}
