'use client';

import { calculateNeedForCognitionResults } from '../../test/private/NeedForCognitionCalculator';

interface NeedForCognitionResultProps {
  answers: string[];
}

const levelText = {
  low: '认知需求偏低',
  moderate: '认知需求中等',
  high: '认知需求较高',
};

const levelDescription = {
  low: '你可能更偏好清晰、直接、低认知负荷的处理方式。面对复杂问题时，降低进入门槛和明确收益会更有帮助。',
  moderate: '你会根据情境投入思考：重要、有兴趣或有价值的问题更容易激发你深入加工。',
  high: '你通常喜欢深入思考、分析复杂问题和寻找新解法。注意在低风险问题上保留效率感，会更平衡。',
};

function width(value: number) {
  return `${Math.max(0, Math.min(100, ((value - 1) / 4) * 100))}%`;
}

export function NeedForCognitionResult({ answers }: NeedForCognitionResultProps) {
  const results = calculateNeedForCognitionResults(answers);

  return (
    <div className="mt-6 space-y-6">
      <div className="border bg-white p-6 shadow-sm">
        <h3 className="text-lg font-semibold mb-4">认知需求量表结果</h3>
        <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
          <MetricCard title="总分" value={`${results.total}/90`} />
          <MetricCard title="平均分" value={`${results.average.toFixed(2)}/5`} />
          <MetricCard title="结果水平" value={levelText[results.level]} />
        </div>
      </div>

      <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
        <BarCard title="思考投入" value={results.thinkingAverage} />
        <BarCard title="智力挑战偏好" value={results.challengeAverage} />
      </div>

      <div className="border bg-blue-50 p-6 text-blue-900 shadow-sm">
        <h3 className="text-lg font-semibold mb-3">结果解释</h3>
        <p className="text-sm">{levelDescription[results.level]}</p>
      </div>

      <div className="border bg-gray-50 p-4 text-sm text-gray-700">
        注：认知需求表示思考动机和偏好，不是智力测验。可与CRT结果结合理解。
      </div>
    </div>
  );
}

function MetricCard({ title, value }: { title: string; value: string }) {
  return (
    <div className="rounded-lg bg-gray-50 p-4 text-center">
      <div className="text-sm text-muted-foreground">{title}</div>
      <div className="mt-1 text-2xl font-semibold text-indigo-600">{value}</div>
    </div>
  );
}

function BarCard({ title, value }: { title: string; value: number }) {
  return (
    <div className="rounded-lg border bg-white p-5 shadow-sm">
      <div className="mb-3 flex items-center justify-between">
        <h4 className="font-semibold">{title}</h4>
        <span className="text-sm text-muted-foreground">
          {value.toFixed(2)} / 5
        </span>
      </div>
      <div className="h-2 overflow-hidden rounded-full bg-gray-100">
        <div
          className="h-full rounded-full bg-emerald-500"
          style={{ width: width(value) }}
        />
      </div>
    </div>
  );
}
