import { Button, Card, notifier, SimpleGrid, TextInput } from '@tidbcloud/uikit'
import { Form, FormPhoneInput, FormTextInput } from '@tidbcloud/uikit/biz'
import DOMPurify from 'dompurify'
import { observer } from 'mobx-react'
import { useEffect } from 'react'
import { useForm } from 'react-hook-form'

import { useUpdateUserProfile } from 'dbaas/services'
import { getErrorMessage } from 'dbaas/services/errorCodes'
import useStores from 'dbaas/stores/useStores'
import { userProfileTracking } from 'dbaas/utils/tracking'
import { firstNameRules, lastNameRules } from 'dbaas/utils/validationRules'

import { BlockHeader } from '../components'

type ProfileFormModel = {
  firstName: string
  lastName: string
  phoneNumber?: string
}

export const Profile = observer(() => {
  const {
    store: {
      lastVisitLocation: { orgId },
      userProfile: { user_id: userId, first_name: firstName, last_name: lastName, email, phone_number: phoneNumber }
    },
    actions: { updateLocalUserProfile }
  } = useStores()

  const form = useForm<ProfileFormModel>({
    mode: 'onChange',
    defaultValues: {
      firstName,
      lastName,
      phoneNumber
    }
  })
  const {
    setValue,
    formState: { isDirty }
  } = form
  const updator = useUpdateUserProfile({
    mutation: {
      onSuccess: (_data, args) => {
        const { org_id, ...profile } = args.data

        updateLocalUserProfile(profile)
        // Update user's info on mixpanel
        userProfileTracking({ first_name: profile.first_name, last_name: profile.last_name })
        notifier.success('Your profile has been successfully updated.')
      },
      onError: (error) => {
        const message = getErrorMessage(error, true)

        notifier.error(<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(message) }} />)
      }
    }
  })
  const onSubmit = (data: ProfileFormModel) => {
    const firstName = data.firstName.trim()
    const lastName = data.lastName.trim()
    const phoneNumber = data.phoneNumber?.trim()

    return updator.mutateAsync({
      orgId,
      data: {
        org_id: orgId,
        first_name: firstName,
        last_name: lastName,
        phone_number: phoneNumber
      }
    })
  }

  useEffect(() => {
    if (userId) {
      setValue('firstName', firstName)
      setValue('lastName', lastName)
      setValue('phoneNumber', phoneNumber)
    }
  }, [userId])

  return (
    <Card p="xl">
      <Form form={form} onSubmit={onSubmit} layout="none" withActions={false}>
        <BlockHeader
          title="Account Profile"
          description="You can change your first name, last name and phone number."
          rightSection={
            <Button
              variant="default"
              type="submit"
              loading={updator.isLoading}
              disabled={!isDirty}
              size="sm"
              data-mp-event="Profile Save Button Clicked"
            >
              Update
            </Button>
          }
          mb="xl"
        />
        <SimpleGrid cols={{ base: 4, sm: 1, md: 2 }} spacing="xl">
          <TextInput label="Email" value={userId ? email : 'Loading...'} disabled />
          <FormTextInput
            data-testid="first-name"
            name="firstName"
            label="First Name"
            placeholder={userId ? '' : 'Loading...'}
            required
            rules={{
              required: 'Required',
              ...firstNameRules
            }}
          />
          <FormTextInput
            data-testid="last-name"
            name="lastName"
            label="Last Name"
            placeholder={userId ? '' : 'Loading...'}
            required
            rules={{
              required: 'Required',
              ...lastNameRules
            }}
          />
          <FormPhoneInput
            name="phoneNumber"
            label="Phone Number"
            placeholder={userId ? '' : 'Loading...'}
            showContryCodeAfterFocus
          />
        </SimpleGrid>
      </Form>
    </Card>
  )
})
