import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'

import Layout from '$theme-components/layout'
import Form from '$theme-components/personalInfo/Form'
import { t } from '$themelocalization'
import urlGenerator from '$ustoreinternal/services/urlGenerator'
import { UStoreProvider } from '@ustore/core'

import './PersonalInformation.scss'

const PersonalInformation = (props) => {
  const [fields, setFields] = useState([])
  const navigate = useNavigate()

  useEffect(() => {
    ;(async () => {
      const info = await UStoreProvider.api.personalInfo.getPersonalInfo()
      setFields(info.Fields?.toSorted((a, b) => a.DisplayOrder - b.DisplayOrder) ?? [])
    })()
  }, [])

  const handleCancel = () => {
    navigate(urlGenerator.get({ page: 'home' }))
  }

  return (
    <Layout {...props} className="personal-information-ng">
      <h2 className="title">{t('PersonalInformation.Title')}</h2>
      <p className="subtitle">{t('PersonalInformation.Subtitle')}</p>
      {fields.length > 0 && <Form fields={fields} onCancel={handleCancel} />}
    </Layout>
  )
}

export default PersonalInformation
