import { useCallback, useEffect, useMemo, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';

import { useDrawerV2 } from '@material-hu/hooks/useDrawerV2';

import HuAlert from '@material-hu/components/design-system/Alert';
import useHuSnackbar from '@material-hu/components/design-system/Snackbar';

import { logEvent } from 'src/config/logging';
import { useAuth } from 'src/contexts/JWTContext';
import { documentsRoutes } from 'src/pages/dashboard/documents/routes';
import { pxRoutes } from 'src/pages/dashboard/PeopleExperience/routes';
import { EventName, Modules } from 'src/types/amplitude';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { useEmployeeLifecycleIds } from '../../../hooks/useEmployeeLifecycleIds';
import { useGetJourneyTask } from '../../../hooks/useGetJourneyTask';
import { useMarkTaskAsDone } from '../../../hooks/useMarkTaskAsDone';
import { useReopenJourneyTask } from '../../../hooks/useReopenJourneyTask';
import { useStartSurveyTask } from '../../../hooks/useStartSurveyTask';
import { employeeLifecycleRoutes } from '../../../routes';
import {
  type DocumentTaskDetail,
  type FormTaskDetail,
  JourneyTaskType,
  type SurveyTaskDetail,
} from '../../../types';
import { type UploadedDocument } from '../DocumentUploadSection';

import { Task } from './Task';

type TaskDetailProps = {
  isUserTasksModule?: boolean;
};

export const TaskDetail = ({ isUserTasksModule }: TaskDetailProps) => {
  const { t } = useLokaliseTranslation('employee_lifecycle');
  const params = useParams();
  const { user } = useAuth();
  const navigate = useNavigate();
  const { enqueueSnackbar } = useHuSnackbar();
  const { stepId, journeyId } = useEmployeeLifecycleIds();
  const taskId = params.taskId ? parseInt(params.taskId) : null;

  useEffect(() => {
    if (taskId) showDrawer({ taskId });
  }, [taskId]);

  const { task, isLoading: loadingTask } = useGetJourneyTask(taskId);

  // TODO: TECH-DEBT [SQGZ-892] — DOCUMENT task logic is mixed into this component alongside
  // CUSTOM and FORM. As new task types are added this file will keep growing.
  // Refactor: give each task type its own drawer component (e.g. DocumentTaskDrawer,
  // FormTaskDrawer) and turn TaskDetail into a thin dispatcher that opens the right one.
  // Migrate to useDrawerLayer when doing so. Reference: useActionDrawer pattern in Admin.
  const [uploadedDocuments, setUploadedDocuments] = useState<
    UploadedDocument[]
  >([]);
  const [showDocumentErrors, setShowDocumentErrors] = useState(false);

  const isTaskDone = Boolean(task && task?.status === 'DONE');
  const isFormTask = Boolean(task && task?.task?.type === JourneyTaskType.FORM);
  const isDocumentTask = Boolean(
    task && task?.task?.type === JourneyTaskType.DOCUMENT,
  );
  const isSurveyTask = Boolean(
    task && task?.task?.type === JourneyTaskType.SURVEY,
  );

  const documentTask = isDocumentTask ? (task as DocumentTaskDetail) : null;
  const surveyTask = isSurveyTask ? (task as SurveyTaskDetail) : null;
  const allDocumentsUploaded =
    isDocumentTask &&
    documentTask !== null &&
    uploadedDocuments.length === documentTask.task.documentNames.length;

  const handleDocumentFilesChange = useCallback(
    (files: UploadedDocument[]) => setUploadedDocuments(files),
    [],
  );

  const amplitudeEventData = useMemo(() => {
    if (!task) return;

    return {
      taskId: task.id,
      taskType: task.task.type,
      stepId: task.stepId,
      module: isUserTasksModule ? Modules.TASKS : Modules.ONBOARDING_2,
      onboardingId: task.userJourneyId,
      userId: user?.id,
    };
  }, [task, isUserTasksModule, user]);

  const markTaskAsDoneMutation = useMarkTaskAsDone(task, () => {
    enqueueSnackbar({
      title: t('custom_task_detail.completed_snackbar.title'),
      description: t('custom_task_detail.completed_snackbar.description'),
      variant: 'success',
    });
    logEvent(EventName.USER_TASK_COMPLETED, amplitudeEventData);
  });

  const startSurveyTaskMutation = useStartSurveyTask(task);

  const reopenTaskMutation = useReopenJourneyTask(task, () => {
    enqueueSnackbar({
      title: t('custom_task_detail.completed_snackbar.reopen_task'),
      description: t('custom_task_detail.completed_snackbar.description'),
      variant: 'success',
    });
    logEvent(EventName.USER_TASK_REOPEN, amplitudeEventData);
  });

  const handleGoBack = () => {
    const backRoute = isUserTasksModule
      ? employeeLifecycleRoutes.tasks.base()
      : employeeLifecycleRoutes.journeys.stepTasks(journeyId!, stepId!);

    navigate(backRoute);
  };

  const goToFormResults = (formTask: FormTaskDetail) => {
    const formAnswerId = Number(formTask.taskInfo.answerId);
    const formAnswerToken = formTask.taskInfo.token;
    const formTag = formTask.task.formTag;

    return navigate(
      employeeLifecycleRoutes.form.results(
        formTag,
        formAnswerId,
        formAnswerToken,
      ),
    );
  };

  const goToFormComplete = (formTask: FormTaskDetail) => {
    const formProgressionId = formTask.taskInfo.progressionId;
    const formTag = formTask.task.formTag;

    return navigate(
      employeeLifecycleRoutes.form.complete(
        formTag,
        formProgressionId,
        formTask.id,
      ),
    );
  };

  const reopenTask = (id: number) => reopenTaskMutation.mutate(id);

  const markTaskAsDone = (id: number) =>
    markTaskAsDoneMutation.mutate({ taskId: id });

  const goToDocumentFolder = () => {
    if (!documentTask) return;
    navigate(documentsRoutes.folders.detail(documentTask.task.targetFolderId));
  };

  const handleClickButton = (closeDrawer: () => void) => {
    if (!task) return;

    if (isSurveyTask && surveyTask) {
      const { participantAdded, completed } = surveyTask.taskInfo;
      const surveyUrl = pxRoutes.collaboratorSurvey(surveyTask.task.surveyId);
      // TODO: [SQGZ-956] Fetch canViewAnswers from GET /people-experience/work-environment-survey/survey/${surveyTask.task.surveyId} — field pending backend confirmation.
      const canViewAnswers = false;

      if (!participantAdded) {
        startSurveyTaskMutation.mutate(task.id, {
          onSuccess: () => {
            window.open(surveyUrl, '_blank');
          },
        });
      } else if (!completed) {
        window.open(surveyUrl, '_blank');
      } else if (canViewAnswers) {
        // TODO: [SQGZ-956] Open answers URL — pending backend confirmation.
      }
      return;
    }

    // All cases for a task
    if (isTaskDone && isFormTask) {
      return goToFormResults(task as FormTaskDetail);
    } else if (isTaskDone && isDocumentTask) {
      return goToDocumentFolder();
    } else if (isTaskDone && !isFormTask) {
      reopenTask(task.id);
    } else if (!isTaskDone && isFormTask) {
      return goToFormComplete(task as FormTaskDetail);
    } else if (!isTaskDone && isDocumentTask) {
      if (!allDocumentsUploaded) {
        setShowDocumentErrors(true);
        return;
      }
      markTaskAsDoneMutation.mutate(
        {
          taskId: task.id,
          data: {
            type: JourneyTaskType.DOCUMENT,
            documents: uploadedDocuments.map(d => ({
              fileAssetId: d.fileAssetId,
            })),
          },
        },
        {
          onSuccess: () => {
            closeDrawer();
            handleGoBack();
          },
        },
      );
      return;
    } else {
      markTaskAsDone(task.id);
    }

    // ---- Shared cleanup ----
    closeDrawer();
    handleGoBack();
  };

  const markAsDoneText = useMemo(() => {
    if (isSurveyTask && surveyTask) {
      const { participantAdded, completed } = surveyTask.taskInfo;
      if (!participantAdded) return t('survey_task_detail.start_survey');
      if (!completed) return t('survey_task_detail.resume_survey');
      return t('survey_task_detail.see_answers');
    }

    if (!isTaskDone) {
      if (isFormTask) return t('questionnaire_form_task.start_button');
      if (isDocumentTask) return t('document_task_detail.complete_task');
      return t('custom_task_detail.mark_as_completed');
    }

    if (isFormTask) return t('questionnaire_form_task.see_my_answers');
    if (isDocumentTask) return t('document_task_detail.see_in_my_documents');
    return t('custom_task_detail.reopen_task');
  }, [isSurveyTask, surveyTask, isTaskDone, isFormTask, isDocumentTask, t]);

  const isSurveyCompleted = Boolean(surveyTask?.taskInfo.completed);
  // TODO: [SQGZ-956] Replace with real canViewAnswers from PX endpoint once field is confirmed.
  const canViewAnswers = false;
  const isSurveyButtonDisabled =
    isSurveyTask && isSurveyCompleted && !canViewAnswers;

  const loadingMutations =
    loadingTask ||
    markTaskAsDoneMutation.isLoading ||
    reopenTaskMutation.isLoading ||
    startSurveyTaskMutation.isLoading;

  const { showDrawer, drawer } = useDrawerV2(({ closeDrawer }) => {
    return {
      title: task?.actionTitle,
      children: (
        <Task
          task={task}
          isLoading={loadingTask}
          onDocumentFilesChange={handleDocumentFilesChange}
          onViewDocuments={isDocumentTask ? goToDocumentFolder : undefined}
          showDocumentErrors={showDocumentErrors}
        />
      ),
      footer: isDocumentTask && !isTaskDone && (
        <HuAlert
          severity="warning"
          title={t('document_task_detail.cannot_modify_title')}
          description={t('document_task_detail.cannot_modify_warning')}
        />
      ),
      primaryButtonProps: isSurveyButtonDisabled
        ? undefined
        : {
            children: markAsDoneText,
            loading: loadingMutations,
            disabled: loadingMutations,
            variant: isTaskDone ? 'secondary' : 'primary',
            onClick: () => handleClickButton(closeDrawer),
            sx: { marginLeft: 'auto', px: 6 },
            // Drawer.Actions defaults to fullWidth buttons when size is SMALL
            // or MEDIUM. Override to keep the action button at its natural
            // width — looks better aligned to the right in both compact and
            // expanded (task focus) modes.
            fullWidth: false,
          },
      onClose: () => {
        closeDrawer();
        handleGoBack();
      },
      // Default to the compact size; users can opt into the full-screen focus
      // mode via the maximize button rendered in the header below.
      size: 'small',
      // Renders a maximize/minimize icon in the drawer header that toggles
      // between the current size and `taskFocus` (full screen). State is
      // managed internally by material-hu's Drawer.
      enableTaskFocus: true,
      slotProps: {
        layout: { sx: { maxWidth: 'none' } },
      },
      // Proper fix: migrate to `useDrawerLayer` + Drawer.Actions (SQGZ-892)
      PaperProps: {
        sx: {
          '& > .MuiStack-root > .MuiStack-root:last-child > .MuiStack-root': {
            maxWidth: 'none',
          },
        },
      },
    };
  });

  return <>{drawer}</>;
};
