import {
  ArrowRight,
  Brain,
  CheckCircle,
  Eye,
  Fingerprint,
  Heart,
  RefreshCw,
  RotateCcw,
  Shield,
  Sparkles,
  TrendingUp,
  Users,
} from 'lucide-react';
import type { LucideIcon } from 'lucide-react';

import { StatePanel } from '@/components/ui/state-panel';
import type {
  EmotionalIntelligencePageActions,
  EmotionalIntelligencePageState,
} from '@/components/emotional-intelligence/types';
import type { EmotionalIntelligenceTopicIconId } from '@/shared/types/emotionalIntelligence';
import { getPersonalityType } from '@/shared/constants/personalityCatalog';

const TOPIC_ICONS: Record<EmotionalIntelligenceTopicIconId, LucideIcon> = {
  shield: Shield,
  brain: Brain,
  heart: Heart,
  eye: Eye,
};

type AssessmentTabProps = {
  state: EmotionalIntelligencePageState;
  actions: EmotionalIntelligencePageActions;
};

export function AssessmentTab({ state, actions }: AssessmentTabProps) {
  return (
    <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
      <div className="lg:col-span-2">
        {state.contentLoading ? (
          <StatePanel tone="pink" size="lg" alignment="center" loading>
            Loading assessment content...
          </StatePanel>
        ) : state.contentError ? (
          <StatePanel tone="red" role="alert">
            Emotional intelligence content could not be loaded from the backend.
          </StatePanel>
        ) : state.assessmentQuestions.length === 0 ? (
          <StatePanel tone="slate">
            Emotional intelligence assessment content is not available yet.
          </StatePanel>
        ) : !state.assessmentStarted && !state.assessmentComplete ? (
          <AssessmentIntro state={state} actions={actions} />
        ) : state.assessmentComplete ? (
          <AssessmentResults state={state} actions={actions} />
        ) : (
          <AssessmentQuestion state={state} actions={actions} />
        )}
      </div>

      <AssessmentSidebar state={state} actions={actions} />
    </div>
  );
}

function AssessmentIntro({ state, actions }: AssessmentTabProps) {
  return (
    <div className="bg-slate-800/40 backdrop-blur-sm rounded-2xl border border-slate-700/40 p-6">
      <div className="text-center mb-6">
        <div className="w-20 h-20 rounded-2xl bg-gradient-to-br from-pink-500 to-violet-600 flex items-center justify-center mx-auto mb-4 shadow-xl shadow-pink-500/20">
          <Brain size={36} className="text-white" />
        </div>
        <h3 className="text-xl font-bold text-white">EI Self-Assessment</h3>
        <p className="text-sm text-slate-400 mt-1">{state.assessmentQuestions.length} reflective questions - Private results - Takes 5 minutes</p>
      </div>
      <button
        type="button"
        onClick={() => actions.setAssessmentStarted(true)}
        className="w-full py-3 bg-gradient-to-r from-pink-500 to-violet-600 text-white rounded-xl font-semibold hover:shadow-lg hover:shadow-pink-500/25 transition-all"
      >
        Begin Assessment
      </button>
      <div className="mt-6 grid grid-cols-2 gap-3">
        {state.weeklyTopics.map((topic) => {
          const TopicIcon = TOPIC_ICONS[topic.iconId];
          return (
            <div key={topic.title} className={`${topic.color} border rounded-xl p-4`}>
              <div className="mb-2"><TopicIcon size={18} /></div>
              <h4 className="font-semibold text-sm">{topic.title}</h4>
              <p className="text-[10px] mt-1 opacity-80">{topic.desc}</p>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function AssessmentResults({ state, actions }: AssessmentTabProps) {
  const { assessmentLevel } = state;

  return (
    <div className="bg-slate-800/40 backdrop-blur-sm rounded-2xl border border-slate-700/40 p-6">
      <div className="text-center mb-6">
        <div className={`w-24 h-24 rounded-full ${assessmentLevel.bg} border flex items-center justify-center mx-auto mb-4`}>
          <span className={`text-3xl font-bold ${assessmentLevel.color}`}>{state.percentage}%</span>
        </div>
        <h3 className={`text-xl font-bold ${assessmentLevel.color}`}>{assessmentLevel.label}</h3>
        <p className="text-sm text-slate-400 mt-2 max-w-md mx-auto">{assessmentLevel.desc}</p>
      </div>
      <div className="bg-slate-700/30 rounded-xl p-4 mb-4 border border-slate-600/30">
        <div className="flex justify-between text-sm mb-2">
          <span className="text-slate-400">Your Score</span>
          <span className="font-bold text-white">{state.totalScore}/{state.maxScore}</span>
        </div>
        <div className="h-3 bg-slate-700/50 rounded-full overflow-hidden">
          <div className="h-full bg-gradient-to-r from-pink-500 to-violet-500 rounded-full transition-all duration-1000" style={{ width: `${state.percentage}%` }} />
        </div>
      </div>
      <div className="bg-pink-500/10 rounded-xl p-4 mb-4 border border-pink-500/20">
        <h4 className="font-semibold text-pink-400 text-sm mb-2">Your Growth Path</h4>
        <ul className="space-y-1.5">
          {state.growthTips.slice(0, 3).map((tip) => (
            <li key={tip} className="flex items-start gap-2">
              <CheckCircle size={14} className="text-pink-400 mt-0.5 flex-shrink-0" />
              <span className="text-xs text-slate-300">{tip}</span>
            </li>
          ))}
        </ul>
      </div>
      <div className="flex gap-3 justify-center">
        <button
          type="button"
          onClick={actions.resetAssessment}
          className="flex items-center gap-2 px-5 py-2.5 bg-pink-500/15 text-pink-400 rounded-xl font-medium text-sm hover:bg-pink-500/25 border border-pink-500/20"
        >
          <RotateCcw size={14} /> Retake Assessment
        </button>
        <button
          type="button"
          onClick={() => actions.setActiveTab('personality')}
          className="flex items-center gap-2 px-5 py-2.5 bg-violet-500/15 text-violet-400 rounded-xl font-medium text-sm hover:bg-violet-500/25 border border-violet-500/20"
        >
          <Fingerprint size={14} /> Take Personality Quiz
        </button>
      </div>
    </div>
  );
}

function AssessmentQuestion({ state, actions }: AssessmentTabProps) {
  const question = state.assessmentQuestions[state.currentQuestionIndex];

  if (!question) {
    return (
      <div className="bg-slate-800/40 backdrop-blur-sm rounded-2xl border border-slate-700/40 p-6 text-sm text-slate-400">
        Current assessment question is unavailable.
      </div>
    );
  }

  return (
    <div className="bg-slate-800/40 backdrop-blur-sm rounded-2xl border border-slate-700/40 p-6">
      <div className="flex items-center justify-between mb-4">
        <span className="text-sm font-medium text-slate-400">Question {state.currentQuestionIndex + 1} of {state.assessmentQuestions.length}</span>
        <span className="text-xs text-slate-500">Private & Confidential</span>
      </div>
      <div className="h-2 bg-slate-700/50 rounded-full mb-6">
        <div className="h-full bg-gradient-to-r from-pink-500 to-violet-500 rounded-full transition-all duration-500" style={{ width: `${((state.currentQuestionIndex + 1) / state.assessmentQuestions.length) * 100}%` }} />
      </div>
      <h3 className="text-lg font-semibold text-white mb-4">{question.q}</h3>
      <div className="space-y-3">
        {question.options.map((option, index) => (
          <button
            type="button"
            key={option}
            onClick={() => actions.handleAnswer(index)}
            className="w-full text-left p-4 rounded-xl border-2 border-slate-600/40 bg-slate-700/30 hover:bg-pink-500/10 hover:border-pink-500/30 transition-all"
          >
            <span className="text-sm text-slate-200">{option}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

function AssessmentSidebar({ state, actions }: AssessmentTabProps) {
  const personalityType = state.personalityResult ? getPersonalityType(state.personalityResult, state.personalityTypes) : null;

  return (
    <div className="space-y-4">
      <div className="bg-gradient-to-br from-violet-500/10 to-indigo-500/10 backdrop-blur-sm rounded-2xl border border-violet-500/20 p-5">
        <div className="flex items-center gap-3 mb-3">
          <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-violet-500 to-indigo-600 flex items-center justify-center shadow-lg">
            <Fingerprint size={18} className="text-white" />
          </div>
          <div>
            <h3 className="font-semibold text-white text-sm">Personality Type Quiz</h3>
            <p className="text-[10px] text-slate-400">
              {state.personalityResult ? `Your type: ${state.personalityResult}` : 'Discover your MBTI type'}
            </p>
          </div>
        </div>
        {state.personalityResult ? (
          <>
            <div className="bg-violet-500/10 border border-violet-500/20 rounded-xl p-3 mb-3">
              <div className="flex items-center gap-2 mb-1">
                <span className="text-lg font-black text-violet-400">{state.personalityResult}</span>
                <span className="text-xs text-slate-300">{personalityType?.name}</span>
              </div>
              <p className="text-[10px] text-slate-500">{personalityType?.nickname}</p>
              {state.savedDate && (
                <p className="text-[9px] text-slate-600 mt-1">Last taken: {new Date(state.savedDate).toLocaleDateString()}</p>
              )}
            </div>
            <div className="flex gap-2">
              <button type="button" onClick={() => actions.setActiveTab('personality')} className="flex-1 py-2 bg-violet-500/15 text-violet-400 rounded-xl font-medium text-xs hover:bg-violet-500/25 border border-violet-500/20 transition-all flex items-center justify-center gap-1">
                <Eye size={12} /> View
              </button>
              <button type="button" onClick={() => actions.setActiveTab('personality')} className="flex-1 py-2 bg-slate-700/50 text-slate-300 rounded-xl font-medium text-xs hover:bg-slate-700/70 border border-slate-600/30 transition-all flex items-center justify-center gap-1">
                <RefreshCw size={12} /> Retake
              </button>
            </div>
          </>
        ) : (
          <>
            <p className="text-xs text-slate-400 mb-3">Find out if you are an INFJ, ESTP, or one of 16 personality types. Learn how your type shapes your work relationships and communication style.</p>
            <button type="button" onClick={() => actions.setActiveTab('personality')} className="w-full py-2.5 bg-gradient-to-r from-violet-500 to-indigo-600 text-white rounded-xl font-semibold text-sm hover:shadow-lg hover:shadow-violet-500/25 transition-all flex items-center justify-center gap-2">
              Take the Quiz <ArrowRight size={14} />
            </button>
          </>
        )}
      </div>

      <div className="bg-slate-800/40 backdrop-blur-sm rounded-2xl border border-slate-700/40 p-5">
        <h3 className="font-semibold text-white mb-3 flex items-center gap-2"><Sparkles size={16} className="text-pink-400" /> Daily Growth Tips</h3>
        <div className="space-y-2.5">
          {state.growthTips.map((tip) => (
            <div key={tip} className="flex items-start gap-2 p-2 rounded-lg bg-pink-500/5 border border-pink-500/10">
              <CheckCircle size={14} className="text-pink-400 mt-0.5 flex-shrink-0" />
              <p className="text-xs text-slate-300">{tip}</p>
            </div>
          ))}
        </div>
      </div>

      {state.isDirector && <TeamWellnessCard metrics={state.teamWellnessMetrics} />}
    </div>
  );
}

function TeamWellnessCard({ metrics }: { readonly metrics: readonly EmotionalIntelligencePageState['teamWellnessMetrics'][number][] }) {
  return (
    <div className="bg-slate-800/40 backdrop-blur-sm rounded-2xl border border-slate-700/40 p-5">
      <h3 className="font-semibold text-white mb-3 flex items-center gap-2"><Users size={16} className="text-violet-400" /> Team Wellness (Aggregated)</h3>
      <p className="text-[10px] text-slate-500 mb-3">No individual emotional data shown</p>
      <div className="space-y-3">
        {metrics.map((item) => (
          <div key={item.label}>
            <div className="flex justify-between text-xs mb-1">
              <span className="text-slate-400">{item.label}</span>
              <span className={`font-semibold ${item.color} flex items-center gap-1`}>
                {item.label === 'Growth Trend' && <TrendingUp size={12} />}
                {item.value}
              </span>
            </div>
            <div className="h-2 bg-slate-700/50 rounded-full"><div className={`h-full ${item.bar} rounded-full`} style={{ width: item.width }} /></div>
          </div>
        ))}
      </div>
    </div>
  );
}
