import { putUpdateProfile } from '@api/user'
import { errorTip, labelWithIcon } from '@components/Common'
import { useAuth } from '@hooks/useAuth'
import {
  Box,
  Button,
  Divider,
  Group,
  Paper,
  PasswordInput,
  Text,
  TextInput,
} from '@mantine/core'
import { useForm, yupResolver } from '@mantine/form'
import { notifications } from '@mantine/notifications'
import {
  IconCircleCheckFilled,
  IconKeyFilled,
  IconUserCircle,
  IconUserFilled,
} from '@tabler/icons-react'
import { Helpers } from '@utils/helper'
import { useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import * as yup from 'yup'

const vschema = (t) =>
  yup.object({
    name: yup
      .string()
      .required(t('message_is_required', { field: t('ui_display_name') })),
    password: yup.string().nullable().optional(),
    confirmPassword: yup.string().when('password', {
      is: (val) => !!(val && val.length > 0),
      then: (schema) =>
        schema.oneOf(
          [yup.ref('password'), null],
          t('message_password_mustmatch'),
        ),
    }),
  })

export default function Profile() {
  const { t } = useTranslation()
  const { auth, setUserInfo } = useAuth()
  const form = useForm({
    initialValues: {
      name: '',
      password: '',
      confirmPassword: '',
    },
    validate: yupResolver(vschema(t)),
    transformValues: (values) => ({
      name: values.name,
      password: values.password,
    }),
    enhanceGetInputProps: (payload) => ({
      error: errorTip(payload.inputProps.error),
    }),
  })

  const onSubmit = async (values) => {
    const resp = await putUpdateProfile(Helpers.clearObject(values))

    if (resp.status === 200) {
      setUserInfo(resp.data)
      form.reset()
    }

    notifications.show({
      color: 'green.5',
      icon: <IconCircleCheckFilled size={30} />,
      title: t('ui_success'),
      message: t('message_update_success'),
    })
  }

  useEffect(() => {
    if (auth.userInfo) {
      form.setFieldValue('name', auth?.userInfo?.name)
    }
  }, [auth.userInfo])

  return (
    <Box>
      <Divider
        label={
          <>
            <IconUserCircle size={20} color="black" />
            <Text ml="xs" c="black">
              {t('ui_profile')}
            </Text>
          </>
        }
        mb="md"
      />
      <Paper shadow="md" p="md" radius="lg">
        <Text mb="lg">{t('ui_change_info')}</Text>
        <form onSubmit={form.onSubmit(onSubmit)} autoComplete="off">
          <TextInput
            label={labelWithIcon(t('ui_display_name'), IconUserFilled)}
            placeholder={t('ui_display_name')}
            mb="md"
            {...form.getInputProps('name')}
          />
          <PasswordInput
            label={labelWithIcon(t('ui_new_password'), IconKeyFilled)}
            placeholder={t('ui_new_password')}
            mb="md"
            {...form.getInputProps('password')}
          />
          <PasswordInput
            label={labelWithIcon(t('ui_confirm_new_password'), IconKeyFilled)}
            placeholder={t('ui_confirm_new_password')}
            {...form.getInputProps('confirmPassword')}
          />
          <Group position="right" mt="md">
            <Button type="submit">{t('ui_save')}</Button>
          </Group>
        </form>
      </Paper>
    </Box>
  )
}
