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"

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 (
        <div
            style={{
                width: '100%',
                height: '100%',
                padding: '1rem'
            }}
        >
            {currentUser &&
                <div style={{
                    display: 'flex',
                    flexDirection: 'column',
                    width: '100%',
                    gap: '1rem'
                }}>
                    <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="Смена пароля"
                    />
                </div>
            }
        </div>
    )
}