import { putUpdateProfile } from '@api/user'
import TextInput from '@components/common/TextInput'
import { useSiteContext } from '@context/SiteContext'
import { createForm } from '@felte/solid'
import { validator } from '@felte/validator-yup'
import useLanguage from '@hooks/useLanguage'
import useToast from '@hooks/useToast'
import { IconKey, IconUser, IconUserCircle } from '@tabler/icons-solidjs'
import { Helpers } from '@utils/helper'
import * as yup from 'yup'

const profileSchema = (language, isRequired) =>
  yup.object({
    name: yup.string().required(isRequired(language.ui.displayName)),
    password: yup.string().nullable().optional(),
    'confirm-password': yup.string().when('password', {
      is: (val) => !!(val && val.length > 0),
      then: (schema) =>
        schema.oneOf(
          [yup.ref('password'), null],
          language.message['PASSWORD_MUSTMATCH'],
        ),
    }),
  })

export default function Profile() {
  const {
    store: { userInfo },
    setUser,
  } = useSiteContext()
  const { language, isRequired } = useLanguage()
  const notify = useToast()

  const { form, errors, reset } = createForm({
    extend: [validator({ schema: profileSchema(language, isRequired) })],
    onSubmit: async (values) => {
      try {
        const { name, password } = values
        const clearObj = Helpers.clearObject({
          name: name || null,
          password: password || null,
        })
        const resp = await putUpdateProfile(clearObj)

        if (resp.status === 200) {
          setUser(resp.data)
          reset()
          notify.success({
            title: 'Update profile success!',
            description: 'Your profile has been updated!',
          })
        }
      } catch (error) {
        notify.error({
          title: 'Update profile fail!',
          description: error?.data
            ? language.message[error.data]
            : 'Your username or password input is wrong!',
          closable: true,
        })
      }
    },
  })

  return (
    <div class="profile">
      <div class="flex items-center gap-2 mb-5 text-xl">
        <span class="text-secondary">
          <IconUserCircle size={30} />
        </span>
        {language.ui.profile}
      </div>
      <div class="card w-full bg-base-100 shadow-lg border border-gray-200">
        <div class="card-body">
          <form autoComplete="off" use:form>
            <p class="card-title">{language.ui.changeInfo}</p>
            <div class="form-content py-5">
              <TextInput
                icon={IconUser}
                name="name"
                label={language.ui.displayName}
                value={userInfo?.name}
                placeholder={language.ui.displayName}
                error={errors('name')}
              />
              <TextInput
                icon={IconKey}
                name="password"
                type="password"
                label={language.ui.newPassword}
                placeholder={language.ui.newPassword}
                error={errors('password')}
              />
              <TextInput
                icon={IconKey}
                name="confirm-password"
                type="password"
                label={language.ui.confirmNewPassword}
                placeholder={language.ui.confirmNewPassword}
                error={errors('confirm-password')}
              />
            </div>
            <div class="card-actions">
              <button type="submit" class="btn btn-primary">
                {language.ui.save}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  )
}
