import React, {ReactNode, useCallback, useEffect, useMemo, useRef} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {useNavigation} from '@react-navigation/native';
import {RenderSceneProps, Spinner, Tabs, TabsRef} from '@components';
import {FeatureFlags} from '@interfaces/featureFlags';
import ServiceManagementTaskHeader from '@modules/serviceManagement/components/ServiceManagementTaskHeader';
import {
  AmplitudeServiceManagementRole,
  ServiceManagementTask,
  ServiceManagementTaskType,
  ServiceManagementTaskSubtask,
} from '@modules/serviceManagement/interfaces';
import {TaskDetailsTabKeys} from '@modules/serviceManagement/navigation/interfaces';
import ServiceManagementTaskDetailsTab from '@modules/serviceManagement/components/ServiceManagementTaskDetailsTab';
import ServiceManagementTaskCommentsTab from '@modules/serviceManagement/components/ServiceManagementTaskCommentsTab';
import ServiceManagementTaskApprovalsTab from '@modules/serviceManagement/components/ServiceManagementTaskApprovalsTab';
import {useGetShouldShowSubtasksForTask} from '@modules/serviceManagement/hooks/useGetShouldShowSubtasksForTask';
import {useGetShouldShowApprovalsForTask} from '@modules/serviceManagement/hooks/useGetShouldShowApprovalsForTask';
import {logAmplitudeEvent} from '@shared/utils';
import {AMPLITUDE_EVENTS, Screens} from '@shared/constants';
import {commonStyles} from '@shared/styles';
import {useTheme} from '@shared/theme';
import {useFeatureFlag} from '@stores/featureFlags';

import {styles} from './styles';
import ServiceManagementTaskActivityList from '../ServiceManagementTaskActivityList';
import {ServiceManagementTaskOptionsDialog} from '../ServiceManagementTaskOptionsDialog';
import {ServiceManagementTaskSubtasksTab} from '../ServiceManagementTaskSubtasksTab';

interface Props {
  task?: ServiceManagementTask;
  isLoading: boolean;
  showInitiator?: boolean;
  footer?: ReactNode;
  firstTabKey?: TaskDetailsTabKeys;
  isAgent?: boolean;
  headerButton: ReactNode;
}

function ServiceManagementTaskDetailsLayout({
  task,
  isLoading,
  showInitiator,
  footer,
  firstTabKey = Screens.SERVICE_MANAGEMENT_TASKS_DETAILS_TAB,
  isAgent = false,
  headerButton,
}: Props) {
  const {t} = useTranslation();
  const navigation = useNavigation();
  const tabRef = useRef<TabsRef>(null);
  const didJumpRef = useRef(false);
  const {theme} = useTheme();
  const isDownloadCertificateEnabled =
    useFeatureFlag(FeatureFlags.DOWNLOAD_CERTIFICATE_ENABLED) ?? true;
  const {
    shouldShowApprovals,
    isLoadingShouldShowApprovals,
    isSuccessShouldShowApprovals,
  } = useGetShouldShowApprovalsForTask(task?.id);
  const {
    shouldShowSubtasks,
    isLoadingShouldShowSubtasks,
    isSuccessShouldShowSubtasks,
  } = useGetShouldShowSubtasksForTask(task?.id);
  const isLoadingTabs =
    isLoadingShouldShowApprovals || isLoadingShouldShowSubtasks;

  useEffect(() => {
    logAmplitudeEvent(AMPLITUDE_EVENTS.SERVICE_MGMT_REQUEST_DETAIL_VIEWED, {
      role: isAgent
        ? AmplitudeServiceManagementRole.AGENT
        : AmplitudeServiceManagementRole.INITIATOR,
      serviceId: task?.catalogItem?.id,
      serviceName: task?.catalogItem?.name,
      requestId: task?.id,
    });
  }, [isAgent, task?.catalogItem?.id, task?.catalogItem?.name, task?.id]);

  useEffect(() => {
    navigation.setOptions({
      headerTitle:
        task?.type === ServiceManagementTaskType.Approval
          ? task?.parentTask.catalogItem.name
          : task?.catalogItem.name,
    });
  }, [navigation, task]);

  const routes = useMemo(
    () => [
      {
        key: Screens.SERVICE_MANAGEMENT_TASKS_DETAILS_TAB,
        label: t('service_management.details'),
      },
      {
        key: Screens.SERVICE_MANAGEMENT_TASKS_COMMENTS_TAB,
        label: t('service_management.comments'),
      },
      ...(isAgent
        ? []
        : [
            {
              key: Screens.SERVICE_MANAGEMENT_TASKS_ACTIVITY_TAB,
              label: t('service_management.activity'),
            },
          ]),
      ...(!isLoadingTabs && isAgent && shouldShowSubtasks
        ? [
            {
              key: Screens.SERVICE_MANAGEMENT_SUBTASKS_TAB,
              label: t('service_management.subtasks.title'),
            },
          ]
        : []),
      ...(!isLoadingTabs && isAgent && shouldShowApprovals
        ? [
            {
              key: Screens.SERVICE_MANAGEMENT_APPROVALS_TAB,
              label: t('service_management.approvals.title'),
            },
          ]
        : []),
    ],
    [t, isAgent, isLoadingTabs, shouldShowSubtasks, shouldShowApprovals],
  );

  // If the firstTabKey is not found, set the initial index to 0
  const initialIndex = Math.max(
    routes.findIndex(route => route.key === firstTabKey),
    0,
  );

  useEffect(() => {
    if (didJumpRef.current) {
      return;
    }

    if (
      isSuccessShouldShowApprovals &&
      isSuccessShouldShowSubtasks &&
      firstTabKey !== Screens.SERVICE_MANAGEMENT_TASKS_DETAILS_TAB
    ) {
      const firstTabIndex = routes.findIndex(
        route => route.key === firstTabKey,
      );

      if (firstTabIndex === -1) {
        return;
      }

      tabRef.current?.goToIndex(firstTabIndex);
      didJumpRef.current = true;
    }
  }, [
    firstTabKey,
    isSuccessShouldShowApprovals,
    isSuccessShouldShowSubtasks,
    routes,
  ]);

  const renderScene = useCallback(
    ({route, isActive = false}: RenderSceneProps) => {
      if (!task) {
        return null;
      }

      switch (route.key) {
        case Screens.SERVICE_MANAGEMENT_TASKS_DETAILS_TAB:
          return (
            <ServiceManagementTaskDetailsTab
              task={task}
              footer={footer}
              showInitiator={showInitiator}
              isAgent={isAgent}
              showActivityTabOpen={
                isAgent &&
                firstTabKey === Screens.SERVICE_MANAGEMENT_TASKS_ACTIVITY_TAB
              }
              isActive={isActive}
            />
          );
        case Screens.SERVICE_MANAGEMENT_TASKS_COMMENTS_TAB:
          return (
            <ServiceManagementTaskCommentsTab
              task={task}
              isAgent={isAgent}
              isActive={isActive}
            />
          );
        case Screens.SERVICE_MANAGEMENT_TASKS_ACTIVITY_TAB:
          return (
            <ServiceManagementTaskActivityList
              task={task}
              footer={footer}
              backgroundColor={theme.background.layout.default}
              isAgent={isAgent}
            />
          );
        case Screens.SERVICE_MANAGEMENT_APPROVALS_TAB:
          return <ServiceManagementTaskApprovalsTab task={task} />;
        case Screens.SERVICE_MANAGEMENT_SUBTASKS_TAB:
          return (
            <ServiceManagementTaskSubtasksTab
              task={task as ServiceManagementTaskSubtask}
              isActive={isActive}
            />
          );
        default:
          return null;
      }
    },
    [
      firstTabKey,
      footer,
      isAgent,
      showInitiator,
      task,
      theme.background.layout.default,
    ],
  );

  return (
    <View
      style={[
        commonStyles.flex,
        {
          backgroundColor: theme.background.elements.default,
        },
      ]}>
      {isLoading || !task ? (
        <View style={styles.spinnerContainer}>
          <Spinner />
        </View>
      ) : (
        <>
          {isDownloadCertificateEnabled && (
            <ServiceManagementTaskOptionsDialog task={task} isAgent={isAgent} />
          )}
          <ServiceManagementTaskHeader
            task={task}
            headerButton={headerButton}
          />
          <View style={commonStyles.flex}>
            <Tabs
              ref={tabRef}
              routes={routes}
              renderScene={renderScene}
              initialIndex={initialIndex}
              fullWidth
            />
          </View>
        </>
      )}
    </View>
  );
}

export default ServiceManagementTaskDetailsLayout;
