"use client";

import type { PageSpeedInsights, CoreWebVital, WebVitalGrade } from "@/lib/page-speed/types";

interface Props {
  pageSpeedInsights: PageSpeedInsights | null | undefined;
}

const TIER_CONFIG: Record<
  PageSpeedInsights["overallScoreTier"],
  { label: string; scoreClass: string; badgeClass: string; barClass: string }
> = {
  excellent: {
    label: "Excellent",
    scoreClass: "text-emerald-400",
    badgeClass: "bg-emerald-500/20 text-emerald-400 border border-emerald-500/30",
    barClass: "bg-emerald-500",
  },
  good: {
    label: "Good",
    scoreClass: "text-blue-400",
    badgeClass: "bg-blue-500/20 text-blue-400 border border-blue-500/30",
    barClass: "bg-blue-500",
  },
  needs_improvement: {
    label: "Needs Improvement",
    scoreClass: "text-amber-400",
    badgeClass: "bg-amber-500/20 text-amber-400 border border-amber-500/30",
    barClass: "bg-amber-500",
  },
  poor: {
    label: "Poor",
    scoreClass: "text-red-400",
    badgeClass: "bg-red-500/20 text-red-400 border border-red-500/30",
    barClass: "bg-red-500",
  },
};

const GRADE_CONFIG: Record<WebVitalGrade, { label: string; class: string }> = {
  good: { label: "Good", class: "text-emerald-400 bg-emerald-500/10 border-emerald-500/30" },
  needs_improvement: { label: "Needs Improvement", class: "text-amber-400 bg-amber-500/10 border-amber-500/30" },
  poor: { label: "Poor", class: "text-red-400 bg-red-500/10 border-red-500/30" },
};

function VitalCard({ vital }: { vital: CoreWebVital }) {
  const grade = vital.fieldGrade ?? vital.labGrade;
  const value = vital.fieldValue ?? vital.labValue;
  const gradeCfg = grade ? GRADE_CONFIG[grade] : null;
  const displayValue =
    value != null
      ? vital.unit === "score"
        ? value.toFixed(2)
        : vital.unit === "s"
          ? `${(value / 1000).toFixed(1)}s`
          : `${Math.round(value)}ms`
      : "N/A";

  return (
    <div className={`rounded-xl border p-4 space-y-2 ${gradeCfg ? `${gradeCfg.class} border` : "bg-slate-800/60 border-slate-700/50"}`}>
      <div className="flex items-center justify-between gap-2">
        <span className="text-xs font-bold text-slate-300 uppercase tracking-wide">{vital.metric}</span>
        {gradeCfg && (
          <span className="text-xs font-medium">{gradeCfg.label}</span>
        )}
      </div>
      <p className="text-2xl font-black text-white">{displayValue}</p>
      <p className="text-xs text-slate-400 leading-snug">{vital.displayName}</p>
    </div>
  );
}

function formatBytes(bytes: number): string {
  if (bytes >= 1_048_576) return `${(bytes / 1_048_576).toFixed(1)} MB`;
  if (bytes >= 1024) return `${Math.round(bytes / 1024)} KB`;
  return `${bytes} B`;
}

function truncateUrl(url: string, max = 60): string {
  try {
    const parsed = new URL(url);
    const short = parsed.pathname + (parsed.search ? "?" + parsed.search.slice(1, 30) : "");
    return short.length > max ? short.slice(0, max) + "..." : short;
  } catch {
    return url.length > max ? url.slice(0, max) + "..." : url;
  }
}

export default function PageSpeedInsightsDeepDiveSection({ pageSpeedInsights }: Props) {
  if (!pageSpeedInsights?.hasInsights || pageSpeedInsights.perPageAnalyses.length === 0) {
    return null;
  }

  const tierCfg = TIER_CONFIG[pageSpeedInsights.overallScoreTier];
  const hasRevenueLoss = pageSpeedInsights.estimatedMonthlyRevenueLoss > 0;

  return (
    <section className="space-y-6">
      {/* Revenue impact hero */}
      <div className="rounded-2xl bg-slate-800/50 border border-slate-700/50 p-6">
        <div className="flex flex-col sm:flex-row sm:items-start justify-between gap-6">
          <div className="space-y-2">
            <div className="flex items-center gap-3">
              <span className={`text-xs font-semibold px-2.5 py-1 rounded-full ${tierCfg.badgeClass}`}>
                {tierCfg.label}
              </span>
            </div>
            <h3 className="text-lg font-bold text-white">Page Load Performance Analysis</h3>
            <p className="text-sm text-slate-400">
              {pageSpeedInsights.pagesAnalyzed} page{pageSpeedInsights.pagesAnalyzed !== 1 ? "s" : ""} analyzed
            </p>
          </div>
          {hasRevenueLoss && (
            <div className="rounded-xl bg-red-500/10 border border-red-500/20 p-4 text-center min-w-[160px]">
              <p className="text-xs text-red-400 font-semibold uppercase tracking-wide mb-1">
                Est. Monthly Revenue Impact
              </p>
              <p className="text-3xl font-black text-red-300">
                ${pageSpeedInsights.estimatedMonthlyRevenueLoss.toLocaleString()}
              </p>
              <p className="text-xs text-slate-500 mt-1">
                ~{pageSpeedInsights.estimatedMonthlyTrafficLoss.toLocaleString()} sessions / mo
              </p>
            </div>
          )}
        </div>
      </div>

      {/* Aggregate CWV grid */}
      <div className="space-y-3">
        <h4 className="text-sm font-semibold text-slate-300 uppercase tracking-wide">
          Core Vitals Summary
        </h4>
        <div className="grid gap-3 sm:grid-cols-5">
          {(["LCP", "INP", "CLS", "FCP", "TTFB"] as const).map((metric) => {
            const grade = pageSpeedInsights.aggregateCwvGrades[metric];
            const gradeCfg = grade ? GRADE_CONFIG[grade] : null;
            return (
              <div
                key={metric}
                className={`rounded-xl border p-3 text-center ${gradeCfg ? `${gradeCfg.class} border` : "bg-slate-800/60 border-slate-700/50"}`}
              >
                <p className="text-xs font-bold text-slate-300 uppercase">{metric}</p>
                <p className={`text-sm font-semibold mt-1 ${gradeCfg ? "" : "text-slate-400"}`}>
                  {grade ? GRADE_CONFIG[grade].label : "N/A"}
                </p>
              </div>
            );
          })}
        </div>
      </div>

      {/* Per-page tabs */}
      <div className="space-y-3">
        <h4 className="text-sm font-semibold text-slate-300 uppercase tracking-wide">
          Per-Page Breakdown
        </h4>
        {pageSpeedInsights.perPageAnalyses.map((analysis, idx) => {
          const pageTierKey: PageSpeedInsights["overallScoreTier"] =
            analysis.overallScore >= 90
              ? "excellent"
              : analysis.overallScore >= 70
                ? "good"
                : analysis.overallScore >= 50
                  ? "needs_improvement"
                  : "poor";
          const pageTierCfg = TIER_CONFIG[pageTierKey];
          return (
            <details key={analysis.pageUrl} open={idx === 0} className="rounded-2xl bg-slate-800/50 border border-slate-700/50 overflow-hidden">
              <summary className="flex items-center justify-between cursor-pointer p-5 list-none select-none hover:bg-slate-700/20 transition-colors">
                <div className="flex items-center gap-3">
                  <span className="text-sm font-semibold text-slate-200">{analysis.pageLabel}</span>
                  <span className="text-xs text-slate-500 truncate max-w-[200px] hidden sm:block">
                    {truncateUrl(analysis.pageUrl)}
                  </span>
                </div>
                <span className={`text-sm font-bold ${pageTierCfg.scoreClass}`}>
                  {analysis.overallScore}/100
                </span>
              </summary>

              <div className="px-5 pb-5 space-y-4 border-t border-slate-700/40 pt-4">
                {/* 5 vital cards */}
                <div className="grid gap-2 grid-cols-2 sm:grid-cols-5">
                  {analysis.coreWebVitals.map((vital) => (
                    <VitalCard key={vital.metric} vital={vital} />
                  ))}
                </div>

                {/* Render-blocking resources */}
                {analysis.renderBlockingResources.length > 0 && (
                  <div className="space-y-2">
                    <p className="text-xs font-semibold text-slate-400 uppercase tracking-wide">
                      Render-Blocking Resources
                    </p>
                    <div className="rounded-xl overflow-hidden border border-slate-700/40">
                      <table className="w-full text-xs">
                        <thead>
                          <tr className="bg-slate-900/40">
                            <th className="text-left p-2 text-slate-500 font-medium">Resource</th>
                            <th className="text-left p-2 text-slate-500 font-medium">Type</th>
                            <th className="text-right p-2 text-slate-500 font-medium">Delay (ms)</th>
                          </tr>
                        </thead>
                        <tbody>
                          {analysis.renderBlockingResources.slice(0, 5).map((r, i) => (
                            <tr key={i} className="border-t border-slate-700/30">
                              <td className="p-2 text-slate-300 font-mono truncate max-w-[220px]">
                                {truncateUrl(r.url, 50)}
                              </td>
                              <td className="p-2 text-slate-400 capitalize">{r.resourceType}</td>
                              <td className="p-2 text-right text-amber-400 font-medium">
                                {r.wastedMs > 0 ? r.wastedMs.toLocaleString() : "—"}
                              </td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  </div>
                )}

                {/* Image opportunities */}
                {analysis.imageOpportunities.length > 0 && (
                  <div className="space-y-2">
                    <p className="text-xs font-semibold text-slate-400 uppercase tracking-wide">
                      Image Optimization Opportunities
                    </p>
                    <div className="space-y-2">
                      {analysis.imageOpportunities.slice(0, 3).map((opp, i) => (
                        <div
                          key={i}
                          className="flex items-center justify-between gap-3 rounded-lg bg-slate-900/40 border border-slate-700/30 p-2.5"
                        >
                          <div className="min-w-0">
                            <p className="text-xs text-slate-400 font-mono truncate">{truncateUrl(opp.url, 50)}</p>
                            <p className="text-xs text-slate-500 mt-0.5">{opp.issue}</p>
                          </div>
                          <span className="flex-shrink-0 text-xs font-semibold text-orange-400">
                            {formatBytes(opp.wastedBytes)}
                          </span>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* Top opportunities */}
                {analysis.topOpportunities.length > 0 && (
                  <div className="space-y-2">
                    <p className="text-xs font-semibold text-slate-400 uppercase tracking-wide">
                      Additional Opportunities
                    </p>
                    <ul className="space-y-1.5">
                      {analysis.topOpportunities.slice(0, 3).map((opp, i) => (
                        <li key={i} className="flex gap-2 text-xs text-slate-300">
                          <span className="text-blue-400 flex-shrink-0 mt-0.5">--</span>
                          <span>
                            <span className="font-medium">{opp.title}</span>
                            {opp.description && (
                              <span className="text-slate-400 ml-1">{opp.description}</span>
                            )}
                          </span>
                        </li>
                      ))}
                    </ul>
                  </div>
                )}
              </div>
            </details>
          );
        })}
      </div>

      {/* Top render-blocking resources (cross-page) */}
      {pageSpeedInsights.topRenderBlockingResources.length > 0 && (
        <div className="rounded-2xl bg-slate-800/50 border border-slate-700/50 p-5 space-y-3">
          <h4 className="text-sm font-semibold text-slate-300 uppercase tracking-wide">
            Top Render-Blocking Resources (All Pages)
          </h4>
          <div className="rounded-xl overflow-hidden border border-slate-700/40">
            <table className="w-full text-xs">
              <thead>
                <tr className="bg-slate-900/40">
                  <th className="text-left p-2 text-slate-500 font-medium">Resource</th>
                  <th className="text-left p-2 text-slate-500 font-medium">Type</th>
                  <th className="text-right p-2 text-slate-500 font-medium">Max Delay (ms)</th>
                </tr>
              </thead>
              <tbody>
                {pageSpeedInsights.topRenderBlockingResources.slice(0, 6).map((r, i) => (
                  <tr key={i} className="border-t border-slate-700/30">
                    <td className="p-2 text-slate-300 font-mono truncate max-w-[260px]">
                      {truncateUrl(r.url, 60)}
                    </td>
                    <td className="p-2 text-slate-400 capitalize">{r.resourceType}</td>
                    <td className="p-2 text-right text-amber-400 font-medium">
                      {r.wastedMs > 0 ? r.wastedMs.toLocaleString() : "—"}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </section>
  );
}
