import UserService from "../services/UserService"
import { setUserData, useAuthStore } from "../store/auth"
import { useEffect, useState } from "react"
import { CreateField } from "../interfaces/create"
import { IUser } from "../interfaces/user"
import FormFields from "../components/FormFields"
import AuthService from "../services/AuthService"
import { Flex, ScrollAreaAutosize } from "@mantine/core"

export default function Settings() {
    const { token } = useAuthStore()
    const [currentUser, setCurrentUser] = useState<IUser>()

    const fetchCurrentUser = async () => {
        if (token) {
            await UserService.getCurrentUser(token).then(response => {
                setCurrentUser(response.data)
            })
        }
    }

    useEffect(() => {
        if (token) {
            fetchCurrentUser()
        }
    }, [token])

    const profileFields: CreateField[] = [
        //{ key: 'email', headerName: 'E-mail', type: 'string', required: true },
        //{ key: 'login', headerName: 'Логин', type: 'string', required: true },
        { key: 'phone', headerName: 'Телефон', type: 'string', required: false },
        { key: 'name', headerName: 'Имя', type: 'string', required: true },
        { key: 'surname', headerName: 'Фамилия', type: 'string', required: true },
    ]

    const passwordFields: CreateField[] = [
        { key: 'password', headerName: 'Новый пароль', type: 'string', required: true, inputType: 'password' },
        { key: 'password_confirm', headerName: 'Подтверждение пароля', type: 'string', required: true, inputType: 'password', watch: 'password', watchMessage: 'Пароли не совпадают', include: false },
    ]

    return (
        <ScrollAreaAutosize
            w={'100%'}
            h={'100%'}
            p='sm'
        >
            {currentUser &&
                <Flex direction='column' gap='sm' w='100%'>
                    <FormFields
                        fields={profileFields}
                        defaultValues={currentUser}
                        mutateHandler={(data: any) => {
                            setUserData(data)
                        }}
                        submitHandler={(data) => UserService.updateUser({ id: currentUser.id, ...data })}
                        title="Пользователь"
                    />

                    <FormFields
                        fields={passwordFields}
                        submitHandler={(data) => AuthService.updatePassword({ id: currentUser.id, ...data })}
                        title="Смена пароля"
                    />
                </Flex>
            }
        </ScrollAreaAutosize>
    )
}