"use client";

import { useEffect, useState } from "react";

import {
  getActiveNetwork,
  listMaviNetworks,
  readNetworkId,
  setNetworkId,
  type MaviNetworkId,
} from "@/lib/mavi/network";
import { cn } from "@/lib/utils";

export function NetworkSwitcher({
  className,
  onChange,
}: {
  className?: string;
  onChange?: (id: MaviNetworkId) => void;
}) {
  const [id, setId] = useState<MaviNetworkId>("private-anvil");
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
    setId(readNetworkId());
    const sync = () => setId(readNetworkId());
    window.addEventListener("mavi-network", sync);
    return () => window.removeEventListener("mavi-network", sync);
  }, []);

  if (!mounted) {
    return (
      <div className={cn("h-10 animate-pulse rounded-lg bg-muted/40", className)} />
    );
  }

  const active = getActiveNetwork();

  return (
    <div className={cn("space-y-2", className)}>
      <label htmlFor="mavi-network" className="text-sm font-medium">
        Network
      </label>
      <select
        id="mavi-network"
        value={id}
        onChange={(e) => {
          const next = e.target.value as MaviNetworkId;
          setNetworkId(next);
          setId(next);
          onChange?.(next);
        }}
        className="flex h-10 w-full rounded-md border border-border bg-background px-3 text-sm text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
      >
        {listMaviNetworks().map((n) => (
          <option key={n.id} value={n.id}>
            {n.label}
          </option>
        ))}
      </select>
      <p className="text-[11px] text-muted-foreground leading-snug">
        {active.hint} · chain id {active.chainId}
      </p>
    </div>
  );
}
