"use client";

import { useTranslations, useLocale } from "next-intl";
import type { PMItemResponse } from "@/types/therapist-report";

interface ReportCardProps {
  itemResponses: PMItemResponse[]; // score > 0 items from API; missing items default to score=0
}

// All 29 MBHS items in canonical scale order (hardcoded — standardised instrument)
const MBHS_ITEMS: { item_number: number; scale_name: string; question_text: string }[] = [
  // Somatization
  { item_number: 1, scale_name: "somatization", question_text: "I have pains." },
  { item_number: 12, scale_name: "somatization", question_text: "I feel weak." },
  { item_number: 23, scale_name: "somatization", question_text: "I get nauseated often." },
  // Cognitive Issues
  { item_number: 7, scale_name: "cognitive_issues", question_text: "I have trouble concentrating." },
  { item_number: 17, scale_name: "cognitive_issues", question_text: "I get distracted easily." },
  { item_number: 27, scale_name: "cognitive_issues", question_text: "I can't remember things." },
  // Demoralization
  { item_number: 2, scale_name: "demoralization", question_text: "I feel useless." },
  { item_number: 13, scale_name: "demoralization", question_text: "I am dissatisfied with my life." },
  { item_number: 24, scale_name: "demoralization", question_text: "I feel generally discouraged." },
  // Anhedonia
  { item_number: 3, scale_name: "anhedonia", question_text: "There is little joy in my life." },
  { item_number: 14, scale_name: "anhedonia", question_text: "I have little motivation." },
  { item_number: 20, scale_name: "anhedonia", question_text: "I tend to avoid social activities." },
  // Anxiety
  { item_number: 4, scale_name: "anxiety", question_text: "I worry a lot." },
  { item_number: 16, scale_name: "anxiety", question_text: "Nervousness interferes with my daily functioning." },
  { item_number: 28, scale_name: "anxiety", question_text: "I obsess about things I can't control." },
  // Suicidal Ideation
  { item_number: 6, scale_name: "suicidal_ideation", question_text: "These days, I feel like I don't belong." },
  { item_number: 10, scale_name: "suicidal_ideation", question_text: "These days, the people in my life would be better off if I were gone." },
  { item_number: 15, scale_name: "suicidal_ideation", question_text: "I want to die." },
  { item_number: 25, scale_name: "suicidal_ideation", question_text: "I am not afraid to die. (Fearlessness)" },
  { item_number: 29, scale_name: "suicidal_ideation", question_text: "Any previous suicide attempts? (Previous attempts)" },
  // Activation
  { item_number: 5, scale_name: "activation", question_text: "My mood severely changes regardless of what is going on around me." },
  { item_number: 11, scale_name: "activation", question_text: "At times I feel uncontrollable excitement." },
  { item_number: 22, scale_name: "activation", question_text: "Some days I am so full of energy I can't sit still." },
  // Disconstraint
  { item_number: 9, scale_name: "disconstraint", question_text: "I often make impulsive decisions." },
  { item_number: 19, scale_name: "disconstraint", question_text: "I often break rules, regardless of the consequences." },
  { item_number: 21, scale_name: "disconstraint", question_text: "I don't think before I act." },
  // Substance Use Problems
  { item_number: 8, scale_name: "substance_use_problems", question_text: "I sometimes drink or use drugs too much." },
  { item_number: 18, scale_name: "substance_use_problems", question_text: "I sometimes spend more time drinking or using drugs than I intended." },
  { item_number: 26, scale_name: "substance_use_problems", question_text: "I have wanted to cut down on drinking or using drugs." },
];

// Maps snake_case scale key → next-intl key under practitioner.scales
const SCALE_I18N_KEY: Record<string, string> = {
  somatization: "somatization",
  cognitive_issues: "cognitiveIssues",
  demoralization: "demoralization",
  anhedonia: "anhedonia",
  anxiety: "anxiety",
  suicidal_ideation: "suicidalIdeation",
  activation: "activation",
  disconstraint: "disconstraint",
  substance_use_problems: "substanceUseProblems",
};

// Fallback label map: derive answer label from score when API omits score=0 items
const SCORE_LABELS: Record<number, string> = {
  0: "Definitely False",
  1: "Mostly False",
  2: "Mostly True",
  3: "Definitely True",
};

const ANSWER_LABEL_ES: Record<string, string> = {
  "Definitely False": "Definitivamente Falso",
  "Mostly False": "Mayormente Falso",
  "Mostly True": "Mayormente Verdadero",
  "Definitely True": "Definitivamente Verdadero",
  "Previous Attempts": "Intentos previos",
};

const QUESTION_TEXT_ES: Record<number, string> = {
  1: "Tengo dolores.",
  12: "Me siento débil.",
  23: "Con frecuencia tengo náuseas.",
  7: "Tengo dificultad para concentrarme.",
  17: "Me distraigo fácilmente.",
  27: "No puedo recordar las cosas.",
  2: "Me siento inútil.",
  13: "Estoy insatisfecho/a con mi vida.",
  24: "Me siento generalmente desanimado/a.",
  3: "Hay poco gozo en mi vida.",
  14: "Tengo poca motivación.",
  20: "Tiendo a evitar las actividades sociales.",
  4: "Me preocupo mucho.",
  16: "El nerviosismo interfiere con mi funcionamiento diario.",
  28: "Me obsesiono con cosas que no puedo controlar.",
  6: "Últimamente, siento que no pertenezco.",
  10: "Últimamente, las personas en mi vida estarían mejor si yo no estuviera.",
  15: "Quiero morir.",
  25: "No tengo miedo a morir. (Valentía ante la muerte)",
  29: "¿Ha habido intentos de suicidio previos? (Intentos previos)",
  5: "Mi estado de ánimo cambia severamente independientemente de lo que ocurra a mi alrededor.",
  11: "A veces siento una emoción incontrolable.",
  22: "Algunos días tengo tanta energía que no puedo estar quieto/a.",
  9: "A menudo tomo decisiones impulsivas.",
  19: "A menudo rompo reglas, independientemente de las consecuencias.",
  21: "No pienso antes de actuar.",
  8: "A veces bebo o consumo drogas en exceso.",
  18: "A veces paso más tiempo bebiendo o consumiendo drogas de lo que pretendía.",
  26: "He querido reducir el consumo de alcohol o drogas.",
};

// Canonical scale rendering order
const SCALE_ORDER = [
  "somatization",
  "cognitive_issues",
  "demoralization",
  "anhedonia",
  "anxiety",
  "suicidal_ideation",
  "activation",
  "disconstraint",
  "substance_use_problems",
];

export default function ReportCard({ itemResponses }: ReportCardProps) {
  const t = useTranslations("practitioner.report.reportCard");
  const tScales = useTranslations("practitioner.scales");
  const locale = useLocale();

  // Build lookup map: item_number/question_order → { score, answer_label }
  const scoreMap = new Map<number, { score: number; answer_label: string }>();
  for (const item of itemResponses) {
    const key = item.item_number ?? item.question_order;
    const val = item.score ?? item.answer_value ?? 0;
    if (key !== undefined) scoreMap.set(key, { score: val, answer_label: item.answer_label });
  }

  // Group all 29 items by scale in canonical order
  const scales = SCALE_ORDER.map((scaleName) => ({
    scaleName,
    displayName: tScales(SCALE_I18N_KEY[scaleName] as Parameters<typeof tScales>[0]),
    items: MBHS_ITEMS.filter((item) => item.scale_name === scaleName).map((item) => {
      const response = scoreMap.get(item.item_number);
      const score = response?.score ?? 0;
      // Q#29 is a count of previous suicide attempts, not a 4-point Likert item —
      // the Definitely/Mostly False/True labels don't apply, so override with a semantic label.
      const isPreviousAttempts = item.item_number === 29;
      const enLabel = isPreviousAttempts
        ? "Previous Attempts"
        : (response?.answer_label || SCORE_LABELS[score] || "Definitely False");
      return {
        item_number: item.item_number,
        question_text: locale === 'es' ? (QUESTION_TEXT_ES[item.item_number] || item.question_text) : item.question_text,
        score,
        answer_label: locale === 'es' ? (ANSWER_LABEL_ES[enLabel] || enLabel) : enLabel,
      };
    }),
  }));

  // Global alternating row index across all scales
  let globalRowIndex = 0;

  return (
    <div data-pdf-section="report-card-header" style={{ marginTop: "40px" }}>
      {/* Section title */}
      <h2
        style={{
          fontSize: "18px",
          fontWeight: 700,
          color: "#111827",
          marginBottom: "6px",
          marginTop: 0,
        }}
      >
        {t("title")}
      </h2>
      <p
        style={{
          fontSize: "13px",
          color: "#6b7280",
          marginBottom: "16px",
          marginTop: 0,
        }}
      >
        {t("subtitle")}
      </p>

      {/* Report card table */}
      <table
        style={{
          width: "100%",
          borderCollapse: "collapse",
          fontSize: "13px",
          tableLayout: "fixed",
        }}
      >
        <colgroup>
          <col style={{ width: "200px" }} />
          <col />
          <col style={{ width: "55px" }} />
          <col style={{ width: "130px" }} />
        </colgroup>
        <thead>
          <tr
            style={{
              backgroundColor: "#f3f4f6",
              borderBottom: "2px solid #e5e7eb",
            }}
          >
            <th
              style={{
                padding: "8px 10px",
                textAlign: "left",
                fontWeight: 600,
                color: "#374151",
              }}
            >
              {t("colScale")}
            </th>
            <th
              style={{
                padding: "8px 10px",
                textAlign: "left",
                fontWeight: 600,
                color: "#374151",
              }}
            >
              {t("colQuestion")}
            </th>
            <th
              style={{
                padding: "8px 10px",
                textAlign: "center",
                fontWeight: 600,
                color: "#374151",
              }}
            >
              {t("colScore")}
            </th>
            <th
              style={{
                padding: "8px 10px",
                textAlign: "left",
                fontWeight: 600,
                color: "#374151",
              }}
            >
              {t("colResponse")}
            </th>
          </tr>
        </thead>
        <tbody>
          {scales.map(({ scaleName, displayName, items }) =>
            items.map((item, itemIndex) => {
              const isEven = globalRowIndex % 2 === 0;
              globalRowIndex++;
              const rowBg = isEven ? "#ffffff" : "#f9fafb";

              const scoreColor =
                item.score === 0
                  ? "#9ca3af"
                  : item.score === 1
                  ? "#374151"
                  : "#dc2626"; // score ≥ 2 = red (clinically elevated)

              return (
                <tr
                  key={`${scaleName}-${item.item_number}`}
                  data-pdf-section={`report-card-row-${item.item_number}`}
                  style={{
                    backgroundColor: rowBg,
                    borderBottom: "1px solid #e5e7eb",
                  }}
                >
                  {/* Scale name cell — only on first item in group, spans all items */}
                  {itemIndex === 0 && (
                    <td
                      rowSpan={items.length}
                      style={{
                        padding: "8px 10px",
                        fontWeight: 600,
                        color: "#111827",
                        backgroundColor: "#f9fafb",
                        verticalAlign: "top",
                        borderRight: "1px solid #e5e7eb",
                        borderBottom: "2px solid #d1d5db",
                        lineHeight: 1.4,
                        whiteSpace: "nowrap",
                      }}
                    >
                      {displayName}
                    </td>
                  )}

                  {/* Item number + question text */}
                  <td
                    style={{
                      padding: "8px 10px",
                      color: "#374151",
                      lineHeight: 1.5,
                    }}
                  >
                    <span
                      style={{
                        fontSize: "11px",
                        color: "#9ca3af",
                        marginRight: "6px",
                      }}
                    >
                      #{item.item_number}
                    </span>
                    {item.question_text}
                  </td>

                  {/* Score */}
                  <td
                    style={{
                      padding: "8px 10px",
                      textAlign: "center",
                      fontWeight: 700,
                      color: scoreColor,
                    }}
                  >
                    {item.score}
                  </td>

                  {/* Response label */}
                  <td
                    style={{
                      padding: "8px 10px",
                      color: scoreColor,
                    }}
                  >
                    {item.answer_label}
                  </td>
                </tr>
              );
            })
          )}
        </tbody>
      </table>
    </div>
  );
}
