import { useEffect } from 'react';

import Clickable from '~/src/components/Clickable';
import Page from '~/src/components/Page';
import PageMetadata from '~/src/components/PageMetadata';
import Text from '~/src/components/Text';
import useIsEnabled from '~/src/hooks/useIsEnabled';
import useTheme from '~/src/hooks/useTheme';
import { useI18n } from '~/src/lib/i18n';
import { useAppRouter } from '~/src/lib/router2';
import { MappedUser } from '~/src/lib/songwhipApi/users/types';
import { Features } from '~/src/store/session/types';
import { Tab, Tabs } from '~/src/ui/components/tabs';
import { DashboardContentLinks } from './contentLinks/DashboardContentLinks';
import DashboardPages from './DashboardPages';

export const DashboardPage = ({ user }: { user: MappedUser }) => {
  const theme = useTheme();
  const { t } = useI18n('dashboard');

  const isContentLinksEnabled = useIsEnabled(Features.CONTENT_LINKS);

  const router = useAppRouter();
  const query = router.getQuery();
  const initialTabId = query.tab as string | undefined;

  const handleTabChange = async (tabId) => {
    const persistedQuery = router.getPersistedQuery('/dashboard', tabId);

    await router.setQuery(
      { tab: tabId, ...persistedQuery },
      { type: 'replace', reset: true }
    );
  };

  useEffect(() => {
    router.setPersistedQuery(query);
  }, [router, query]);

  return (
    <Page
      withGradient
      testId="dashboardPage"
      withMenuButton
      renderHeaderContent={() => (
        <Text size="1.5rem" isBold color={theme.textColor40}>
          Dashboard
        </Text>
      )}
      renderHeaderRight={() => (
        <Clickable
          fullHeight
          centerContent
          padding="0 .5rem"
          href="/create"
          testId="createPageButton"
        >
          <Text size="1.5rem" color={theme.textColor90} isBold>
            {t('createPage')}
          </Text>
        </Clickable>
      )}
      contentStyle={{
        paddingTop: '6rem',
      }}
    >
      {isContentLinksEnabled ? (
        <Tabs
          testId="dashboardTabs"
          defaultTabId={initialTabId}
          onTabChange={handleTabChange}
        >
          <Tab id="pages" label={t('labels.pages')}>
            <DashboardPages />
          </Tab>
          <Tab id="contentLinks" label={t('labels.contentLinks')}>
            <DashboardContentLinks user={user} />
          </Tab>
        </Tabs>
      ) : (
        <DashboardPages />
      )}

      <PageMetadata title="Dashboard" />
    </Page>
  );
};
