import { useMemo, useState } from 'react';

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

import HuChips from '@material-hu/components/design-system/Chip';
import HuPills from '@material-hu/components/design-system/Pills';
import HuTitle from '@material-hu/components/design-system/Title';

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

import { usePerformanceReview } from '../PerformanceReviewContext';
import {
  getCyclesStatusLabelKey,
  getReviewDisplayStatus,
  getReviewStatusPillType,
  groupReviewsByDirection,
  type ReviewDirectionGroup,
} from '../utils';

import NoReviewText from './NoReviewText';
import UserListRow from './UserList/UserListRow';
import UserListSection from './UserList/UserListSection';

type ReviewFilter = 'all' | 'pending' | 'finished';

type ReviewWithStatus = ReviewDetail & {
  displayStatus: ReviewCycleStatus;
};

const FILTER_OPTIONS: { value: ReviewFilter; labelKey: string }[] = [
  { value: 'all', labelKey: 'general:all_female' },
  { value: 'pending', labelKey: 'performance:reviews.pending_reviews' },
  { value: 'finished', labelKey: 'performance:reviews.completed_reviews' },
];

const ReviewEvaluationsList = () => {
  const { t } = useLokaliseTranslation(['performance']);
  const { reviews, setSelectedReview } = usePerformanceReview();

  const [filter, setFilter] = useState<ReviewFilter>('all');

  const reviewsWithStatus = useMemo<ReviewWithStatus[]>(
    () =>
      reviews.map(review => ({
        ...review,
        displayStatus: getReviewDisplayStatus(review),
      })),
    [reviews],
  );

  const { hasPending, hasFinished } = useMemo(() => {
    let pending = false;
    let finished = false;

    reviewsWithStatus.forEach(review => {
      if (review.displayStatus === ReviewCycleStatus.FINISHED) {
        finished = true;
      } else {
        pending = true;
      }
    });

    return { hasPending: pending, hasFinished: finished };
  }, [reviewsWithStatus]);

  const shouldShowFilters = hasPending && hasFinished;
  const activeFilter: ReviewFilter = shouldShowFilters ? filter : 'all';

  const filteredReviews = useMemo<ReviewWithStatus[]>(() => {
    return reviewsWithStatus.filter(review => {
      if (activeFilter === 'all') return true;
      if (activeFilter === 'finished') {
        return review.displayStatus === ReviewCycleStatus.FINISHED;
      }
      return review.displayStatus !== ReviewCycleStatus.FINISHED;
    });
  }, [activeFilter, reviewsWithStatus]);

  const groups = useMemo<ReviewDirectionGroup<ReviewWithStatus>[]>(
    () => groupReviewsByDirection(filteredReviews),
    [filteredReviews],
  );

  if (groups.length === 0) {
    return (
      <NoReviewText
        title={t('admin_check.without_review.title')}
        description={t('admin_check.without_review.description')}
      />
    );
  }

  return (
    <Stack sx={{ gap: 3, width: '100%' }}>
      <Stack
        sx={{
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
          flexWrap: 'wrap',
          gap: 1,
        }}
      >
        <HuTitle
          variant="L"
          title={t('complete_reviews')}
        />
        {shouldShowFilters && (
          <Stack
            sx={{
              flexDirection: 'row',
              alignItems: 'center',
              flexWrap: 'wrap',
              gap: 1,
            }}
          >
            <Typography
              variant="body2"
              color="text.secondary"
            >
              {t('general:filter_by')}
            </Typography>
            {FILTER_OPTIONS.map(option => (
              <HuChips
                key={option.value}
                label={t(option.labelKey)}
                isSelected={activeFilter === option.value}
                onClick={() => setFilter(option.value)}
              />
            ))}
          </Stack>
        )}
      </Stack>
      {groups.map(group => (
        <UserListSection
          key={group.titleKey}
          title={group.titleKey ? t(group.titleKey) : undefined}
        >
          {group.reviews.map(review => (
            <UserListRow
              key={review.reviewId}
              user={{
                id: review.userId,
                profilePicture: review.profilePicture,
                firstName: review.firstName,
                lastName: review.lastName,
              }}
              primary={getFullName(review)}
              onClick={() => setSelectedReview(review.reviewId)}
            >
              <HuPills
                label={t(getCyclesStatusLabelKey(review.displayStatus))}
                size="small"
                type={getReviewStatusPillType(review.displayStatus)}
                hasIcon={false}
                sx={{
                  flexShrink: 0,
                  textTransform: 'none',
                }}
              />
            </UserListRow>
          ))}
        </UserListSection>
      ))}
    </Stack>
  );
};

export default ReviewEvaluationsList;
