import { useEffect, useMemo, useState } from 'react';
import { FormProvider, useForm } from 'react-hook-form';
import { useQuery } from 'react-query';
import { useParams } from 'react-router-dom';

import { isNil } from 'lodash-es';
import Stack from '@material-hu/mui/Stack';

import HuTabs from '@material-hu/components/design-system/Tabs';

import { performanceKeys } from 'src/pages/dashboard/performance/queries';
import { getReviewDetail } from 'src/pages/dashboard/performance/services';
import {
  ReviewDirection,
  type ReviewUser,
} from 'src/pages/dashboard/performance/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import CalibrationComparisonDrawer from '../../CalibrationDetail/components/CalibrationComparisonDrawer';
import NoReviewText from '../../components/NoReviewText';
import PerformanceLoading from '../../components/PerformanceLoading';
import ReviewInputSection, {
  ReviewInputSectionType,
  reviewSectionTitleTranslationKey,
} from '../../components/ReviewInputSection';
import { useReviewCalibrationComparison } from '../../hooks/useReviewCalibrationComparison';
import { usePerformanceReview } from '../../PerformanceReviewContext';
import {
  buildReviewValues,
  getEffectiveReviewForm,
  splitReviewInputs,
} from '../../utils';

import ReviewHeaderCard from './ReviewHeaderCard';
import ReviewScoreCardByDirection from './score/ReviewScoreCardByDirection';

const ReviewDetailView = () => {
  const { id } = useParams();
  const { t } = useLokaliseTranslation(['performance', 'competencies']);
  const form = useForm();

  const cycleId = id || '';
  const { viewingReviewId } = usePerformanceReview();

  const { data: reviewData, isLoading } = useQuery(
    performanceKeys.review(cycleId, viewingReviewId),
    () => getReviewDetail(cycleId, viewingReviewId ?? 0),
    {
      enabled: !!viewingReviewId,
      select: response => response.data,
      onSuccess: response => {
        const effective = getEffectiveReviewForm(response);
        if (!effective?.questions?.length) return;
        form.reset(buildReviewValues(effective.questions));
      },
    },
  );

  const reviewed = reviewData?.reviewed;
  const reviewer = reviewData?.reviewer;
  const isAnswered = !!reviewData?.answered;
  const isSelfReview = reviewData?.type === ReviewDirection.AUTO_REVIEW;
  const reviewedFirstName = reviewed?.firstName;
  const canViewGoalDetails =
    reviewData?.loggedUserCanViewGoalsOfReviewed || false;
  const reviewInputs = getEffectiveReviewForm(reviewData)?.questions || [];

  const { formQuestions, goalQuestions, competencyQuestions } =
    splitReviewInputs(reviewInputs);

  const availableTabs = useMemo(() => {
    const tabs: ReviewInputSectionType[] = [];
    if (formQuestions.length > 0) tabs.push(ReviewInputSectionType.FORM);
    if (goalQuestions.length > 0) tabs.push(ReviewInputSectionType.GOAL);
    if (competencyQuestions.length > 0)
      tabs.push(ReviewInputSectionType.COMPETENCY);
    return tabs;
  }, [formQuestions.length, goalQuestions.length, competencyQuestions.length]);

  const [selectedTab, setSelectedTab] = useState<ReviewInputSectionType>(
    ReviewInputSectionType.FORM,
  );

  useEffect(() => {
    if (availableTabs.length === 0) return;
    if (!availableTabs.includes(selectedTab)) {
      setSelectedTab(availableTabs[0]);
    }
  }, [availableTabs, selectedTab]);

  const sectionTabsForHu = useMemo(
    () =>
      availableTabs.map(value => ({
        value,
        label: t(reviewSectionTitleTranslationKey[value]),
      })),
    [availableTabs, t],
  );

  const firstAvailableTab = availableTabs[0];
  const activeSectionType =
    availableTabs.length === 1 && !isNil(firstAvailableTab)
      ? firstAvailableTab
      : selectedTab;

  const {
    isActive: showCalibrationComparison,
    getHeaderActions,
    drawerProps: calibrationDrawerProps,
  } = useReviewCalibrationComparison(reviewData);

  const headerUser: ReviewUser | undefined = reviewer
    ? {
        ...reviewer,
        profilePicture:
          reviewer.profilePicture ?? reviewed?.profilePicture ?? null,
      }
    : reviewed;

  if (isLoading || isNil(reviewData)) {
    return <PerformanceLoading />;
  }

  return (
    <FormProvider {...form}>
      <Stack sx={{ gap: 3, width: '100%', boxSizing: 'border-box' }}>
        <ReviewHeaderCard
          user={headerUser}
          rightSlot={
            <ReviewScoreCardByDirection
              score={reviewData.score}
              scoreTag={reviewData.scoreTag}
            />
          }
        />

        {!isAnswered ? (
          <NoReviewText
            title={t(
              isSelfReview
                ? 'admin_check.empty_auto_review.title'
                : 'admin_check.empty_review.title',
            )}
            description={t(
              isSelfReview
                ? 'admin_check.empty_auto_review.description'
                : 'admin_check.empty_review.description',
              {
                user: reviewedFirstName,
              },
            )}
          />
        ) : (
          availableTabs.length > 0 && (
            <Stack sx={{ gap: 2, width: '100%' }}>
              {availableTabs.length > 1 && (
                <HuTabs
                  value={selectedTab}
                  tabs={sectionTabsForHu}
                  onTabChange={v => setSelectedTab(v as ReviewInputSectionType)}
                />
              )}
              {activeSectionType === ReviewInputSectionType.FORM &&
                formQuestions.length > 0 && (
                  <ReviewInputSection
                    reviewItems={formQuestions}
                    type={ReviewInputSectionType.FORM}
                    answered={isAnswered}
                    getHeaderActions={getHeaderActions}
                  />
                )}
              {activeSectionType === ReviewInputSectionType.GOAL &&
                goalQuestions.length > 0 && (
                  <ReviewInputSection
                    canViewGoalDetails={canViewGoalDetails}
                    reviewItems={goalQuestions}
                    type={ReviewInputSectionType.GOAL}
                    answered={isAnswered}
                    getHeaderActions={getHeaderActions}
                  />
                )}
              {activeSectionType === ReviewInputSectionType.COMPETENCY &&
                competencyQuestions.length > 0 && (
                  <ReviewInputSection
                    reviewItems={competencyQuestions}
                    type={ReviewInputSectionType.COMPETENCY}
                    answered={isAnswered}
                    getHeaderActions={getHeaderActions}
                  />
                )}
            </Stack>
          )
        )}
      </Stack>
      {showCalibrationComparison && (
        <CalibrationComparisonDrawer {...calibrationDrawerProps} />
      )}
    </FormProvider>
  );
};

export default ReviewDetailView;
