import { useEffect } from 'react'
import Alert from '@mui/material/Alert'
import Box from '@mui/material/Box'
import Button from '@mui/material/Button'
import Stack from '@mui/material/Stack'
import TextField from '@mui/material/TextField'
import Typography from '@mui/material/Typography'
import { useUnit } from 'effector-react'
import { useForm } from 'react-hook-form'
import { getApiErrorMessage } from '@/shared/lib/get-api-error-message'
import { $user, $updateProfileError, updateProfileFx } from '@/shared/model/auth'

export function ProfileSection() {
  const user = useUnit($user)
  const pendingProfile = useUnit(updateProfileFx.pending)
  const updateProfileError = useUnit($updateProfileError)

  const profileErrorMsg = getApiErrorMessage(updateProfileError)

  const profileForm = useForm<{ displayName: string }>({
    defaultValues: { displayName: user?.displayName ? String(user.displayName) : '' },
    mode: 'onChange',
  })

  useEffect(() => {
    profileForm.reset({ displayName: user?.displayName ? String(user.displayName) : '' })
  }, [user?.displayName, profileForm])

  return (
    <Box>
      <Typography variant="h6" gutterBottom>
        Профиль
      </Typography>
      <Stack spacing={2}>
        <TextField
          label="Имя или ник"
          helperText="До 40 символов"
          slotProps={{ htmlInput: { maxLength: 40 } }}
          {...profileForm.register('displayName')}
        />
        {profileErrorMsg && (
          <Alert severity="error" sx={{ mt: 1 }}>
            {profileErrorMsg}
          </Alert>
        )}
        <Button
          variant="contained"
          disabled={pendingProfile}
          onClick={() => {
            const raw = profileForm.getValues('displayName')
            const name = raw.trim()
            updateProfileFx({ displayName: name.length ? name : null })
          }}
        >
          Сохранить
        </Button>
      </Stack>
    </Box>
  )
}
