'use client';

import { calculateAttachmentResults } from '../../test/private/AttachmentCalculator';

interface AttachmentResultProps {
  answers: string[];
}

const patternText = {
  secure: '相对安全型',
  preoccupied: '焦虑偏高型',
  dismissive: '回避偏高型',
  fearful: '焦虑与回避都偏高',
};

const patternDescription = {
  secure: '你在当前重要关系中通常较能亲近、信任和表达需求，不安全感相对较低。',
  preoccupied: '你可能较容易担心关系不够稳定，或需要更多确认来获得安全感。',
  dismissive: '你可能更习惯保持独立和距离，不太愿意依靠他人或表达脆弱。',
  fearful: '你可能既渴望亲近，又担心受伤或被拒绝，因此在关系中容易拉扯。',
};

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

export function AttachmentResult({ answers }: AttachmentResultProps) {
  const results = calculateAttachmentResults(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.avoidance.toFixed(2)}/7`} />
          <MetricCard title="依恋焦虑" value={`${results.anxiety.toFixed(2)}/7`} />
          <MetricCard title="模式提示" value={patternText[results.pattern]} />
        </div>
      </div>

      <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
        <BarCard title="依恋回避" value={results.avoidance} />
        <BarCard title="依恋焦虑" value={results.anxiety} />
      </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">{patternDescription[results.pattern]}</p>
      </div>

      <div className="border bg-gray-50 p-4 text-sm text-gray-700">
        注：依恋结果会随关系对象和关系阶段变化。它适合帮助你观察互动模式，不是给关系下定论。
      </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)} / 7
        </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>
  );
}
