"use client";
import { useEffect, useState } from "react";
import type { PublicKey } from "@solana/web3.js";

import "./globals.css";
import { PhantomProvider } from "typings";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const [provider, setProvider] = useState<PhantomProvider>();
  const [walletAddress, setWalletAddress] = useState("");
  const [showErrorMessage, setShowErrorMessage] = useState(false);

  useEffect(() => {
    const provider = getProvider();
    setProvider(provider);
    if (!provider) return;
    provider.on("connect", async (publicKey: PublicKey) => {
      const body = { publicKey: publicKey };
      const res = await fetch("/api/user/login", {
        method: "POST",
        body: JSON.stringify(body),
        headers: { "Content-Type": "application/json" },
      });
      if (res.status === 200) {
        setWalletAddress(publicKey.toBase58());
      }
      if (res.status === 404) {
        setShowErrorMessage(true);
        setTimeout(() => {
          setShowErrorMessage(false);
        }, 3000);
      }
    });
  }, []);

  const getProvider = () => {
    if ("phantom" in window) {
      const anyWindow: any = window;
      const provider = anyWindow.phantom.solana;
      if (provider.isPhantom) return provider;
    }
  };

  const connectWallet = () => {
    if (!provider) return console.log("no provider");
    provider.connect();
  };

  return (
    <html lang="en">
      <head />
      <body className="bg-slate-900">
        <nav className="text-white flex justify-between mt-4">
          <div className="p-2 m-4 bg-slate-800 rounded-lg">Moon Miners</div>
          {showErrorMessage && (
            <div className="p-2 m-4 bg-red-800 rounded-lg">
              Wallet address not registered!
            </div>
          )}
          {walletAddress.length === 0 ? (
            <button
              onClick={connectWallet}
              className="p-2 m-4 bg-slate-800 rounded-lg"
            >
              Connect Wallet
            </button>
          ) : (
            <div className="p-2 m-4 bg-slate-800 rounded-lg">
              {walletAddress}
            </div>
          )}
        </nav>
        {children}
      </body>
    </html>
  );
}
