import { Fragment, useEffect } from 'react';

import {
  IconAdjustmentsHorizontal,
  IconChevronRight,
  IconFileCheck,
  IconFileExport,
  IconFiles,
  IconProgressCheck,
} from '@material-hu/icons/tabler';
import CircularProgress from '@material-hu/mui/CircularProgress';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import HuSelectionCard from '@material-hu/components/composed-components/SelectionCard';

import useFeatureFlag from 'src/hooks/useFeatureFlag';
import {
  MenuItems,
  ReviewCycleStatus,
  type ReviewDetail,
  ReviewDirection,
  type ReviewTemplateWrapper,
} from 'src/pages/dashboard/performance/types';
import { FeatureFlags } from 'src/types/featureFlags';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { getReviewBoxMenuItems } from '../constants';
import { usePerformanceReview } from '../PerformanceReviewContext';

type ReviewsMenuProps = {
  isLoading: boolean;
  reviews: ReviewDetail[];
  reviewedFormReviews: ReviewDetail[];
  isResponsible: boolean;
  cycleStatus?: ReviewCycleStatus;
  isExternal?: boolean;
  canBeSharedBeforeCycleFinish?: boolean;
  formTemplates?: ReviewTemplateWrapper[];
};

const MENU_ICONS: Record<MenuItems, typeof IconProgressCheck> = {
  [MenuItems.TEAM_PROGRESS]: IconProgressCheck,
  [MenuItems.COMPLETE_REVIEW]: IconFiles,
  [MenuItems.CALIBRATION]: IconAdjustmentsHorizontal,
  [MenuItems.SHARE_RESULTS]: IconFileExport,
  [MenuItems.MY_RESULTS]: IconFileCheck,
};

const ReviewsMenu = (props: ReviewsMenuProps) => {
  const {
    reviews,
    reviewedFormReviews,
    isLoading,
    isResponsible,
    cycleStatus,
    isExternal,
    canBeSharedBeforeCycleFinish,
    formTemplates,
  } = props;

  const isCalibrationFFEnabled = useFeatureFlag(
    FeatureFlags.PERFORMANCE_REVIEW_CALIBRATION_ENABLED,
  );

  const showCalibration =
    !isExternal &&
    isCalibrationFFEnabled &&
    cycleStatus === ReviewCycleStatus.IN_PROGRESS &&
    (formTemplates?.some(template => template.withCalibration) ?? false);

  const { t } = useLokaliseTranslation(['performance']);
  const theme = useTheme();
  const palette = theme.palette as typeof theme.palette & {
    new?: {
      text?: { neutral?: { brand?: string } };
    };
  };
  const {
    selectedReview,
    setSelectedReview,
    menuSelected,
    setMenuSelected,
    setAllReviewsCompleted,
    setUserToShareId,
  } = usePerformanceReview();

  const handleChangeItem = (item: MenuItems) => {
    if (item === menuSelected && item === MenuItems.COMPLETE_REVIEW) {
      setSelectedReview(null);
      return;
    }
    if (item !== menuSelected) {
      setMenuSelected(item);
      if (item === MenuItems.MY_RESULTS) {
        const reviewId = reviewedFormReviews[0]?.id || null;
        setSelectedReview(reviewId);
      } else {
        setSelectedReview(null);
      }
      setUserToShareId(null);
      setAllReviewsCompleted(false);
    }
  };

  const selfReview = reviews.filter(
    review => review.type === ReviewDirection.AUTO_REVIEW,
  );

  const downwardReview = reviews.filter(
    review =>
      review.type === ReviewDirection.SUBORDINATE_REVIEW ||
      review.type === ReviewDirection.CALIBRATION_REVIEW,
  );

  const upwardReview = reviews.filter(
    review => review.type === ReviewDirection.BOSS_REVIEW,
  );

  const peerReview = reviews.filter(
    review => review.type === ReviewDirection.PEER_REVIEW,
  );

  const externalReview = reviews.filter(
    review => review.type === ReviewDirection.PEER_EXTERNAL_REVIEW,
  );

  const othersReview = reviews.filter(
    review => review.type === ReviewDirection.OTHERS_REVIEW,
  );

  useEffect(() => {
    if (
      !isLoading &&
      !(
        isResponsible ||
        selfReview.length > 0 ||
        peerReview.length > 0 ||
        upwardReview.length > 0 ||
        externalReview.length > 0 ||
        othersReview.length > 0
      ) &&
      selectedReview
    ) {
      setMenuSelected(MenuItems.MY_RESULTS);
    }
  }, [
    setMenuSelected,
    isLoading,
    isResponsible,
    selfReview,
    selectedReview,
    peerReview,
    upwardReview,
    externalReview,
    othersReview,
  ]);

  const showMyResults =
    !isExternal &&
    (cycleStatus === ReviewCycleStatus.FINISHED ||
      canBeSharedBeforeCycleFinish);

  const menuItems = getReviewBoxMenuItems(
    isResponsible,
    t,
    selfReview,
    downwardReview,
    upwardReview,
    peerReview,
    showMyResults,
    externalReview,
    othersReview,
    showCalibration,
  );

  const brandIconColor =
    palette.new?.text?.neutral?.brand ?? theme.palette.primary.main;

  return (
    <Stack
      sx={{
        alignItems: 'stretch',
        width: '100%',
        flexShrink: 0,
        gap: 2,
      }}
    >
      {isLoading && (
        <Stack
          alignItems="center"
          sx={{ py: 2 }}
        >
          <CircularProgress size={20} />
        </Stack>
      )}
      {!isLoading &&
        menuItems?.map(item => {
          const Icon = MENU_ICONS[item.id];
          const isSelected = menuSelected === item.id;
          return (
            <Fragment key={item.id}>
              <HuSelectionCard
                checked={isSelected}
                onClick={() => handleChangeItem(item.id)}
                fullWidth
                sx={{
                  borderRadius: 2,
                  '& .MuiCardContent-root': {
                    py: 2,
                    px: 2,
                  },
                }}
              >
                <Stack
                  sx={{
                    flexDirection: 'row',
                    alignItems: 'center',
                    gap: 1,
                    width: '100%',
                    minWidth: 0,
                  }}
                >
                  <Stack
                    sx={{
                      alignItems: 'center',
                      justifyContent: 'center',
                      borderRadius: '50%',
                      height: 40,
                      width: 40,
                      flexShrink: 0,
                      backgroundColor: 'new.background.layout.brand',
                      color: brandIconColor,
                    }}
                  >
                    <Icon
                      size={24}
                      color="currentColor"
                      aria-hidden
                    />
                  </Stack>
                  <Typography
                    variant="body1"
                    fontWeight="fontWeightSemiBold"
                    color="text.primary"
                    sx={{
                      flex: 1,
                      minWidth: 0,
                    }}
                    noWrap
                  >
                    {item.title}
                  </Typography>
                  <IconChevronRight
                    size={20}
                    aria-hidden
                    style={{ flexShrink: 0, opacity: 0.6 }}
                  />
                </Stack>
              </HuSelectionCard>
            </Fragment>
          );
        })}
    </Stack>
  );
};

export default ReviewsMenu;
