"use client";

import { useState } from "react";
import type { PriorityItemViewModel } from "../_lib/types";

interface Props {
  priorities: readonly PriorityItemViewModel[];
}

const SEV_STYLES = {
  critical: {
    border: "border-l-red-500",
    badge: "bg-red-100 text-red-700",
    impactColor: "text-red-600",
  },
  high: {
    border: "border-l-amber-500",
    badge: "bg-amber-100 text-amber-700",
    impactColor: "text-amber-600",
  },
} as const;

function PriorityCard({ p, defaultOpen }: { p: PriorityItemViewModel; defaultOpen: boolean }) {
  const [open, setOpen] = useState(defaultOpen);
  const [showAllPages, setShowAllPages] = useState(false);

  const sev = SEV_STYLES[p.severity];
  const PAGE_PREVIEW = 3;
  const displayedPages = showAllPages ? p.affectedPages : p.affectedPages.slice(0, PAGE_PREVIEW);
  const moreCount = Math.max(0, p.affectedPages.length - PAGE_PREVIEW);
  const hasImpact = p.scoreLift != null || p.affectedPages.length > 0;

  return (
    <article
      className={`bg-white border border-slate-200 border-l-[3px] ${sev.border} rounded-xl shadow-subtle overflow-hidden`}
    >
      {/* Collapsed header -- always visible */}
      <button
        type="button"
        className="w-full flex items-center gap-3 px-6 py-4 text-left hover:bg-slate-50 transition-colors"
        onClick={() => setOpen((o) => !o)}
        aria-expanded={open}
      >
        <div className="flex flex-wrap items-center gap-2 flex-1 min-w-0">
          <span
            className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded text-[10px] font-bold uppercase tracking-widest ${sev.badge} shrink-0 before:content-[''] before:w-1.5 before:h-1.5 before:rounded-full before:bg-current`}
          >
            {p.severity === "critical" ? "Critical" : "High"}
          </span>
          {p.category === "tech" ? (
            <span className="px-2.5 py-1 bg-violet-100 border border-violet-200 rounded text-[10px] font-bold text-violet-700 uppercase tracking-[0.04em] shrink-0">
              Tech
            </span>
          ) : p.category === "multilingual" ? (
            <span className="px-2.5 py-1 bg-cyan-100 border border-cyan-200 rounded text-[10px] font-bold text-cyan-700 uppercase tracking-[0.04em] shrink-0">
              Multi
            </span>
          ) : p.category === "compliance" ? (
            <span className="px-2.5 py-1 bg-red-100 border border-red-200 rounded text-[10px] font-bold text-red-700 uppercase tracking-[0.04em] shrink-0">
              Compliance
            </span>
          ) : p.category === "ecommerce" ? (
            <span className="px-2.5 py-1 bg-green-100 border border-green-200 rounded text-[10px] font-bold text-green-700 uppercase tracking-[0.04em] shrink-0">
              Ecom
            </span>
          ) : p.category === "b2b" ? (
            <span className="px-2.5 py-1 bg-indigo-100 border border-indigo-200 rounded text-[10px] font-bold text-indigo-700 uppercase tracking-[0.04em] shrink-0">
              B2B
            </span>
          ) : (
            <span className="px-2.5 py-1 bg-slate-50 border border-slate-200 rounded text-[10px] font-semibold text-slate-600 uppercase tracking-[0.04em] shrink-0">
              {p.dimension}
            </span>
          )}
          {p.scoreLift != null && (
            <span className="px-2.5 py-1 bg-emerald-50 text-emerald-700 rounded text-[11px] font-semibold tabular-nums shrink-0">
              +{p.scoreLift} health pts
            </span>
          )}
          <h3 className="text-[15px] font-bold text-slate-900 tracking-tight min-w-0">
            {p.title}
          </h3>
        </div>
        <div className="flex items-center gap-3 shrink-0 ml-2">
          {p.affectedPages.length > 0 && (
            <span className="text-[11px] text-slate-400 tabular-nums whitespace-nowrap">
              {p.affectedPages.length} page{p.affectedPages.length !== 1 ? "s" : ""}
            </span>
          )}
          <svg
            className={`w-4 h-4 text-slate-400 transition-transform duration-200 ${open ? "rotate-180" : ""}`}
            viewBox="0 0 16 16"
            fill="none"
            stroke="currentColor"
            strokeWidth={1.5}
          >
            <path d="M4 6l4 4 4-4" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </div>
      </button>

      {/* Expanded content */}
      {open && (
        <div className="border-t border-slate-100 grid grid-cols-1 xl:grid-cols-[1.3fr_1.4fr_1fr] gap-7 px-6 py-5">

          {/* Left: Description + affected pages */}
          <div>
            <span className="text-[10px] font-semibold text-slate-500 uppercase tracking-widest">
              Description
            </span>
            <p className="text-[12px] text-slate-600 leading-relaxed mt-1.5 mb-3.5">
              {p.subline}
            </p>

            {p.affectedPages.length > 0 && (
              <div className="flex flex-col gap-1.5">
                {displayedPages.map((page) => (
                  <div
                    key={page}
                    className="flex items-center gap-2 px-2.5 py-1.5 bg-slate-50 border border-slate-200 rounded-md font-mono text-[11px] text-slate-700"
                  >
                    <span className="text-slate-400 text-[10px]">&#8599;</span>
                    {page}
                  </div>
                ))}
                {!showAllPages && moreCount > 0 && (
                  <button
                    type="button"
                    className="text-[11px] font-semibold text-red-600 px-2.5 py-1 text-left hover:underline"
                    onClick={(e) => { e.stopPropagation(); setShowAllPages(true); }}
                  >
                    +{moreCount} more page{moreCount !== 1 ? "s" : ""}
                  </button>
                )}
              </div>
            )}
          </div>

          {/* Center: Recommended fix or action steps */}
          <div className="flex flex-col gap-3">
            {p.fixCode != null ? (
              <>
                <span className="text-[10px] font-semibold text-slate-500 uppercase tracking-widest">
                  Recommended Fix
                </span>
                <div className="bg-slate-50 border border-slate-200 rounded-lg p-3 flex-1">
                  <pre className="font-mono text-[11.5px] text-slate-700 leading-relaxed overflow-x-auto whitespace-pre-wrap break-words">
                    {p.fixCode}
                  </pre>
                </div>
                {p.fixAction && (
                  <button
                    type="button"
                    className="self-start inline-flex items-center gap-1.5 px-3 py-1.5 bg-white border border-slate-200 rounded-lg text-[12px] font-medium text-slate-700 hover:border-slate-300 hover:bg-slate-50 transition-colors"
                  >
                    {p.fixAction}
                  </button>
                )}
              </>
            ) : p.recommendedNextSteps.length > 0 ? (
              <>
                <span className="text-[10px] font-semibold text-slate-500 uppercase tracking-widest">
                  Recommended Actions
                </span>
                <ol className="flex flex-col gap-2.5">
                  {p.recommendedNextSteps.map((step, i) => (
                    <li key={i} className="flex gap-2.5 text-[12px] text-slate-600 leading-relaxed">
                      <span className="shrink-0 w-4 h-4 mt-0.5 rounded-full bg-slate-100 text-slate-500 text-[10px] font-bold flex items-center justify-center">
                        {i + 1}
                      </span>
                      {step}
                    </li>
                  ))}
                </ol>
              </>
            ) : null}
          </div>

          {/* Right: Impact */}
          {hasImpact && (
            <div className="flex flex-col gap-4">
              <span className="text-[10px] font-semibold text-slate-500 uppercase tracking-widest">
                Impact
              </span>
              {p.scoreLift != null && (
                <div className="flex flex-col gap-0.5">
                  <span className={`text-[28px] font-bold tabular-nums leading-none ${sev.impactColor}`}>
                    +{p.scoreLift}
                  </span>
                  <span className="text-[11px] text-slate-500">health score pts</span>
                </div>
              )}
              {p.affectedPages.length > 0 && (
                <div className="flex flex-col gap-0.5">
                  <span className="text-[24px] font-bold text-slate-700 tabular-nums leading-none">
                    {p.affectedPages.length}
                  </span>
                  <span className="text-[11px] text-slate-500">
                    page{p.affectedPages.length !== 1 ? "s" : ""} affected
                  </span>
                </div>
              )}
              {p.dimension && p.dimension !== "SEO" && (
                <div className="flex flex-col gap-1">
                  <span className="text-[10px] text-slate-400 uppercase tracking-wider">Dimensions</span>
                  <span className="text-[12px] text-slate-600 font-medium">{p.dimension}</span>
                </div>
              )}
            </div>
          )}
        </div>
      )}
    </article>
  );
}

export function PriorityStack({ priorities }: Props) {
  if (priorities.length === 0) {
    return (
      <div className="flex items-center justify-center py-10 text-[13px] text-slate-400">
        No critical or high-priority findings for this brand.
      </div>
    );
  }

  return (
    <div className="flex flex-col gap-3">
      {priorities.map((p, i) => (
        <PriorityCard key={i} p={p} defaultOpen={i === 0} />
      ))}
    </div>
  );
}
