import { BarChart3, Loader2, PieChart, RefreshCw, Shield } from 'lucide-react';

import { getPersonalityGroup } from '@/business/personality/selectors';
import { getPersonalityGroupColor } from '@/components/emotional-intelligence/groupStyles';
import type {
  EmotionalIntelligencePageActions,
  EmotionalIntelligencePageState,
} from '@/components/emotional-intelligence/types';
import { getPersonalityType } from '@/shared/constants/personalityCatalog';

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

export function PersonalityDistributionPanel({ state, actions }: PersonalityDistributionPanelProps) {
  return (
    <div className="bg-slate-800/40 backdrop-blur-sm rounded-2xl border border-slate-700/40 overflow-hidden">
      <div className="p-5 border-b border-slate-700/40">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-purple-500 to-indigo-600 flex items-center justify-center shadow-lg shadow-purple-500/20">
              <BarChart3 size={18} className="text-white" />
            </div>
            <div>
              <h3 className="font-bold text-white">Team Personality Distribution</h3>
              <p className="text-xs text-slate-400">Anonymized, aggregated view across all campuses</p>
            </div>
          </div>
          <button
            type="button"
            onClick={() => actions.refreshDistribution()}
            disabled={state.distributionLoading}
            className="flex items-center gap-1.5 px-3 py-1.5 bg-slate-700/50 text-slate-300 rounded-lg text-xs font-medium hover:bg-slate-700/70 border border-slate-600/30 transition-all"
          >
            {state.distributionLoading ? <Loader2 size={12} className="animate-spin" /> : <RefreshCw size={12} />}
            Refresh
          </button>
        </div>
      </div>

      <div className="p-5">
        {state.distributionErrorMessage ? (
          <div className="bg-rose-500/10 border border-rose-500/20 rounded-xl p-4 text-sm text-rose-300">
            {state.distributionErrorMessage}
          </div>
        ) : state.distributionLoading ? (
          <div className="flex items-center justify-center py-8">
            <Loader2 size={24} className="animate-spin text-violet-400" />
          </div>
        ) : state.distribution.length === 0 ? (
          <div className="text-center py-8">
            <PieChart size={32} className="mx-auto mb-3 text-slate-600" />
            <p className="text-sm text-slate-500">No personality quiz results yet.</p>
            <p className="text-xs text-slate-600 mt-1">Results will appear here as staff members complete the quiz.</p>
          </div>
        ) : (
          <div className="space-y-6">
            <DistributionSummary state={state} />
            <DistributionByGroup state={state} />
            <DistributionByType state={state} />
            <PrivacyNotice />
          </div>
        )}
      </div>
    </div>
  );
}

function DistributionSummary({ state }: Pick<PersonalityDistributionPanelProps, 'state'>) {
  return (
    <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
      <DistributionSummaryCard value={state.distributionTotal} label="Total Assessed" valueClassName="text-white" />
      <DistributionSummaryCard value={state.distribution.length} label="Unique Types" valueClassName="text-violet-400" />
      <DistributionSummaryCard value={state.distribution[0]?.type || '-'} label="Most Common" valueClassName="text-emerald-400" />
      <DistributionSummaryCard value={Object.keys(state.groupDistribution).length} label="Groups Represented" valueClassName="text-amber-400" />
    </div>
  );
}

type DistributionSummaryCardProps = {
  value: string | number;
  label: string;
  valueClassName: string;
};

function DistributionSummaryCard({ value, label, valueClassName }: DistributionSummaryCardProps) {
  return (
    <div className="bg-slate-700/30 rounded-xl p-4 border border-slate-600/30 text-center">
      <div className={`text-2xl font-black ${valueClassName}`}>{value}</div>
      <div className="text-[10px] text-slate-400 mt-1">{label}</div>
    </div>
  );
}

function DistributionByGroup({ state }: Pick<PersonalityDistributionPanelProps, 'state'>) {
  return (
    <div>
      <h4 className="font-semibold text-white text-sm mb-3 flex items-center gap-2">
        <PieChart size={14} className="text-violet-400" /> Distribution by Group
      </h4>
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        {['Analysts', 'Diplomats', 'Sentinels', 'Explorers'].map((group) => {
          const count = state.groupDistribution[group] || 0;
          const percentage = state.distributionTotal > 0 ? Math.round((count / state.distributionTotal) * 100) : 0;
          const colors = getPersonalityGroupColor(group);
          return (
            <div key={group} className={`${colors.bg} border ${colors.border} rounded-xl p-4`}>
              <div className="flex items-center justify-between mb-2">
                <span className={`text-xs font-semibold ${colors.text}`}>{group}</span>
                <span className="text-xs font-bold text-white">{count}</span>
              </div>
              <div className="h-2 bg-slate-700/50 rounded-full overflow-hidden mb-1">
                <div className={`h-full rounded-full transition-all duration-500 ${colors.bar}`} style={{ width: `${percentage}%` }} />
              </div>
              <span className="text-[10px] text-slate-500">{percentage}% of team</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function DistributionByType({ state }: Pick<PersonalityDistributionPanelProps, 'state'>) {
  return (
    <div>
      <h4 className="font-semibold text-white text-sm mb-3 flex items-center gap-2">
        <BarChart3 size={14} className="text-violet-400" /> Distribution by Type
      </h4>
      <div className="space-y-2">
        {state.distribution.map((item) => {
          const typeInfo = getPersonalityType(item.type, state.personalityTypes);
          const percentage = state.distributionTotal > 0 ? Math.round((item.count / state.distributionTotal) * 100) : 0;
          const group = getPersonalityGroup(item.type);
          const colors = getPersonalityGroupColor(group);
          return (
            <div key={item.type} className="flex items-center gap-3 p-2.5 bg-slate-700/20 rounded-xl border border-slate-700/30">
              <div className={`w-12 h-10 rounded-lg bg-gradient-to-br ${typeInfo?.color || 'from-slate-500 to-slate-600'} flex items-center justify-center flex-shrink-0`}>
                <span className="text-[10px] font-black text-white">{item.type}</span>
              </div>
              <div className="flex-1 min-w-0">
                <div className="flex items-center justify-between mb-1">
                  <div className="flex items-center gap-2">
                    <span className="text-xs font-semibold text-white">{typeInfo?.name || item.type}</span>
                    <span className={`text-[9px] ${colors.text} ${colors.bg} border ${colors.border} px-1.5 py-0.5 rounded`}>
                      {group}
                    </span>
                  </div>
                  <span className="text-xs font-bold text-slate-300">{item.count} staff ({percentage}%)</span>
                </div>
                <div className="h-1.5 bg-slate-700/50 rounded-full overflow-hidden">
                  <div className={`h-full rounded-full transition-all duration-500 ${colors.bar}`} style={{ width: `${percentage}%` }} />
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function PrivacyNotice() {
  return (
    <div className="bg-slate-700/20 rounded-xl p-4 border border-slate-600/20">
      <div className="flex items-start gap-2">
        <Shield size={14} className="text-slate-500 mt-0.5 flex-shrink-0" />
        <div>
          <p className="text-[11px] text-slate-500 font-medium">Privacy Notice</p>
          <p className="text-[10px] text-slate-600 mt-0.5">
            This view shows anonymized, aggregated data only. Individual staff members&apos; personality types are not identified.
            Results are grouped to show team composition patterns and help inform professional development planning.
          </p>
        </div>
      </div>
    </div>
  );
}
