import { type Goal } from 'src/pages/dashboard/goals/types';
import { type Competency } from 'src/types/competencies';
import { type User } from 'src/types/user';

export enum ReviewRole {
  REVIEWED = 'REVIEWED',
  REVIEWER = 'REVIEWER',
}

export enum MenuItems {
  TEAM_PROGRESS = 'TEAM_PROGRESS',
  COMPLETE_REVIEW = 'COMPLETE_REVIEW',
  CALIBRATION = 'CALIBRATION',
  MY_RESULTS = 'MY_RESULTS',
  SHARE_RESULTS = 'SHARE_RESULTS',
}

export enum ReviewQuestionType {
  TEXT = 'TEXT',
  CHECKBOX = 'CHECKBOX',
  MULTIPLE_CHOICE = 'MULTIPLE_CHOICE',
  RATING = 'RATING',
}

export enum ReviewCommentableStatus {
  NONE = 'NONE',
  OPTIONAL = 'OPTIONAL',
  REQUIRED = 'REQUIRED',
}

export const COMMENT = '_comment';

export enum DeliveryStatus {
  SHARE_DISABLED = 'SHARE_DISABLED',
  NOT_SHARED = 'NOT_SHARED',
  SHARED_UNCONFIRMED = 'SHARED_UNCONFIRMED',
  SHARED_CONFIRMED = 'SHARED_CONFIRMED',
}

export enum ReviewCycleStatus {
  FINISHED = 'FINISHED',
  IN_PROGRESS = 'IN_PROGRESS',
  PENDING = 'PENDING',
  OMITTED = 'OMITTED',
  EDIT_REQUESTED = 'EDIT_REQUESTED',
  EDIT_PENDING = 'EDIT_PENDING',
  SELECTION = 'SELECTION',
}

export enum ReviewDirection {
  AUTO_REVIEW = 'AUTO_REVIEW',
  BOSS_REVIEW = 'BOSS_REVIEW',
  PEER_REVIEW = 'PEER_REVIEW',
  SUBORDINATE_REVIEW = 'SUBORDINATE_REVIEW',
  PEER_EXTERNAL_REVIEW = 'PEER_EXTERNAL_REVIEW',
  OTHERS_REVIEW = 'OTHERS_REVIEW',
  CALIBRATION_REVIEW = 'CALIBRATION_REVIEW',
}

enum ReviewCycleUsersMode {
  ALL_USERS = 'ALL_USERS',
  TARGETED_USERS = 'TARGETED_USERS',
}

export type PerformanceReview = {
  id: number;
  isResponsible: boolean;
  name: string;
  needsChanges: boolean;
  reviewedUsersMode: ReviewCycleUsersMode;
  status: ReviewCycleStatus;
  reviewedFormReviews: ReviewDetail[];
  reviewerFormReviews: ReviewDetail[];
  withSummary: boolean;
  userTargetUser: Pick<
    ReviewUserToShare,
    | 'cycleId'
    | 'id'
    | 'responsible'
    | 'responsibleId'
    | 'shareStatus'
    | 'user'
    | 'userId'
    | 'score'
    | 'scoreTag'
  > & {
    summary: string;
  };
  reviewsVisibleAfterFinishedReviewCycle: boolean;
};

export enum PendingActionFilter {
  PENDING_SELECTION = 'PENDING_SELECTION',
  PENDING_EVALUATION = 'PENDING_EVALUATION',
  PENDING_DELIVERY = 'PENDING_DELIVERY',
}

export type StatusBreakdown = {
  finished: number;
  inProgress: number;
  pending: number;
};

export type LeaderDashboardFilter = {
  q?: string;
  pendingActionFilter?: PendingActionFilter;
  teamScore?: number;
  sortBy?: 'NAME';
  sortDirection?: 'ASC' | 'DESC';
};

export type ReviewUser = Pick<
  User,
  'profilePicture' | 'firstName' | 'lastName'
> & {
  deleted: boolean;
  userId: number;
  filledReviews: number;
  pendingReviews: number;
  status: ReviewCycleStatus;
  totalReviews: number;
  score?: number;
  teamScoreDiff?: number;
  shareStatus?: DeliveryStatus;
  employeeInternalId?: string;
};

export enum PeerUserStatuses {
  ASSIGNED = 'ASSIGNED',
  PENDING = 'PENDING',
}

export type ReviewedUserSelection = Pick<
  ReviewUser,
  'profilePicture' | 'firstName' | 'lastName' | 'userId'
> & {
  reviewerCount: number;
  responsibleFistName: string;
  responsibleLastName: string;
  status: PeerUserStatuses;
};

export type ReviewerUserSelection = Pick<
  ReviewUser,
  'profilePicture' | 'firstName' | 'lastName' | 'userId'
> & {
  isExternal: boolean;
};

export type ReviewDetailFormQuestions = {
  choices: string[] | null;
  commentableStatus: ReviewCommentableStatus;
  defaultCountryCode: string | null;
  description: string | null;
  id: string;
  pattern: string | null;
  required: boolean;
  rows: null;
  title: string;
  type: ReviewQuestionType;
  userField: null;
  answer?: string | number | number[];
  comment?: string;
  goal?: Goal;
  competency?: Competency;
};

export type ReviewDetailFormQuestionsGoalItem = ReviewDetailFormQuestions & {
  isAutomatic: boolean;
};

export type CompetencyCategory = NonNullable<
  NonNullable<ReviewDetailFormQuestions['competency']>['category']
>;

export type CompetencyGroup = {
  category: CompetencyCategory | null;
  items: ReviewDetailFormQuestions[];
};

export type ReviewDetailForm = {
  answeredAt: string | null;
  description: string | null;
  questions: Array<ReviewDetailFormQuestions>;
  title: string;
  withAnswer: boolean;
};

export type ReviewDetail = {
  id: number;
  answered: boolean;
  reviewId: number;
  userId: number;
  profilePicture: string;
  firstName: string;
  lastName: string;
  cycleId: number;
  form: ReviewDetailForm | null;
  calibrationForm: ReviewDetailForm | null;
  reviewer: ReviewUser;
  reviewerId: number;
  reviewed: ReviewUser;
  reviewedId: number;
  shareStatus: DeliveryStatus;
  status: ReviewCycleStatus;
  type: ReviewDirection;
  score: number;
  scoreTag: string | null;
  loggedUserCanViewGoalsOfReviewed: boolean;
};

export type ReviewBody = {
  fillingTime: number;
  questionAnswers: {
    questionId: string;
    answer: unknown;
    comment?: string;
  }[];
};

enum ReviewQuestionOrigin {
  PERFORMANCE_REVIEW = 'PERFORMANCE_REVIEW',
}

export type ReviewQuestion = {
  id: number;
  title: string;
  description: string;
  type: ReviewDirection;
  commentableStatus: ReviewDirection;
  origin: ReviewQuestionOrigin;
  status: ReviewCycleStatus;
  answerRequired: boolean;
  createdAt: Date;
  updatedAt: Date;
  possibleAnswers: string[];
};

export type ReviewTemplate = {
  id: number;
  title: string;
  description: string;
  origin: ReviewQuestionOrigin;
  questionTemplates: ReviewQuestion[];
  questionsCount: number;
  status: string;
  createdAt: Date;
  updatedAt: Date;
  draftId: string;
  creatorId: number;
  creator?: User;
  evaluationType?: ReviewDirection;
  coreFormId?: number;
  coreFormTag?: number;
};

export type ReviewTemplateWrapper = {
  coreFormId: number;
  coreFormTag: string;
  createdAt: Date;
  cycleId: number;
  evaluationType?: ReviewDirection;
  template?: {
    formTemplate: ReviewTemplate;
    id: number;
  };
  templateId: number;
  id: number;
  updatedAt: number;
  withGoalScore: boolean;
  withCalibration?: boolean;
};

export type ReviewCycle = {
  id: number;
  name: string;
  createdAt: Date;
  updatedAt: Date;
  startDate: Date;
  endDate: Date;
  status: ReviewCycleStatus;
  reviewedUsersMode: ReviewCycleUsersMode;
  template: number | string;
  formTemplates?: ReviewTemplateWrapper[];
  // biome-ignore lint/suspicious/noExplicitAny: out of scope
  finishedReviews?: any;
  // biome-ignore lint/suspicious/noExplicitAny: out of scope
  totalReviews?: any;
  targetUserIds?: number[];
  withSummary?: boolean;
  needsChanges?: boolean;
  reviewsVisibleAfterFinishedReviewCycle?: boolean;
  canBeShared?: boolean;
  canBeSharedBeforeCycleFinish?: boolean;
  peerReviewReviewerSelectionVisibleForBosses?: boolean;
  peerReviewExternalReviewerSelectionVisibleForBosses?: boolean;
  othersReviewReviewerSelectionVisibleForBosses?: boolean;
  upwardReviewAnonymousAnswers?: boolean;
  peerReviewAnonymousAnswers?: boolean;
  peerExternalReviewAnonymousAnswers?: boolean;
  othersReviewAnonymousAnswers?: boolean;
  reviewerLimitByHiringDate?: Date;
};

export type ReviewStatus = {
  PENDING: number;
  FINISHED: number;
  IN_PROGRESS: number;
  OMITTED: number;
};

export type ReviewProgressStats = {
  // biome-ignore lint/complexity/noBannedTypes: out of scope
  statsPerReviewType: {};
  totalStats: ReviewStatus;
  teamScore?: number;
  evaluatedCollaborators?: number;
  totalCollaborators?: number;
  deliveredEvaluations?: number;
  statusBreakdown?: StatusBreakdown;
};

type UserToShare = Pick<
  ReviewUser,
  'deleted' | 'firstName' | 'lastName' | 'profilePicture' | 'userId'
>;

export type ReviewUserToShare = {
  cycleId: number;
  id: number;
  responsible: Pick<
    ReviewUser,
    'deleted' | 'firstName' | 'lastName' | 'profilePicture' | 'userId'
  > | null;
  responsibleId: number;
  shareStatus: DeliveryStatus;
  updatedAt: Date;
  user: Pick<
    ReviewUser,
    'deleted' | 'firstName' | 'lastName' | 'profilePicture' | 'userId'
  >;
  userId: number;
  summary: string;
  reviewedFormReviews: {
    answered: boolean;
    createdAt: string;
    cycleId: number;
    id: number;
    responsibleId: number;
    reviewed: UserToShare;
    reviewedId: number;
    reviewer: UserToShare;
    reviewerId: number;
    shareStatus: DeliveryStatus;
    status: ReviewCycleStatus;
    type: ReviewDirection;
    score: number | null;
    scoreTag: string | null;
    updatedAt: string;
  }[];
  score: number | null;
  scoreTag: string | null;
};

type Content = {
  subHeaderTitle: string;
  array: ReviewDetail[] | Omit<ReviewUserToShare, 'reviewedFormReviews'>[];
};

export type MenuItemsProps = {
  id: MenuItems;
  title: string;
  content: Content[];
}[];

export type ExternalUserReviewer = {
  createdAt: Date;
  email: string;
  firstName: string;
  lastName: string;
  id: number;
  updatedAt: Date;
};

export type PerformanceNotificationsResponse = {
  performanceReviewNotifications: number;
};

export type QueryId = string | number | null | undefined;
export type QueryFilter = Record<string, unknown> | undefined;
export type CycleReview = {
  id: number;
  answered: boolean;
} & Record<string, unknown>;
export type CycleQueryData = {
  data?: {
    reviewerFormReviews?: CycleReview[];
  };
};

export type UseLeaderDashboardParams = {
  cycleId: string | undefined;
  responsibleId: number | undefined;
};

export type UseLeaderDashboardReturn = {
  stats: ReviewProgressStats | undefined;
  statsLoading: boolean;
  users: ReviewUser[];
  usersLoading: boolean;
  usersFetching: boolean;
  totalPages: number;
  page: number;
  setPage: (page: number) => void;
  query: string;
  setQuery: (q: string) => void;
  debouncedQuery: string;
  selectedFilter: PendingActionFilter | undefined;
  setSelectedFilter: (filter: PendingActionFilter | undefined) => void;
  availableFilters: PendingActionFilter[];
  refetch: () => void;
};

export type LeaderCollaboratorsSectionProps = {
  users: ReviewUser[];
  usersLoading: boolean;
  usersFetching: boolean;
  query: string;
  setQuery: (q: string) => void;
  selectedFilter: PendingActionFilter | undefined;
  setSelectedFilter: (filter: PendingActionFilter | undefined) => void;
  availableFilters: PendingActionFilter[];
  page: number;
  setPage: (page: number) => void;
  totalPages: number;
  onUserSelect: (user: ReviewUser) => void;
};

export type LeaderCollaboratorRowProps = {
  user: ReviewUser;
  onSelect: (user: ReviewUser) => void;
};

export type LeaderStatCardsProps = {
  stats: ReviewProgressStats | undefined;
  isLoading: boolean;
};

export type LeaderProgressBlockProps = {
  stats: ReviewProgressStats | undefined;
  isLoading: boolean;
};

export type ReviewFormValues = {
  [key: string]: string | number | number[] | undefined;
  summary?: string;
};

export type ReviewedFormReviewItem = NonNullable<
  ReviewUserToShare['reviewedFormReviews']
>[number];

// --- Calibration ---

export type PerformanceReviewFormStatus =
  | 'EDIT_PENDING'
  | 'EDIT_REQUESTED'
  | 'FINISHED'
  | 'IN_PROGRESS'
  | 'OMITTED'
  | 'PENDING';

export type PerformanceReviewUser = {
  userId: number;
  employeeInternalId: string;
  firstName: string;
  lastName: string;
  profilePicture: string | null;
  deleted: boolean;
};

export type PerformanceReviewCoreFormQuestion = {
  id?: string;
  title?: string;
  description?: string | null;
  type?: string;
  commentableStatus?: string;
  required?: boolean;
  choices?: string[] | null;
  rows?: string[] | null;
  userField?: string | null;
  pattern?: string | null;
  defaultCountryCode?: string | null;
  answer?: unknown;
  comment?: string | null;
  goal?: Goal;
  competency?: Competency;
};

export type PerformanceReviewCoreFormContent = {
  title: string;
  description: string | null;
  questions: PerformanceReviewCoreFormQuestion[];
  answeredAt: string | null;
  withAnswer: boolean;
};

export type CalibratedUser = {
  formReviewId: number;
  user: {
    userId: number;
    firstName: string;
    lastName: string;
    profilePicture: string | null;
  };
  answered: boolean;
};

export type CalibrationReviewDetail = {
  calibrationReview: {
    formReviewId: number;
    status: PerformanceReviewFormStatus;
    form: PerformanceReviewCoreFormContent | null;
  };
  subordinateReview: {
    reviewer: PerformanceReviewUser | null;
    formReviewId: number;
    status: PerformanceReviewFormStatus;
    score: number | null;
    form: PerformanceReviewCoreFormContent | null;
  } | null;
};

export type FillCalibrationQuestionAnswer = {
  questionId: string;
  answer?: unknown | null;
  comment?: string | null;
};

export type FillCalibrationBody = {
  fillingTime: number;
  questionAnswers: FillCalibrationQuestionAnswer[];
};

export type CalibrationReview = {
  formReviewId: number;
  cycleId: number;
  reviewedId: number;
  reviewerId: number | null;
  status: PerformanceReviewFormStatus;
  score: number | null;
};
