import React, {useCallback, useMemo} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {useNavigation} from '@react-navigation/native';
import {RenderSceneProps, Tabs} from '@components';
import {
  AmplitudeServiceManagementSource,
  ServiceManagementTaskApproval,
} from '@modules/serviceManagement/interfaces';
import {useAppSelector} from '@redux/utils';
import {Screens} from '@shared/constants';
import {useTheme} from '@shared/theme';
import {commonStyles} from '@shared/styles';

import {PendingApprovalsTab} from './components/PendingApprovalsTab';
import {HistoryApprovalsTab} from './components/HistoryApprovalsTab';

export function ServiceManagementApprovalsLayout({
  source,
}: {
  source: AmplitudeServiceManagementSource;
}) {
  const navigation = useNavigation();
  const {theme} = useTheme();
  const {t} = useTranslation();
  const isAgent = useAppSelector(({user}) => user.isAgent);
  const isAgentSource =
    source === AmplitudeServiceManagementSource.ApprovalsListAgentWorkspace;
  const onPressItem = useCallback(
    (item: ServiceManagementTaskApproval) => () => {
      if (isAgent) {
        navigation.navigate(Screens.AGENT_WORKSPACE_TASKS_DETAILS, {
          id: item.parentTask.id,
          fistTabKey: Screens.SERVICE_MANAGEMENT_APPROVALS_TAB,
        });
      } else {
        navigation.navigate(Screens.SERVICE_PORTAL_TASKS_DETAILS, {
          id: item.id,
          fistTabKey: Screens.SERVICE_MANAGEMENT_TASKS_COMMENTS_TAB,
        });
      }
    },
    [isAgent, navigation],
  );

  const routes = useMemo(
    () => [
      {
        key: Screens.SERVICE_PORTAL_APPROVALS_PENDING_TAB,
        label: t('service_management.approvals.pending'),
      },
      {
        key: Screens.SERVICE_PORTAL_APPROVALS_HISTORY_TAB,
        label: t('service_management.approvals.history'),
      },
    ],
    [t],
  );

  const renderScene = useCallback(
    ({route}: RenderSceneProps) => {
      switch (route.key) {
        case Screens.SERVICE_PORTAL_APPROVALS_PENDING_TAB:
          return (
            <PendingApprovalsTab
              onPressItem={onPressItem}
              source={source}
              isAgent={isAgentSource}
            />
          );
        case Screens.SERVICE_PORTAL_APPROVALS_HISTORY_TAB:
          return (
            <HistoryApprovalsTab
              onPressItem={onPressItem}
              isAgent={isAgentSource}
            />
          );
        default:
          return null;
      }
    },
    [onPressItem, source, isAgentSource],
  );

  return (
    <View
      style={[
        commonStyles.flex,
        {backgroundColor: theme.background.elements.default},
      ]}>
      <Tabs routes={routes} renderScene={renderScene} fullWidth />
    </View>
  );
}
