"use client";

import { useAccount } from "wagmi";
import { useSwitchChain } from "wagmi";
import { type ReactNode, useState } from "react";

interface ChainGuardProps {
  requiredChainId: number | null;
  children: ReactNode;
}

export default function ChainGuard({ requiredChainId, children }: ChainGuardProps) {
  const { chain, isConnected } = useAccount();
  const { switchChain } = useSwitchChain();
  const [switching, setSwitching] = useState(false);

  // No enforcement needed if proxy hasn't sent chain config or wallet isn't connected
  if (!requiredChainId || !isConnected || !chain) {
    return <>{children}</>;
  }

  // Wallet is on the correct chain
  if (chain.id === requiredChainId) {
    return <>{children}</>;
  }

  const handleSwitch = async () => {
    setSwitching(true);
    try {
      switchChain({ chainId: requiredChainId });
    } catch (err) {
      console.error("Failed to switch chain:", err);
    } finally {
      setSwitching(false);
    }
  };

  const requiredHex = `0x${requiredChainId.toString(16)}`;

  return (
    <div className="flex flex-1 items-center justify-center">
      <div className="mx-auto max-w-sm rounded-xl border border-amber-200 bg-amber-50 p-6 text-center shadow-sm dark:border-amber-800/50 dark:bg-amber-950/30">
        <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-amber-100 dark:bg-amber-900/50">
          <svg
            className="h-6 w-6 text-amber-600 dark:text-amber-400"
            fill="none"
            viewBox="0 0 24 24"
            strokeWidth={1.5}
            stroke="currentColor"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126ZM12 15.75h.007v.008H12v-.008Z"
            />
          </svg>
        </div>

        <h3 className="mb-2 text-sm font-semibold text-amber-900 dark:text-amber-200">
          Wrong Network
        </h3>
        <p className="mb-4 text-xs text-amber-700 dark:text-amber-400">
          The proxy RPC requires chain{" "}
          <span className="font-mono font-semibold">{requiredChainId}</span>{" "}
          <span className="text-amber-500">({requiredHex})</span> but your wallet is on{" "}
          <span className="font-mono font-semibold">{chain.name}</span>{" "}
          <span className="text-amber-500">(chain {chain.id})</span>.
        </p>

        <button
          onClick={handleSwitch}
          disabled={switching}
          className="w-full rounded-lg bg-amber-600 px-4 py-2.5 text-sm font-medium text-white transition-colors hover:bg-amber-500 disabled:opacity-50"
        >
          {switching ? "Switching..." : `Switch to Chain ${requiredChainId}`}
        </button>
      </div>
    </div>
  );
}
