import type { PersonalityDistributionDto } from '@/shared/types/personality';
import type { EmotionalIntelligenceLevel } from '@/shared/types/emotionalIntelligence';
import type { PersonalityType, QuizQuestion } from '@/shared/constants/personalityCatalog';
import type {
  PersonalityDirectoryFilterGroup,
  PersonalityDimensionProgress,
  PersonalityRelationshipTip,
  PersonalityTypeBreakdownItem,
} from '@/business/personality/types';

export function totalPersonalityDistribution(distribution: readonly PersonalityDistributionDto[]): number {
  return distribution.reduce((sum, item) => sum + item.count, 0);
}

export function groupPersonalityDistribution(
  distribution: readonly PersonalityDistributionDto[],
  getGroup: (code: string) => string,
): Record<string, number> {
  return distribution.reduce<Record<string, number>>((result, item) => {
    const group = getGroup(item.type);
    result[group] = (result[group] || 0) + item.count;
    return result;
  }, {});
}

export function getEmotionalIntelligenceLevel(percentage: number): EmotionalIntelligenceLevel {
  if (percentage >= 80) {
    return {
      label: 'Strong EI Foundation',
      color: 'text-emerald-400',
      bg: 'bg-emerald-500/15 border-emerald-500/20',
      desc: 'You demonstrate strong emotional awareness and regulation. Focus on mentoring others and deepening your practice.',
    };
  }

  if (percentage >= 60) {
    return {
      label: 'Growing EI Skills',
      color: 'text-blue-400',
      bg: 'bg-blue-500/15 border-blue-500/20',
      desc: 'You have a good foundation. Focus on consistency in high-stress moments and building your regulation toolkit.',
    };
  }

  if (percentage >= 40) {
    return {
      label: 'Developing Awareness',
      color: 'text-amber-400',
      bg: 'bg-amber-500/15 border-amber-500/20',
      desc: 'You are building awareness. Focus on identifying your triggers and practicing one regulation strategy daily.',
    };
  }

  return {
    label: 'Beginning Journey',
    color: 'text-rose-400',
    bg: 'bg-rose-500/15 border-rose-500/20',
    desc: 'This is a great starting point. Focus on naming your emotions throughout the day and noticing patterns.',
  };
}

export function getPersonalityGroup(code: string): string {
  const second = code[1];
  const third = code[2];
  const fourth = code[3];

  if (second === 'N' && third === 'T') {
    return 'Analysts';
  }

  if (second === 'N' && third === 'F') {
    return 'Diplomats';
  }

  if (second === 'S' && fourth === 'J') {
    return 'Sentinels';
  }

  if (second === 'S' && fourth === 'P') {
    return 'Explorers';
  }

  return 'Unknown';
}

export function formatPersonalitySavedDate(dateStr: string): string {
  const date = new Date(dateStr);

  if (Number.isNaN(date.getTime())) {
    return dateStr;
  }

  return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
}

export function getPersonalityDimensionLabel(dimension: QuizQuestion['dimension']): string {
  if (dimension === 'EI') return 'Energy Source';
  if (dimension === 'SN') return 'Information Style';
  if (dimension === 'TF') return 'Decision Making';
  return 'Work Structure';
}

export function getPersonalityDimensionShortLabel(dimension: QuizQuestion['dimension']): string {
  if (dimension === 'EI') return 'E/I';
  if (dimension === 'SN') return 'S/N';
  if (dimension === 'TF') return 'T/F';
  return 'J/P';
}

export function calculatePersonalityQuizProgress(currentQuestionIndex: number, totalQuestions: number): number {
  return ((currentQuestionIndex + 1) / totalQuestions) * 100;
}

export function getPersonalityDimensionProgress(
  currentQuestion: QuizQuestion,
  answers: Record<number, string>,
  questions: readonly QuizQuestion[],
): readonly PersonalityDimensionProgress[] {
  const dimensions: readonly QuizQuestion['dimension'][] = ['EI', 'SN', 'TF', 'JP'];

  return dimensions.map((dimension) => {
    const dimensionQuestions = questions.filter((question) => question.dimension === dimension);

    return {
      dimension,
      label: getPersonalityDimensionShortLabel(dimension),
      answeredCount: dimensionQuestions.filter((question) => Boolean(answers[question.id])).length,
      totalCount: dimensionQuestions.length,
      current: currentQuestion.dimension === dimension,
    };
  });
}

export function getPersonalityTypeBreakdown(type: PersonalityType): readonly PersonalityTypeBreakdownItem[] {
  const labels = ['Energy', 'Info', 'Decisions', 'Structure'];
  const letters = type.code.split('');

  return letters.map((letter, index) => {
    const fullLabels = [
      letter === 'E' ? 'Extraversion' : 'Introversion',
      letter === 'S' ? 'Sensing' : 'Intuition',
      letter === 'T' ? 'Thinking' : 'Feeling',
      letter === 'J' ? 'Judging' : 'Perceiving',
    ];

    return {
      letter,
      label: labels[index],
      fullLabel: fullLabels[index],
    };
  });
}

export function getPersonalityRelationshipTips(type: PersonalityType): readonly PersonalityRelationshipTip[] {
  return [
    {
      type: 'Analysts (NT types)',
      tip: type.code.includes('T')
        ? 'You naturally connect through shared logic - remember to also acknowledge emotions.'
        : 'Bridge the gap by framing your ideas with logical reasoning alongside your values.',
    },
    {
      type: 'Diplomats (NF types)',
      tip: type.code.includes('F')
        ? 'You share a values-driven approach - collaborate on vision and purpose.'
        : 'Show appreciation for their emotional insights and make space for personal connection.',
    },
    {
      type: 'Sentinels (SJ types)',
      tip: type.code.includes('J')
        ? 'You share a love of structure - partner on organizational projects.'
        : 'Respect their need for procedures and provide clear timelines when collaborating.',
    },
    {
      type: 'Explorers (SP types)',
      tip: type.code.includes('P')
        ? 'You share adaptability - team up for creative, hands-on projects.'
        : 'Appreciate their spontaneity and give them room to approach tasks their own way.',
    },
  ];
}

export function getPersonalityCommunicationStrengths(type: PersonalityType): readonly string[] {
  const strengths: string[] = [];

  if (type.code[0] === 'E') {
    strengths.push('Engaging others in open dialogue and brainstorming');
    strengths.push('Energizing team meetings with your verbal contributions');
  } else {
    strengths.push('Providing thoughtful, well-considered responses');
    strengths.push('Creating space for deeper, one-on-one conversations');
  }

  if (type.code[2] === 'T') {
    strengths.push('Delivering clear, logical arguments and analysis');
  } else {
    strengths.push('Reading emotional cues and responding with empathy');
  }

  if (type.code[3] === 'J') {
    strengths.push('Keeping discussions organized and action-oriented');
  } else {
    strengths.push('Adapting your message flexibly to the situation');
  }

  return strengths;
}

export function getPersonalityCommunicationGrowthArea(type: PersonalityType): string {
  if (type.code[0] === 'E') {
    return 'Practice active listening - pause before responding and ask clarifying questions to ensure you fully understand before sharing your perspective.';
  }

  return 'Practice sharing your ideas earlier in discussions - your insights are valuable and the team benefits when you speak up sooner.';
}

export function getPersonalityDirectoryGroup(code: string): PersonalityDirectoryFilterGroup {
  const second = code[1];
  const third = code[2];
  const fourth = code[3];

  if (second === 'N' && third === 'T') {
    return 'analysts';
  }

  if (second === 'N' && third === 'F') {
    return 'diplomats';
  }

  if (second === 'S' && fourth === 'J') {
    return 'sentinels';
  }

  if (second === 'S' && fourth === 'P') {
    return 'explorers';
  }

  return 'all';
}

export function getPersonalityDirectoryGroupLabel(group: PersonalityDirectoryFilterGroup): string {
  if (group === 'analysts') {
    return 'Analysts (NT)';
  }

  if (group === 'diplomats') {
    return 'Diplomats (NF)';
  }

  if (group === 'sentinels') {
    return 'Sentinels (SJ)';
  }

  if (group === 'explorers') {
    return 'Explorers (SP)';
  }

  return 'All Types';
}

export function getPersonalityDirectoryGroupDescription(
  group: PersonalityDirectoryFilterGroup,
): string {
  if (group === 'analysts') {
    return 'Strategic, logical thinkers who value competence and innovation';
  }

  if (group === 'diplomats') {
    return 'Empathetic, values-driven individuals who seek meaning and harmony';
  }

  if (group === 'sentinels') {
    return 'Reliable, practical organizers who value stability and tradition';
  }

  if (group === 'explorers') {
    return 'Adaptable, hands-on doers who thrive on action and spontaneity';
  }

  return 'All 16 personality types and their workplace profiles';
}

export function filterPersonalityDirectoryTypes(
  personalityTypes: readonly PersonalityType[],
  searchQuery: string,
  filterGroup: PersonalityDirectoryFilterGroup,
): readonly PersonalityType[] {
  const normalizedSearch = searchQuery.trim().toLowerCase();

  return personalityTypes.filter((type) => {
    const matchesSearch = normalizedSearch.length === 0
      || type.code.toLowerCase().includes(normalizedSearch)
      || type.name.toLowerCase().includes(normalizedSearch)
      || type.nickname.toLowerCase().includes(normalizedSearch);
    const matchesGroup = filterGroup === 'all' || getPersonalityDirectoryGroup(type.code) === filterGroup;

    return matchesSearch && matchesGroup;
  });
}
