"use client";
import { useState } from "react";
import { AlertCircle, AlertTriangle, TrendingUp, Info, Lightbulb, ChevronDown, ChevronUp, Zap } from "lucide-react";
import type { Finding } from "@/lib/services/analysis-schema";
import { InlineActions } from "./inline-actions";
import { MarkdownContent } from "@/components/shared/MarkdownContent";

const ICON_MAP: Record<string, typeof AlertCircle> = {
  anomaly: AlertCircle, risk: AlertTriangle, trend: TrendingUp, insight: Info, opportunity: Lightbulb,
};

// Severity → left border + badge color
const SEVERITY_BORDER: Record<string, string> = {
  critical: "border-l-red-500",
  high:     "border-l-orange-500",
  medium:   "border-l-amber-500",
  low:      "border-l-blue-500",
  info:     "border-l-slate-300",
};
const SEVERITY_BADGE: Record<string, string> = {
  critical: "text-red-700 bg-red-50 border-red-200",
  high:     "text-orange-700 bg-orange-50 border-orange-200",
  medium:   "text-amber-700 bg-amber-50 border-amber-200",
  low:      "text-blue-700 bg-blue-50 border-blue-200",
  info:     "text-slate-600 bg-slate-50 border-slate-200",
};
const SEVERITY_ICON_BG: Record<string, string> = {
  critical: "text-red-600 bg-red-50 border-red-200",
  high:     "text-orange-600 bg-orange-50 border-orange-200",
  medium:   "text-amber-600 bg-amber-50 border-amber-200",
  low:      "text-blue-600 bg-blue-50 border-blue-200",
  info:     "text-slate-500 bg-slate-50 border-slate-200",
};

const IMPACT_BADGE: Record<string, string> = {
  high:   "text-red-700 bg-red-50 border-red-200",
  medium: "text-amber-700 bg-amber-50 border-amber-200",
  low:    "text-blue-700 bg-blue-50 border-blue-200",
};

const CATEGORY_LABELS: Record<string, string> = {
  performance: "Performance",
  technical:   "Technical",
  content:     "Content",
  competitive: "Competitive",
  opportunity: "Opportunity",
};
const CATEGORY_BADGE: Record<string, string> = {
  performance: "text-purple-700 bg-purple-50 border-purple-200",
  technical:   "text-blue-700 bg-blue-50 border-blue-200",
  content:     "text-emerald-700 bg-emerald-50 border-emerald-200",
  competitive: "text-amber-700 bg-amber-50 border-amber-200",
  opportunity: "text-green-700 bg-green-50 border-green-200",
};

const SEVERITY_ORDER: Record<string, number> = {
  critical: 0, high: 1, medium: 2, low: 3, info: 4,
};

function FindingCard({ f, brandId }: { f: Finding; brandId?: string }) {
  const Icon = ICON_MAP[f.type] ?? Info;
  const isActionable = f.type !== "insight" || f.severity !== "info";
  const borderCls = SEVERITY_BORDER[f.severity] ?? SEVERITY_BORDER.info;
  const badgeCls = SEVERITY_BADGE[f.severity] ?? SEVERITY_BADGE.info;
  const iconCls = SEVERITY_ICON_BG[f.severity] ?? SEVERITY_ICON_BG.info;

  return (
    <div className={`rounded-xl bg-white border border-slate-200 border-l-4 ${borderCls} px-4 py-3.5`}>
      {/* Top row: icon + badges */}
      <div className="flex items-start gap-3">
        <div className={`w-8 h-8 rounded-lg border flex items-center justify-center shrink-0 ${iconCls}`}>
          <Icon className="w-4 h-4" />
        </div>
        <div className="flex-1 min-w-0">
          {/* Badges row */}
          <div className="flex items-center gap-1.5 flex-wrap mb-1">
            <span className={`text-[9px] font-bold uppercase rounded px-1.5 py-0.5 border ${badgeCls}`}>
              {f.severity}
            </span>
            {f.category && CATEGORY_LABELS[f.category] && (
              <span className={`text-[9px] font-semibold rounded px-1.5 py-0.5 border ${CATEGORY_BADGE[f.category] ?? "text-slate-600 bg-slate-50 border-slate-200"}`}>
                {CATEGORY_LABELS[f.category]}
              </span>
            )}
            {f.impactLevel && (
              <span className={`text-[9px] font-bold uppercase rounded px-1.5 py-0.5 border ${IMPACT_BADGE[f.impactLevel] ?? IMPACT_BADGE.medium}`}>
                {f.impactLevel} impact
              </span>
            )}
            {f.affectedMetric && (
              <span className="text-[9px] font-medium text-slate-500 bg-slate-50 border border-slate-100 rounded px-1.5 py-0.5">
                {f.affectedMetric}
              </span>
            )}
          </div>
          {/* Title */}
          <p className="text-sm font-bold text-slate-900 leading-tight">{f.title}</p>
          {/* Description */}
          <MarkdownContent className="text-xs text-slate-600 mt-1">{f.description}</MarkdownContent>

          {/* Evidence (code-like display — monospace data, not rendered markdown) */}
          {f.evidence && (
            <p className="text-[10px] text-slate-500 mt-2 font-mono bg-slate-50 rounded px-2 py-1.5 border border-slate-100">
              {f.evidence}
            </p>
          )}

          {/* Impact statement */}
          {f.impact && (
            <div className="text-[11px] text-amber-700 mt-1.5">
              <span className="font-semibold">Impact: </span>
              <MarkdownContent className="inline text-[11px] text-amber-700">{f.impact}</MarkdownContent>
            </div>
          )}

          {/* Recommended action callout */}
          {f.recommendedAction && (
            <div className="mt-2 flex items-start gap-2 rounded-lg bg-brand-50/60 border border-brand-100 px-3 py-2">
              <Zap className="w-3 h-3 text-brand-600 shrink-0 mt-0.5" />
              <div className="min-w-0">
                <p className="text-[10px] font-bold uppercase tracking-widest text-brand-600">Recommended Action</p>
                <MarkdownContent className="text-[11px] text-slate-700 mt-0.5">{f.recommendedAction}</MarkdownContent>
              </div>
            </div>
          )}

          {/* Citations */}
          {f.citations && f.citations.length > 0 && (
            <div className="flex items-center gap-1.5 mt-2 flex-wrap">
              {f.citations.map(c => (
                c.url ? (
                  <a key={c.evidenceId} href={c.url} target="_blank" rel="noopener noreferrer"
                    className="text-[9px] font-semibold text-brand-600 bg-brand-50 border border-brand-200 rounded px-1.5 py-0.5 hover:bg-brand-100 transition-colors">
                    {c.label}
                  </a>
                ) : (
                  <span key={c.evidenceId} className="text-[9px] font-semibold text-slate-500 bg-slate-50 border border-slate-200 rounded px-1.5 py-0.5">
                    {c.label}
                  </span>
                )
              ))}
            </div>
          )}

          {brandId && (
            <InlineActions
              brandId={brandId}
              itemId={`finding_${f.id}`}
              title={f.title}
              description={f.description}
              priority={f.severity === "info" ? "low" : f.severity}
              evidence={f.evidence}
              actionable={isActionable}
            />
          )}
        </div>
      </div>
    </div>
  );
}

export function FindingsSection({ findings, brandId }: { findings: Finding[]; brandId?: string }) {
  const [expanded, setExpanded] = useState(false);

  // Sort by severity (critical first)
  const sorted = [...findings].sort((a, b) =>
    (SEVERITY_ORDER[a.severity] ?? 9) - (SEVERITY_ORDER[b.severity] ?? 9)
  );

  const visibleFindings = expanded || sorted.length <= 5 ? sorted : sorted.slice(0, 5);
  const hiddenCount = sorted.length - visibleFindings.length;

  const counts = {
    critical: findings.filter(f => f.severity === "critical").length,
    high:     findings.filter(f => f.severity === "high").length,
    medium:   findings.filter(f => f.severity === "medium").length,
  };

  return (
    <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
      <div className="px-4 py-3 border-b border-slate-100 flex items-center gap-2 flex-wrap">
        <AlertCircle className="w-3.5 h-3.5 text-red-500" />
        <h3 className="text-sm font-bold text-slate-800">Findings</h3>
        <div className="ml-auto flex items-center gap-1.5 flex-wrap">
          {counts.critical > 0 && (
            <span className="text-[9px] font-bold bg-red-50 text-red-600 border border-red-200 rounded px-1.5 py-0.5">
              {counts.critical} critical
            </span>
          )}
          {counts.high > 0 && (
            <span className="text-[9px] font-bold bg-orange-50 text-orange-600 border border-orange-200 rounded px-1.5 py-0.5">
              {counts.high} high
            </span>
          )}
          {counts.medium > 0 && (
            <span className="text-[9px] font-bold bg-amber-50 text-amber-600 border border-amber-200 rounded px-1.5 py-0.5">
              {counts.medium} medium
            </span>
          )}
          <span className="text-[10px] text-slate-400">{findings.length} total</span>
        </div>
      </div>
      <div className="p-3 space-y-2.5">
        {visibleFindings.map(f => <FindingCard key={f.id} f={f} brandId={brandId} />)}
      </div>
      {hiddenCount > 0 && (
        <button
          type="button"
          onClick={() => setExpanded(true)}
          className="w-full px-4 py-2.5 border-t border-slate-100 text-[11px] font-semibold text-brand-600 hover:bg-slate-50 transition-colors flex items-center justify-center gap-1"
        >
          <ChevronDown className="w-3 h-3" />
          Show {hiddenCount} more finding{hiddenCount === 1 ? "" : "s"}
        </button>
      )}
      {expanded && sorted.length > 5 && (
        <button
          type="button"
          onClick={() => setExpanded(false)}
          className="w-full px-4 py-2.5 border-t border-slate-100 text-[11px] font-semibold text-slate-500 hover:bg-slate-50 transition-colors flex items-center justify-center gap-1"
        >
          <ChevronUp className="w-3 h-3" />
          Collapse
        </button>
      )}
    </div>
  );
}
