"use client";
import { useState } from "react";
import { Lightbulb, ChevronDown, ChevronRight, Target, Zap, Clock, Wrench } from "lucide-react";
import type { AnalysisRecommendation } from "@/lib/services/analysis-schema";
import { InlineActions } from "./inline-actions";
import { MarkdownContent } from "@/components/shared/MarkdownContent";

// Priority → P1-P4 label + color
const PRIORITY_LABEL: Record<string, string> = {
  critical: "P1",
  high:     "P2",
  medium:   "P3",
  low:      "P4",
};
const PRIORITY_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-blue-700 bg-blue-50 border-blue-200",
  low:      "text-slate-600 bg-slate-50 border-slate-200",
};
const PRIORITY_BORDER: Record<string, string> = {
  critical: "border-l-red-500",
  high:     "border-l-orange-500",
  medium:   "border-l-blue-500",
  low:      "border-l-slate-300",
};

const EFFORT_LABEL: Record<string, string> = {
  low:    "Quick Win",
  medium: "Moderate",
  high:   "Major",
};
const EFFORT_BADGE: Record<string, string> = {
  low:    "text-green-700 bg-green-50 border-green-200",
  medium: "text-amber-700 bg-amber-50 border-amber-200",
  high:   "text-red-700 bg-red-50 border-red-200",
};
const EFFORT_ICON: Record<string, typeof Zap> = {
  low:    Zap,
  medium: Clock,
  high:   Wrench,
};

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 PRIORITY_ORDER: Record<string, number> = { critical: 0, high: 1, medium: 2, low: 3 };

function RecommendationCard({ r, index, brandId }: { r: AnalysisRecommendation; index: number; brandId?: string }) {
  const [stepsOpen, setStepsOpen] = useState(false);
  const priorityLabel = r.priorityLabel ?? PRIORITY_LABEL[r.priority];
  const priorityBadgeCls = PRIORITY_BADGE[r.priority] ?? PRIORITY_BADGE.medium;
  const borderCls = PRIORITY_BORDER[r.priority] ?? PRIORITY_BORDER.medium;
  const effortLabel = r.effortLabel
    ? r.effortLabel.replace("quick-win", "Quick Win").replace("moderate", "Moderate").replace("major", "Major")
    : EFFORT_LABEL[r.effort];
  const effortBadgeCls = EFFORT_BADGE[r.effort] ?? EFFORT_BADGE.medium;
  const EffortIcon = EFFORT_ICON[r.effort] ?? Clock;

  return (
    <div className={`rounded-xl bg-white border border-slate-200 border-l-4 ${borderCls} px-4 py-3.5`}>
      <div className="flex items-start gap-3">
        {/* Priority badge (large P1-P4) */}
        <div className={`w-10 h-10 rounded-lg border flex flex-col items-center justify-center shrink-0 ${priorityBadgeCls}`}>
          <span className="text-[10px] font-bold uppercase tracking-wider leading-none">{priorityLabel}</span>
        </div>

        <div className="flex-1 min-w-0">
          {/* Badges row */}
          <div className="flex items-center gap-1.5 flex-wrap mb-1">
            <span className={`inline-flex items-center gap-1 text-[9px] font-bold uppercase rounded px-1.5 py-0.5 border ${effortBadgeCls}`}>
              <EffortIcon className="w-2.5 h-2.5" />
              {effortLabel}
            </span>
            {r.category && CATEGORY_LABELS[r.category] && (
              <span className={`text-[9px] font-semibold rounded px-1.5 py-0.5 border ${CATEGORY_BADGE[r.category] ?? "text-slate-600 bg-slate-50 border-slate-200"}`}>
                {CATEGORY_LABELS[r.category]}
              </span>
            )}
            {r.relatedFinding && (
              <span className="text-[9px] font-medium text-slate-500 bg-slate-50 border border-slate-100 rounded px-1.5 py-0.5">
                Linked to finding
              </span>
            )}
          </div>

          {/* Title */}
          <p className="text-sm font-bold text-slate-900 leading-tight">
            <span className="text-slate-400 font-semibold mr-1.5">{index}.</span>
            {r.title}
          </p>

          {/* Description */}
          <MarkdownContent className="text-xs text-slate-600 mt-1">{r.description}</MarkdownContent>

          {/* Expected impact */}
          {r.expectedImpact && (
            <div className="flex items-start gap-1.5 mt-2">
              <Target className="w-3 h-3 text-green-600 shrink-0 mt-0.5" />
              <div className="text-[11px] text-green-700">
                <span className="font-semibold">Expected impact: </span>
                <MarkdownContent className="inline text-[11px] text-green-700">{r.expectedImpact}</MarkdownContent>
              </div>
            </div>
          )}

          {/* Collapsible steps */}
          {r.steps && r.steps.length > 0 && (
            <div className="mt-2">
              <button
                type="button"
                onClick={() => setStepsOpen(v => !v)}
                className="flex items-center gap-1 text-[10px] font-bold uppercase tracking-widest text-slate-500 hover:text-brand-600 transition-colors"
              >
                {stepsOpen ? <ChevronDown className="w-3 h-3" /> : <ChevronRight className="w-3 h-3" />}
                {r.steps.length} action step{r.steps.length === 1 ? "" : "s"}
              </button>
              {stepsOpen && (
                <ol className="mt-2 space-y-1.5 rounded-lg bg-slate-50 border border-slate-100 p-3">
                  {r.steps.map((step, si) => (
                    <li key={si} className="flex items-start gap-2 text-[11px] text-slate-600 leading-relaxed">
                      <span className="flex items-center justify-center w-4 h-4 rounded-full bg-white border border-slate-200 text-[9px] font-bold text-slate-500 shrink-0 mt-0.5">
                        {si + 1}
                      </span>
                      <span>{step}</span>
                    </li>
                  ))}
                </ol>
              )}
            </div>
          )}

          {/* Citations */}
          {r.citations && r.citations.length > 0 && (
            <div className="flex items-center gap-1.5 mt-2 flex-wrap">
              {r.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={`rec_${r.relatedFinding ?? index}`}
              title={r.title}
              description={r.description}
              priority={r.priority}
              effort={r.effort}
              evidence={r.expectedImpact}
              actionable={true}
            />
          )}
        </div>
      </div>
    </div>
  );
}

export function RecommendationsSection({ recs, brandId }: { recs: AnalysisRecommendation[]; brandId?: string }) {
  // Sort by priority (critical → low)
  const sorted = [...recs].sort((a, b) =>
    (PRIORITY_ORDER[a.priority] ?? 9) - (PRIORITY_ORDER[b.priority] ?? 9)
  );

  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">
        <Lightbulb className="w-3.5 h-3.5 text-brand-600" />
        <h3 className="text-sm font-bold text-slate-800">Recommendations</h3>
        <span className="ml-auto text-[10px] text-slate-400">{recs.length} · sorted by priority</span>
      </div>
      <div className="p-3 space-y-2.5">
        {sorted.map((r, i) => (
          <RecommendationCard key={i} r={r} index={i + 1} brandId={brandId} />
        ))}
      </div>
    </div>
  );
}
