import { memo, type ReactNode, useMemo } from 'react';

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

import { type Goal } from 'src/pages/dashboard/goals/types';
import {
  type CompetencyGroup,
  type ReviewDetailFormQuestions,
  type ReviewDetailFormQuestionsGoalItem,
} from 'src/pages/dashboard/performance/types';

import CompetencyGroupCard from '../CompetencyGroup';
import GetReviewInputComponent from '../GetReviewInputComponent';

import GoalsSection from './GoalsSection';

export enum ReviewInputSectionType {
  FORM = 'FORM',
  GOAL = 'GOAL',
  COMPETENCY = 'COMPETENCY',
}

/** Tab labels (order in UI: FORM → GOAL → COMPETENCY) */
export const reviewSectionTitleTranslationKey: Record<
  ReviewInputSectionType,
  string
> = {
  [ReviewInputSectionType.FORM]: 'general:questions',
  [ReviewInputSectionType.GOAL]: 'general:goals',
  [ReviewInputSectionType.COMPETENCY]: 'competencies:competencies',
};

type GetReviewQuestionHeaderActions = (
  question: ReviewDetailFormQuestions,
) => ReactNode;

type ReviewInputSectionProps =
  | {
      canViewGoalDetails: boolean;
      reviewItems: ReviewDetailFormQuestionsGoalItem[];
      type: ReviewInputSectionType.GOAL;
      answered: boolean;
      getHeaderActions?: GetReviewQuestionHeaderActions;
    }
  | {
      reviewItems: ReviewDetailFormQuestions[];
      type: Exclude<ReviewInputSectionType, ReviewInputSectionType.GOAL>;
      answered: boolean;
      getHeaderActions?: GetReviewQuestionHeaderActions;
    };

const ReviewInputSection = (props: ReviewInputSectionProps) => {
  const { reviewItems, type, answered, getHeaderActions } = props;
  const isGoalSection = type === ReviewInputSectionType.GOAL;
  const canViewGoalDetails = isGoalSection ? props.canViewGoalDetails : false;

  const itemsToShowAsInput = useMemo(() => {
    return isGoalSection
      ? (reviewItems as ReviewDetailFormQuestionsGoalItem[]).filter(
          item => !item.isAutomatic,
        )
      : reviewItems;
  }, [isGoalSection, reviewItems]);

  const automaticGoals: Goal[] = useMemo(() => {
    if (!isGoalSection) return [];
    return (reviewItems as ReviewDetailFormQuestionsGoalItem[]).flatMap(item =>
      item.isAutomatic && !isNil(item.goal) ? [item.goal as Goal] : [],
    );
  }, [isGoalSection, reviewItems]);

  const competencyGroups = useMemo<CompetencyGroup[]>(() => {
    if (type !== ReviewInputSectionType.COMPETENCY) {
      return [];
    }

    const groups: CompetencyGroup[] = [];
    const groupIndexes = new Map<string, number>();

    (reviewItems as ReviewDetailFormQuestions[]).forEach(item => {
      const category = item.competency?.category ?? null;
      const categoryKey = category
        ? `category-${String(category.id)}`
        : 'uncategorized';
      const existingGroupIndex = groupIndexes.get(categoryKey);

      if (isNil(existingGroupIndex)) {
        groupIndexes.set(categoryKey, groups.length);
        groups.push({ category, items: [item] });
        return;
      }

      groups[existingGroupIndex].items.push(item);
    });

    return groups;
  }, [reviewItems, type]);

  const shouldGroupCompetencies =
    type === ReviewInputSectionType.COMPETENCY &&
    competencyGroups.some(group => !isNil(group.category));

  return (
    <Stack
      sx={{
        flexDirection: 'column',
        gap: 3,
        width: '100%',
        boxSizing: 'border-box',
      }}
    >
      {shouldGroupCompetencies
        ? competencyGroups.map((group, groupIndex) => (
            <CompetencyGroupCard
              key={group.category?.id ?? `uncategorized-${String(groupIndex)}`}
              group={group}
              answered={answered}
              canViewGoalDetails={canViewGoalDetails}
              getHeaderActions={getHeaderActions}
            />
          ))
        : itemsToShowAsInput.map((item, index) => (
            <GetReviewInputComponent
              canViewGoalDetails={canViewGoalDetails}
              key={`input${item.id}-index${index}`}
              answered={answered}
              index={index}
              {...item}
              description={item.description || undefined}
              choices={item.choices || undefined}
              headerActions={getHeaderActions?.(item)}
            />
          ))}
      {isGoalSection && automaticGoals.length > 0 && (
        <GoalsSection
          canViewGoalDetails={canViewGoalDetails}
          goals={automaticGoals}
        />
      )}
    </Stack>
  );
};

export default memo(ReviewInputSection);
