"use client";

import { useState } from "react";
import { BarChart2, AlertTriangle } from "lucide-react";
import type { CompetitorVisualComparison, VisualComparisonDifference } from "@/lib/audit/types";

interface Props {
  competitorVisualComparison: CompetitorVisualComparison | null | undefined;
}

// ─── Impact badge ─────────────────────────────────────────────────────────────

function impactBadge(impact: VisualComparisonDifference["impact"]): string {
  const map = {
    critical: "bg-red-100 text-red-700 border-red-200",
    high: "bg-orange-100 text-orange-700 border-orange-200",
    moderate: "bg-amber-100 text-amber-700 border-amber-200",
    low: "bg-slate-100 text-slate-600 border-slate-200",
  } as const;
  return map[impact];
}

const CATEGORY_LABEL: Record<VisualComparisonDifference["category"], string> = {
  cta: "CTA",
  social_proof: "Social Proof",
  trust_signals: "Trust Signals",
  content_depth: "Content Depth",
  navigation: "Navigation",
  visual_design: "Visual Design",
};

// ─── Differences table ────────────────────────────────────────────────────────

function DifferencesTable({ differences }: { differences: VisualComparisonDifference[] }) {
  if (differences.length === 0) {
    return <p className="text-sm text-slate-400 italic">No significant structural differences detected.</p>;
  }
  return (
    <div className="border border-slate-200 rounded-xl overflow-hidden">
      <table className="w-full text-xs min-w-[600px]">
        <thead className="bg-slate-50 border-b border-slate-100">
          <tr>
            <th className="px-3 py-2 text-left font-semibold text-slate-500">#</th>
            <th className="px-3 py-2 text-left font-semibold text-slate-500">Category</th>
            <th className="px-3 py-2 text-left font-semibold text-slate-500">Brand</th>
            <th className="px-3 py-2 text-left font-semibold text-slate-500">Competitor</th>
            <th className="px-3 py-2 text-left font-semibold text-slate-500">Impact</th>
          </tr>
        </thead>
        <tbody>
          {differences.map((d, i) => (
            <tr key={i} className={i % 2 === 1 ? "bg-slate-50" : "bg-white"}>
              <td className="px-3 py-2.5 font-bold text-slate-500">{d.number}</td>
              <td className="px-3 py-2.5">
                <span className="text-xs font-medium text-slate-600">{CATEGORY_LABEL[d.category]}</span>
              </td>
              <td className="px-3 py-2.5 text-slate-600 max-w-[180px]">{d.brandObservation}</td>
              <td className="px-3 py-2.5 text-slate-800 max-w-[180px] font-medium">{d.competitorObservation}</td>
              <td className="px-3 py-2.5">
                <span className={`text-xs px-1.5 py-0.5 rounded-full font-medium border ${impactBadge(d.impact)}`}>
                  {d.impact}
                </span>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

// ─── Competitor panel ─────────────────────────────────────────────────────────

function CompetitorPanel({ comp }: { comp: CompetitorVisualComparison["comparisons"][0] }) {
  const hp = comp.homepageComparison;

  return (
    <div className="space-y-4">
      <p className="text-sm text-slate-600 leading-relaxed">{comp.summaryNarrative}</p>

      {/* Side-by-side or two-column */}
      {hp.sideBySideUrl ? (
        <div>
          <div className="text-xs font-semibold text-slate-500 mb-1.5">Homepage Comparison</div>
          <a href={hp.sideBySideUrl} target="_blank" rel="noopener noreferrer">
            <img
              src={hp.sideBySideUrl}
              alt={`Side-by-side comparison with ${comp.competitorName}`}
              className="w-full rounded-xl border border-slate-200 hover:shadow-lg transition-shadow"
            />
          </a>
        </div>
      ) : hp.brandScreenshotUrl && hp.competitorScreenshotUrl ? (
        <div className="grid grid-cols-2 gap-3">
          <div>
            <div className="text-xs font-semibold text-slate-500 mb-1.5">Your Site</div>
            <img src={hp.brandScreenshotUrl} alt="Your homepage" className="w-full rounded-xl border border-slate-200" />
          </div>
          <div>
            <div className="text-xs font-semibold text-slate-500 mb-1.5">{comp.competitorName}</div>
            <img src={hp.competitorScreenshotUrl} alt={`${comp.competitorName} homepage`} className="w-full rounded-xl border border-slate-200" />
          </div>
        </div>
      ) : null}

      <DifferencesTable differences={hp.differences} />
    </div>
  );
}

// ─── Main section ─────────────────────────────────────────────────────────────

export function CompetitorVisualComparisonSection({ competitorVisualComparison }: Props) {
  const [activeTab, setActiveTab] = useState(0);

  if (!competitorVisualComparison?.hasComparison) return null;

  const cvc = competitorVisualComparison;
  const captureDate = new Date(cvc.windowDate).toLocaleDateString("en-US", {
    month: "short", day: "numeric", year: "numeric",
  });

  const totalDiffs = cvc.comparisons.reduce(
    (sum, c) => sum + c.homepageComparison.differences.length, 0,
  );

  return (
    <section id="audit-competitor-visual-comparison" className="space-y-5">
      {/* Header */}
      <div className="flex items-start gap-3">
        <div>
          <div className="flex items-center gap-2 mb-1">
            <BarChart2 size={18} className="text-violet-600" />
            <h2 className="text-xl font-bold text-slate-900">Side-by-Side Competitor Visual Comparison</h2>
          </div>
          <p className="text-sm text-slate-500">
            Your site vs {cvc.comparisons.length} competitor{cvc.comparisons.length !== 1 ? "s" : ""} — {totalDiffs} structural differences highlighted — {captureDate}
          </p>
        </div>
      </div>

      {/* Top difference categories */}
      {cvc.topDifferenceCategories.length > 0 && (
        <div className="bg-violet-50 border border-violet-200 rounded-xl p-4 space-y-2">
          <div className="flex items-center gap-1.5">
            <AlertTriangle size={13} className="text-violet-600" />
            <span className="text-xs font-semibold text-violet-700">Most Common Gaps Across Competitors</span>
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
            {cvc.topDifferenceCategories.map((cat, i) => (
              <div key={i} className="flex items-start gap-2">
                <span className="text-xs font-bold text-violet-600 flex-shrink-0 mt-0.5">{cat.occurrenceCount}×</span>
                <div>
                  <div className="text-xs font-semibold text-slate-700">{cat.category}</div>
                  <div className="text-xs text-slate-500">{cat.summary}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Competitor tabs */}
      {cvc.comparisons.length > 1 && (
        <div className="flex gap-2 border-b border-slate-200">
          {cvc.comparisons.map((comp, i) => (
            <button
              key={i}
              onClick={() => setActiveTab(i)}
              className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors capitalize ${
                activeTab === i
                  ? "border-violet-500 text-violet-700"
                  : "border-transparent text-slate-500 hover:text-slate-700"
              }`}
            >
              vs {comp.competitorName}
            </button>
          ))}
        </div>
      )}

      {/* Active competitor */}
      {cvc.comparisons[activeTab] && (
        <CompetitorPanel comp={cvc.comparisons[activeTab]!} />
      )}

      {/* Patent relevance */}
      <p className="text-xs text-slate-400 italic">{cvc.patentRelevance}</p>
    </section>
  );
}
