import { useMemo } from 'react';
import { FormProvider, useForm } from 'react-hook-form';

import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import HuAlert from '@material-hu/components/design-system/Alert';
import { useDialogLayer } from '@material-hu/components/layers/Dialogs';

import { ReviewCycleStatus } from 'src/pages/dashboard/performance/types';
import { splitReviewInputs } from 'src/pages/dashboard/performance/utils';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getFullName } from 'src/utils/userUtils';

import ReviewInputSection, {
  ReviewInputSectionType,
} from '../../../components/ReviewInputSection';
import RichText from '../../../components/RichText';

import ReviewedHeader from './components/ReviewedHeader';
import ReviewFormActions from './components/ReviewFormActions';
import ReviewSectionsNav from './components/ReviewSectionsNav';
import useExternalReview from './hooks/useExternalReview';
import useReviewSteps from './hooks/useReviewSteps';

/**
 * Renders the external reviewer flow for a single review:
 * header, step navigation, dynamic question sections, and finish confirmation.
 *
 * @example
 * <ExternalReviewForm reviewId={selectedReview.id} />
 */
type ExternalReviewFormProps = {
  /** Identifier of the review being answered. */
  reviewId: number;
};

const ExternalReviewForm = ({ reviewId }: ExternalReviewFormProps) => {
  const { t } = useLokaliseTranslation(['performance', 'competencies']);
  const { openDialog, closeDialog } = useDialogLayer();

  const form = useForm();
  const {
    handleSubmit,
    reset,
    formState: { isSubmitting, isValid },
  } = form;

  const { review, reviewLoading, submitReview, isSubmittingReview } =
    useExternalReview({ reviewId, onCompleted: reset });

  const reviewInputs = review?.form?.questions || [];
  const { formQuestions, goalQuestions, competencyQuestions } = useMemo(
    () => splitReviewInputs(reviewInputs),
    [reviewInputs],
  );

  const {
    availableTabs,
    sectionTabs,
    stepperSteps,
    currentStepIndex,
    activeSectionType,
    currentStepQuestions,
    isFirstStep,
    isLastStep,
    goNext,
    goBack,
    goToTab,
  } = useReviewSteps({ formQuestions, goalQuestions, competencyQuestions, t });

  const { reviewed, answered } = review || {};
  const canViewGoalDetails = review?.loggedUserCanViewGoalsOfReviewed || false;
  const description = review?.form?.description || null;
  const isOmitted = review?.status === ReviewCycleStatus.OMITTED;
  const reviewedFullName = getFullName(reviewed || {});
  const isReadOnly = !!answered || isOmitted;
  const canSubmit = isValid && !isSubmittingReview && !isSubmitting;

  const showFinishReviewDialog = () => {
    openDialog({
      title: t('form.finish_review_modal.review_title'),
      body: (
        <Typography variant="body1">
          {t('form.finish_review_modal.external_review_description')}
        </Typography>
      ),
      onClose: () => closeDialog(),
      primaryButtonProps: {
        children: t('form.finish_review_modal.confirm_button'),
        onClick: () => {
          closeDialog();
          handleSubmit(values => submitReview(values))();
        },
      },
      secondaryButtonProps: {
        children: t('general:CANCEL'),
        onClick: () => closeDialog(),
      },
      dialogProps: { fullWidth: true, maxWidth: 'sm' },
    });
  };

  if (reviewLoading) {
    return null;
  }

  return (
    <FormProvider {...form}>
      <Stack
        sx={{
          gap: 3,
          width: '100%',
          boxSizing: 'border-box',
        }}
      >
        <ReviewedHeader
          profilePicture={reviewed?.profilePicture}
          fullName={reviewedFullName}
        />
        {(isOmitted || answered) && (
          <HuAlert
            severity="warning"
            title={t(
              isOmitted
                ? 'form.cycle_finished_warning'
                : 'form.external_review.cycle_still_in_progress',
              { name: reviewedFullName },
            )}
            sx={{ width: '100%' }}
          />
        )}
        {description && (
          <RichText
            text={description}
            sx={{ mb: 0, color: 'text.secondary' }}
          />
        )}
        {availableTabs.length > 0 && (
          <Stack sx={{ gap: 2, width: '100%' }}>
            {availableTabs.length > 1 && (
              <ReviewSectionsNav
                isReadOnly={isReadOnly}
                activeSectionType={activeSectionType}
                sectionTabs={sectionTabs}
                stepperSteps={stepperSteps}
                currentStepIndex={currentStepIndex}
                onTabChange={goToTab}
              />
            )}
            {activeSectionType === ReviewInputSectionType.FORM &&
              formQuestions.length > 0 && (
                <ReviewInputSection
                  reviewItems={formQuestions}
                  type={ReviewInputSectionType.FORM}
                  answered={isReadOnly}
                />
              )}
            {activeSectionType === ReviewInputSectionType.GOAL &&
              goalQuestions.length > 0 && (
                <ReviewInputSection
                  canViewGoalDetails={canViewGoalDetails}
                  reviewItems={goalQuestions}
                  type={ReviewInputSectionType.GOAL}
                  answered={isReadOnly}
                />
              )}
            {activeSectionType === ReviewInputSectionType.COMPETENCY &&
              competencyQuestions.length > 0 && (
                <ReviewInputSection
                  reviewItems={competencyQuestions}
                  type={ReviewInputSectionType.COMPETENCY}
                  answered={isReadOnly}
                />
              )}
          </Stack>
        )}
        {!isReadOnly && (
          <ReviewFormActions
            currentStepQuestions={currentStepQuestions}
            isFirstStep={isFirstStep}
            isLastStep={isLastStep}
            canSubmit={canSubmit}
            reviewedFullName={reviewedFullName}
            onBack={goBack}
            onNext={goNext}
            onFinish={showFinishReviewDialog}
          />
        )}
      </Stack>
    </FormProvider>
  );
};

export default ExternalReviewForm;
