"use client";

import { useState } from "react";
import { ChevronDown, ChevronUp } from "lucide-react";
import type { SeoKeyFinding, PrioritizedFinding, AdditionalFinding, BehavioralOverlay } from "@/lib/audit/types";

interface Props {
  keyFindings: SeoKeyFinding[];
  prioritizedFindings?: PrioritizedFinding[];
  additionalFindings?: AdditionalFinding[];
  showLockedBehavioral?: boolean;
}

type PriorityFilter = "all" | "critical" | "high" | "medium" | "low";

const PRIORITY_COLORS = {
  critical: { bg: "bg-red-50", text: "text-red-700", border: "border-red-200", strip: "bg-red-500" },
  high: { bg: "bg-orange-50", text: "text-orange-700", border: "border-orange-200", strip: "bg-orange-500" },
  medium: { bg: "bg-amber-50", text: "text-amber-700", border: "border-amber-200", strip: "bg-amber-400" },
  low: { bg: "bg-slate-50", text: "text-slate-600", border: "border-slate-200", strip: "bg-slate-400" },
};

function fmtDuration(s: number): string {
  if (s < 60) return `${Math.round(s)}s`;
  const m = Math.floor(s / 60);
  const sec = Math.round(s % 60);
  return sec > 0 ? `${m}m ${sec}s` : `${m}m`;
}

function BehavioralStrip({ overlay }: { overlay: BehavioralOverlay }) {
  const metrics: Array<{ label: string; value: string; accent?: boolean }> = [];
  if (overlay.bounceRate != null)
    metrics.push({ label: "Bounce Rate", value: `${(overlay.bounceRate * 100).toFixed(0)}%` });
  if (overlay.avgSessionDuration != null)
    metrics.push({ label: "Avg Session", value: fmtDuration(overlay.avgSessionDuration) });
  if (overlay.conversions > 0)
    metrics.push({ label: "Conversions", value: String(overlay.conversions) });
  if (overlay.estimatedLostConversionValue > 0)
    metrics.push({ label: "Est. Lost Value", value: `$${overlay.estimatedLostConversionValue.toFixed(0)}`, accent: true });
  if (metrics.length === 0) return null;
  return (
    <div className="mt-4 pt-3 border-t border-slate-100 grid grid-cols-2 sm:grid-cols-4 gap-3">
      {metrics.map(({ label, value, accent }) => (
        <div key={label}>
          <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-0.5">{label}</p>
          <p className={`text-sm font-bold leading-none ${accent ? "text-amber-600" : "text-slate-800"}`}>{value}</p>
        </div>
      ))}
    </div>
  );
}

function ExpandableFinding({ finding, defaultOpen }: { finding: PrioritizedFinding; defaultOpen?: boolean }) {
  const [open, setOpen] = useState(defaultOpen ?? false);
  const p = finding.priority.toLowerCase() as keyof typeof PRIORITY_COLORS;
  const colors = PRIORITY_COLORS[p] ?? PRIORITY_COLORS.low;

  return (
    <div className="flex" style={{ marginBottom: 10 }}>
      <div className={`w-1 rounded-l-sm shrink-0 ${colors.strip}`} />
      <div className="flex-1 border border-l-0 border-slate-200 rounded-r-xl bg-white overflow-hidden">
        <button
          onClick={() => setOpen((o) => !o)}
          className="w-full flex items-start gap-3 p-4 text-left hover:bg-slate-50/60 transition-colors"
        >
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 flex-wrap mb-1">
              <span className={`text-[10px] font-bold uppercase tracking-wider px-2 py-0.5 rounded border ${colors.bg} ${colors.text} ${colors.border}`}>
                {finding.priority}
              </span>
              {finding.rank && (
                <span className="text-[10px] text-slate-400 font-mono">#{finding.rank}</span>
              )}
            </div>
            <p className="text-sm font-semibold text-slate-900 leading-snug">{finding.title}</p>
            {!open && (
              <p className="text-xs text-slate-500 mt-1 leading-relaxed line-clamp-2">
                {finding.whereItFallsShort}
              </p>
            )}
          </div>
          <div className="shrink-0 mt-0.5 text-slate-400">
            {open ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
          </div>
        </button>

        {open && (
          <div className="px-4 pb-4 space-y-4 border-t border-slate-100">
            {finding.whatsWorking && (
              <div className="mt-4">
                <p className="text-[10px] font-semibold uppercase tracking-widest text-green-600 mb-1.5">
                  What&apos;s Working
                </p>
                <p className="text-sm text-slate-700 leading-relaxed">{finding.whatsWorking}</p>
              </div>
            )}
            <div>
              <p className="text-[10px] font-semibold uppercase tracking-widest text-red-600 mb-1.5">
                Gap
              </p>
              <p className="text-sm text-slate-700 leading-relaxed">{finding.whereItFallsShort}</p>
            </div>
            {finding.recommendedNextSteps && finding.recommendedNextSteps.length > 0 && (
              <div>
                <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-2">
                  Next Steps
                </p>
                <ol className="space-y-2">
                  {finding.recommendedNextSteps.map((step, i) => (
                    <li key={i} className="flex gap-2.5 text-sm text-slate-700">
                      <span className="text-indigo-500 font-bold shrink-0 w-4">{i + 1}.</span>
                      <span className="leading-relaxed">{step}</span>
                    </li>
                  ))}
                </ol>
              </div>
            )}
            {finding.affectedUrls && finding.affectedUrls.length > 0 && (
              <div className="pt-3 border-t border-slate-100">
                <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-2">
                  Affected URLs
                </p>
                <div className="space-y-1">
                  {finding.affectedUrls.slice(0, 5).map((url, i) => (
                    <p key={i} className="text-xs font-mono text-indigo-600 truncate">{url}</p>
                  ))}
                  {finding.affectedUrls.length > 5 && (
                    <p className="text-xs text-slate-400">…and {finding.affectedUrls.length - 5} more</p>
                  )}
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

function AdditionalFindingsAccordion({ findings }: { findings: AdditionalFinding[] }) {
  const [open, setOpen] = useState(false);

  return (
    <div className="mt-4 border border-slate-200 rounded-xl overflow-hidden">
      <button
        onClick={() => setOpen((o) => !o)}
        className="w-full flex items-center justify-between px-5 py-3.5 bg-slate-50 hover:bg-slate-100 transition-colors"
      >
        <span className="text-sm font-medium text-slate-700">
          {findings.length} Additional Findings
        </span>
        {open ? <ChevronUp className="w-4 h-4 text-slate-500" /> : <ChevronDown className="w-4 h-4 text-slate-500" />}
      </button>
      {open && (
        <div className="divide-y divide-slate-100">
          {findings.map((f, i) => (
            <div key={i} className="px-5 py-4">
              <p className="text-sm font-semibold text-slate-800 mb-1">{f.title}</p>
              <p className="text-sm text-slate-600 leading-relaxed">{f.assessment}</p>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

const FILTERS: Array<{ value: PriorityFilter; label: string }> = [
  { value: "all", label: "All" },
  { value: "critical", label: "Critical" },
  { value: "high", label: "High" },
  { value: "medium", label: "Medium" },
  { value: "low", label: "Low" },
];

export function KeyFindingsSection({ keyFindings, prioritizedFindings, additionalFindings, showLockedBehavioral }: Props) {
  const [filter, setFilter] = useState<PriorityFilter>("all");
  const useDetailed = prioritizedFindings && prioritizedFindings.length > 0;

  const filteredFindings = useDetailed
    ? prioritizedFindings!.filter(
        (f) => filter === "all" || f.priority.toLowerCase() === filter
      )
    : [];

  return (
    <div id="audit-key-findings" className="bg-white rounded-2xl border border-slate-200 p-6 sm:p-8">
      <div className="flex items-center justify-between gap-4 mb-2 flex-wrap">
        <div>
          <h2 className="text-[11px] font-semibold uppercase tracking-widest text-slate-400">
            Key Findings
          </h2>
          <p className="text-xs text-slate-400 mt-1">Prioritized by business impact</p>
        </div>
        {useDetailed && (
          <div className="flex gap-1 flex-wrap">
            {FILTERS.map(({ value, label }) => (
              <button
                key={value}
                onClick={() => setFilter(value)}
                className={`px-3 py-1 rounded-full text-xs font-medium transition-colors ${
                  filter === value
                    ? "bg-slate-900 text-white"
                    : "bg-slate-100 text-slate-600 hover:bg-slate-200"
                }`}
              >
                {label}
              </button>
            ))}
          </div>
        )}
      </div>

      <div className="mt-5">
        {useDetailed ? (
          <>
            {filteredFindings.length === 0 ? (
              <p className="text-sm text-slate-400 text-center py-8">
                No {filter} findings.
              </p>
            ) : (
              filteredFindings.map((f, i) => (
                <ExpandableFinding key={i} finding={f} defaultOpen={i === 0 && f.priority === "critical"} />
              ))
            )}
          </>
        ) : (
          <div className="grid sm:grid-cols-2 gap-4">
            {keyFindings.map((f, i) => (
              <div
                key={i}
                className="border border-slate-100 rounded-xl p-5 bg-slate-50/60 hover:shadow-md hover:-translate-y-0.5 transition-[box-shadow,transform] duration-150"
              >
                <p className="text-[15px] font-semibold text-slate-900 leading-snug">{f.title}</p>
                <p className="text-sm text-slate-600 mt-2 leading-relaxed">{f.detail}</p>
                {f.behavioralOverlay && <BehavioralStrip overlay={f.behavioralOverlay} />}
                {showLockedBehavioral && !f.behavioralOverlay && <LockedBehavioralPlaceholder />}
              </div>
            ))}
          </div>
        )}
      </div>

      {additionalFindings && additionalFindings.length > 0 && (
        <AdditionalFindingsAccordion findings={additionalFindings} />
      )}
    </div>
  );
}

function LockedBehavioralPlaceholder() {
  return (
    <div className="mt-4 pt-3 border-t border-slate-100 grid grid-cols-2 gap-3">
      {["Bounce Rate", "Avg Session", "Conversions", "Lost Value"].map((label) => (
        <div key={label}>
          <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-1">{label}</p>
          <div className="h-3.5 w-12 bg-slate-100 rounded animate-pulse" />
        </div>
      ))}
    </div>
  );
}
