import React, { useState, useEffect, Suspense, lazy } from 'react';
import { Tabs } from '@/components/ui';
import { AdaptableCard, Container } from '@/components/shared';
import { useNavigate, useLocation } from 'react-router-dom';
import { t } from 'i18next';
import { isEmpty } from 'lodash';
import { apiGetAccountSettingData } from '@/services/AccountServices';

const Profile = lazy(() => import('./components/Profile'));
const Password = lazy(() => import('./components/Password'));

const { TabNav, TabList } = Tabs;

const settingsMenu = {
  profile: { label: t('General info'), path: 'profile' },
  password: { label: t('Password'), path: 'password' },
};

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

  const onTabChange = (val) => {
    setCurrentTab(val);
    navigate(`/account/settings/${val}`);
  };
 
  const fetchData = async () => {
    const response = await apiGetAccountSettingData();
    setData(response.data);
  };

  useEffect(() => {
    setCurrentTab(path);
     if (isEmpty(data)) {
      fetchData();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <Container>
      <AdaptableCard>
        <Tabs value={currentTab} onChange={(val) => onTabChange(val)}>
          <TabList>
            {Object.keys(settingsMenu).map((key) => (
              <TabNav key={key} value={key}>
                {t(settingsMenu[key].label)}
              </TabNav>
            ))}
          </TabList>
        </Tabs>
        <div className="px-4 py-6">
          <Suspense fallback={<></>}>
            {currentTab === 'profile' && <Profile data={data?.result} />}
            {currentTab === 'password' && <Password data={data?.result} />}
          </Suspense>
        </div>
      </AdaptableCard>
    </Container>
  );
};

export default Settings;
