"use client";

import { useState } from "react";
import { Smartphone, Monitor, RefreshCw, Gauge as GaugeIcon } from "@/components/ui/icons";
import { Panel, PanelHeader } from "@/components/ui/panel";
import { EmptyState } from "@/components/ui/empty-state";
import type { LighthouseStrategy, SiteData } from "@/lib/mock-data";
import { formatDate } from "@/lib/format";

export function LighthousePanel({ lighthouse }: { lighthouse: SiteData["lighthouse"] | null }) {
  const [strategy, setStrategy] = useState<LighthouseStrategy>("desktop");

  if (!lighthouse) {
    return (
      <Panel>
        <PanelHeader
          title="Performance technique"
          subtitle="Source : Google PageSpeed Insights"
        />
        <EmptyState
          icon={GaugeIcon}
          title="Mesures non disponibles"
          description="Les scores PageSpeed Insights apparaîtront ici dès la première mesure."
        />
      </Panel>
    );
  }

  const data = lighthouse[strategy];

  return (
    <Panel>
      <PanelHeader
        title="Performance technique"
        subtitle={`Source : Google PageSpeed Insights · Mesure du ${formatDate(data.measuredAt, "long")}`}
        trailing={
          <>
            <div className="flex items-center rounded-md border border-border bg-stone-900/[0.03] p-0.5">
              <StrategyButton active={strategy === "mobile"} onClick={() => setStrategy("mobile")}>
                <Smartphone className="size-3.5" />
                Mobile
              </StrategyButton>
              <StrategyButton active={strategy === "desktop"} onClick={() => setStrategy("desktop")}>
                <Monitor className="size-3.5" />
                Ordinateur
              </StrategyButton>
            </div>
            <button
              type="button"
              aria-label="Relancer la mesure"
              className="size-9 inline-flex items-center justify-center rounded-md border border-border text-text-muted hover:text-accent hover:bg-stone-900/[0.05] transition-colors"
            >
              <RefreshCw className="size-3.5" />
            </button>
          </>
        }
      />

      <div className="px-6 py-6">
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <Gauge value={data.performance} label="Performance" />
          <Gauge value={data.accessibility} label="Accessibilité" />
          <Gauge value={data.bestPractices} label="Bonnes pratiques" />
          <Gauge value={data.seo} label="SEO" />
        </div>

        <div className="mt-6 pt-6 border-t border-border">
          <div className="text-micro uppercase tracking-wider text-text-faint mb-3">
            Core Web Vitals
          </div>
          <div className="grid grid-cols-3 gap-4">
            <Vital
              label="LCP"
              hint="Largest Contentful Paint"
              value={`${data.coreWebVitals.lcp.toFixed(1).replace(".", ",")} s`}
              tone={cwvTone("lcp", data.coreWebVitals.lcp)}
            />
            <Vital
              label="INP"
              hint="Interaction to Next Paint"
              value={`${Math.round(data.coreWebVitals.inp)} ms`}
              tone={cwvTone("inp", data.coreWebVitals.inp)}
            />
            <Vital
              label="CLS"
              hint="Cumulative Layout Shift"
              value={data.coreWebVitals.cls.toFixed(2).replace(".", ",")}
              tone={cwvTone("cls", data.coreWebVitals.cls)}
            />
          </div>
        </div>
      </div>
    </Panel>
  );
}

function StrategyButton({
  active,
  onClick,
  children,
}: {
  active: boolean;
  onClick: () => void;
  children: React.ReactNode;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={`inline-flex items-center gap-1.5 px-3 py-1 text-xs font-medium rounded transition-colors ${
        active ? "bg-surface text-text shadow-sm" : "text-text-dim hover:text-text"
      }`}
    >
      {children}
    </button>
  );
}

function Gauge({ value, label }: { value: number; label: string }) {
  const tone = scoreTone(value);
  const radius = 38;
  const stroke = 6;
  const circumference = 2 * Math.PI * radius;
  const offset = circumference - (value / 100) * circumference;

  return (
    <div className="flex flex-col items-center text-center">
      <div className="relative size-24">
        <svg viewBox="0 0 100 100" className="size-full -rotate-90">
          <circle
            cx="50"
            cy="50"
            r={radius}
            fill="none"
            stroke="rgba(255,255,255,0.06)"
            strokeWidth={stroke}
          />
          <circle
            cx="50"
            cy="50"
            r={radius}
            fill="none"
            stroke={tone.stroke}
            strokeWidth={stroke}
            strokeLinecap="round"
            strokeDasharray={circumference}
            strokeDashoffset={offset}
            style={{ filter: `drop-shadow(0 0 8px ${tone.glow})` }}
          />
        </svg>
        <div className="absolute inset-0 flex flex-col items-center justify-center">
          <span className="text-2xl font-semibold tabular-nums" style={{ color: tone.text }}>
            {value}
          </span>
        </div>
      </div>
      <div className="mt-2 text-xs font-medium text-text-muted">{label}</div>
    </div>
  );
}

function Vital({
  label,
  hint,
  value,
  tone,
}: {
  label: string;
  hint: string;
  value: string;
  tone: "good" | "ni" | "poor";
}) {
  const dot = tone === "good" ? "bg-success" : tone === "ni" ? "bg-warning" : "bg-danger";
  const text = tone === "good" ? "text-success" : tone === "ni" ? "text-warning" : "text-danger";
  return (
    <div className="rounded-md border border-border bg-stone-900/[0.03] px-4 py-3">
      <div className="flex items-center gap-1.5">
        <span className={`size-1.5 rounded-full ${dot}`} />
        <span className="text-xxs font-semibold uppercase tracking-wider text-text-muted">
          {label}
        </span>
      </div>
      <div className={`mt-1.5 text-lg font-semibold tabular-nums ${text}`}>{value}</div>
      <div className="mt-0.5 text-micro text-text-faint">{hint}</div>
    </div>
  );
}

function scoreTone(value: number) {
  if (value >= 90) return { stroke: "#22c55e", glow: "rgba(34,197,94,0.4)", text: "#22c55e" };
  if (value >= 50) return { stroke: "#f59e0b", glow: "rgba(245,158,11,0.4)", text: "#f59e0b" };
  return { stroke: "#ef4444", glow: "rgba(239,68,68,0.4)", text: "#ef4444" };
}

function cwvTone(metric: "lcp" | "inp" | "cls", value: number): "good" | "ni" | "poor" {
  if (metric === "lcp") return value <= 2.5 ? "good" : value <= 4 ? "ni" : "poor";
  if (metric === "inp") return value <= 200 ? "good" : value <= 500 ? "ni" : "poor";
  return value <= 0.1 ? "good" : value <= 0.25 ? "ni" : "poor";
}
