import AdaptableCard from '@/components/shared/AdaptableCard'
import Container from '@/components/shared/Container'
import Tabs from '@/components/ui/Tabs'
import { APP_NAME } from '@/constants/app.constant'
import { useLocalization } from '@/utils/hooks/useLocalization'
import { Suspense, lazy, useState } from 'react'
import { Helmet } from 'react-helmet'
import { useLocation, useNavigate } from 'react-router-dom'

type AccountSetting = {
  profile: {
    firstName?: string
    lastName?: string
    avatar?: string
    lang?: string
  }
  loginHistory: {
    type: string
    deviceName: string
    time: number
    location: string
  }[]
}

const General = lazy(() => import('./components/General'))
const Password = lazy(() => import('./components/Password'))
const NotificationSettings = lazy(() => import('./components/NotificationSettings'))

const { TabNav, TabList } = Tabs

const Profile = () => {
  const { translate } = useLocalization()
  const settingsMenu: Record<
    string,
    {
      label: string
      path: string
    }
  > = {
    general: {
      label: translate('::Abp.Identity.Profile.General'),
      path: 'general',
    },
    password: {
      label: translate('::Abp.Identity.Password'),
      path: 'password',
    },
    notificationSettings: {
      label: translate('::Abp.Identity.NotificationSettings'),
      path: 'notification-settings',
    },
  }

  const location = useLocation()
  const path = location.pathname.substring(location.pathname.lastIndexOf('/') + 1)
  const [currentTab, setCurrentTab] = useState(path)
  const [data, setData] = useState<Partial<AccountSetting>>({})
  const navigate = useNavigate()

  const PROFILE_BASE_PATH = '/admin/profile'

  const onTabChange = (val: string) => {
    if (settingsMenu[val]) {
      setCurrentTab(settingsMenu[val].path)
      navigate(`${PROFILE_BASE_PATH}/${settingsMenu[val].path}`)
    }
  }

  return (
    <Container>
      <Helmet
        titleTemplate={`%s | ${APP_NAME}`}
        title={translate('::' + 'Abp.Identity.Profile')}
        defaultTitle={APP_NAME}
      ></Helmet>
      <AdaptableCard>
        <Tabs value={currentTab} onChange={(val) => onTabChange(val)}>
          <TabList>
            {Object.keys(settingsMenu).map((key) => (
              <TabNav key={key} value={key}>
                {settingsMenu[key].label}
              </TabNav>
            ))}
          </TabList>
        </Tabs>
        <div className="px-4 py-6">
          <Suspense fallback={<></>}>
            {currentTab === 'general' && <General />}
            {currentTab === 'password' && <Password data={data.loginHistory} />}
            {currentTab === 'notification-settings' && <NotificationSettings />}
          </Suspense>
        </div>
      </AdaptableCard>
    </Container>
  )
}

export default Profile
