import { useCallback, useEffect, useState } from 'react' import Alert from '@mui/material/Alert' import Box from '@mui/material/Box' import Button from '@mui/material/Button' import Chip from '@mui/material/Chip' import Stack from '@mui/material/Stack' import TextField from '@mui/material/TextField' import Typography from '@mui/material/Typography' import { useMutation } from '@tanstack/react-query' import { useUnit } from 'effector-react' import { useForm } from 'react-hook-form' import { $user, changePasswordFx, fetchAuthMethodsFx, setPasswordFx, unlinkOAuthFx, type AuthMethod, } from '@/shared/model/auth' const METHOD_LABELS: Record = { password: 'Пароль', vk: 'ВКонтакте', yandex: 'Яндекс' } export function AuthMethodsSection() { const user = useUnit($user) const [authMethods, setAuthMethods] = useState([]) const [showSetPassword, setShowSetPassword] = useState(false) const [fetchError, setFetchError] = useState(null) const passwordForm = useForm<{ password: string; passwordConfirm: string }>({ defaultValues: { password: '', passwordConfirm: '' }, }) useEffect(() => { fetchAuthMethodsFx() .then(setAuthMethods) .catch((err) => { setAuthMethods([]) setFetchError(err?.message || 'Не удалось загрузить методы авторизации') }) }, []) const setPasswordMutation = useMutation({ mutationFn: async (pw: string) => { await setPasswordFx(pw) const methods = await fetchAuthMethodsFx() setAuthMethods(methods) setShowSetPassword(false) }, onError: () => {}, }) const unlinkMutation = useMutation({ mutationFn: async (provider: 'vk' | 'yandex') => { await unlinkOAuthFx(provider) const methods = await fetchAuthMethodsFx() setAuthMethods(methods) }, onError: () => {}, }) const [showChangePassword, setShowChangePassword] = useState(false) const changePasswordForm = useForm<{ oldPassword: string; newPassword: string; confirmPassword: string }>({ defaultValues: { oldPassword: '', newPassword: '', confirmPassword: '' }, }) const changePasswordMutation = useMutation({ mutationFn: async (params: { oldPassword: string; newPassword: string }) => { await changePasswordFx(params) }, onSuccess: () => { setShowChangePassword(false) changePasswordForm.reset() }, }) const linkedCount = useCallback(() => { return authMethods.filter((m) => m.active).length }, [authMethods]) if (!user) return null return ( Методы входа {fetchError && ( {fetchError} )} {authMethods.map((m) => ( {METHOD_LABELS[m.type] || m.type} {m.active && m.type !== 'password' && ( )} {m.active && m.type === 'password' && ( )} {!m.active && m.type === 'password' && ( )} {!m.active && m.type !== 'password' && ( )} ))} {showSetPassword && ( )} {showChangePassword && ( )} ) }