"use client";

import type { LighthouseOpportunity, LighthouseDiagnostic } from "@/lib/sitespeed";

import { IconChevronDown, IconChevronRight } from "@tabler/icons-react";
import { useTranslations } from "next-intl";
import { useState } from "react";

import { formatBytes } from "@/lib/scoring";

function lhColor(score: number) {
  if (score >= 0.9) return "#0cce6b";
  if (score >= 0.5) return "#ffa400";
  return "#ff4e42";
}

function lhBadge(score: number) {
  if (score >= 0.9) return "bg-[#0cce6b]/10 text-[#0cce6b]";
  if (score >= 0.5) return "bg-[#ffa400]/10 text-[#ffa400]";
  return "bg-[#ff4e42]/10 text-[#ff4e42]";
}

interface Props {
  opportunities: LighthouseOpportunity[];
  diagnostics: LighthouseDiagnostic[];
}

export function StructureAudits({ opportunities, diagnostics }: Props) {
  const t = useTranslations("StructureAudits");
  return (
    <div className="space-y-12">
      {/* Opportunities */}
      {opportunities.length > 0 && (
        <div>
          <h3 className="mb-6 font-[family-name:var(--font-manrope)] text-lg font-bold">
            {t("opportunitiesTitle")}
          </h3>
          <p className="mb-6 text-sm text-muted-foreground">{t("opportunitiesDescription")}</p>
          <div className="space-y-3">
            {opportunities.map((opp) => (
              <OpportunityRow key={opp.id} opp={opp} />
            ))}
          </div>
        </div>
      )}

      {/* Diagnostics */}
      {diagnostics.length > 0 && (
        <div>
          <h3 className="mb-6 font-[family-name:var(--font-manrope)] text-lg font-bold">
            {t("diagnosticsTitle")}
          </h3>
          <p className="mb-6 text-sm text-muted-foreground">{t("diagnosticsDescription")}</p>
          <div className="space-y-3">
            {[...diagnostics]
              .toSorted((a, b) => a.score - b.score)
              .map((diag) => (
                <DiagnosticRow key={diag.id} diag={diag} />
              ))}
          </div>
        </div>
      )}
    </div>
  );
}

function OpportunityRow({ opp }: { opp: LighthouseOpportunity }) {
  const [open, setOpen] = useState(false);

  return (
    <div className="overflow-hidden rounded-xl border border-[#45464d]/10 bg-surface-container">
      <button
        type="button"
        onClick={() => setOpen(!open)}
        className="flex w-full items-center gap-4 p-5 text-left transition-colors hover:bg-surface-container-high/50"
      >
        {open ? (
          <IconChevronDown className="size-4 shrink-0 text-muted-foreground" />
        ) : (
          <IconChevronRight className="size-4 shrink-0 text-muted-foreground" />
        )}
        <div className="min-w-0 flex-1">
          <span className="text-sm font-bold text-foreground">{opp.title}</span>
        </div>
        <div className="flex shrink-0 items-center gap-4">
          {opp.savingsBytes > 0 && (
            <span className="text-xs text-muted-foreground">{formatBytes(opp.savingsBytes)}</span>
          )}
          <span className="font-[family-name:var(--font-manrope)] text-sm font-black text-perf-good">
            -
            {opp.savingsMs >= 1000
              ? `${(opp.savingsMs / 1000).toFixed(1)}s`
              : `${Math.round(opp.savingsMs)}ms`}
          </span>
        </div>
      </button>
      {open && (
        <div className="border-t border-[#45464d]/10 px-5 pt-0 pb-5">
          <p className="mt-3 text-xs leading-relaxed text-muted-foreground">{opp.description}</p>
        </div>
      )}
    </div>
  );
}

function DiagnosticRow({ diag }: { diag: LighthouseDiagnostic }) {
  const [open, setOpen] = useState(false);

  return (
    <div className="overflow-hidden rounded-xl border border-[#45464d]/10 bg-surface-container">
      <button
        type="button"
        onClick={() => setOpen(!open)}
        className="flex w-full items-center gap-4 p-5 text-left transition-colors hover:bg-surface-container-high/50"
      >
        {open ? (
          <IconChevronDown className="size-4 shrink-0 text-muted-foreground" />
        ) : (
          <IconChevronRight className="size-4 shrink-0 text-muted-foreground" />
        )}
        <span
          className={`size-3 shrink-0 rounded-full`}
          style={{ backgroundColor: lhColor(diag.score) }}
        />
        <div className="min-w-0 flex-1">
          <span className="text-sm font-bold text-foreground">{diag.title}</span>
        </div>
        {diag.displayValue && (
          <span className="shrink-0 text-xs text-muted-foreground">{diag.displayValue}</span>
        )}
        <span
          className={`shrink-0 rounded px-2 py-0.5 text-[10px] font-black ${lhBadge(diag.score)}`}
        >
          {Math.round(diag.score * 100)}
        </span>
      </button>
      {open && (
        <div className="border-t border-[#45464d]/10 px-5 pt-0 pb-5">
          <p className="mt-3 text-xs leading-relaxed text-muted-foreground">{diag.description}</p>
        </div>
      )}
    </div>
  );
}
