import { redirect } from "@tanstack/react-router";
import { useParams } from "@tanstack/react-router";
import { requireChains } from "@/entities/chain/lib";
import { createFileRoute } from "@tanstack/react-router";
import { useNavigate } from "@tanstack/react-router";

import { useChainState } from "@/entities/chain/model";
import { Typography } from "@mui/material";
import { ChainButtons } from "@/widgets/chain-buttons";

function ChainPage() {
  const navigate = useNavigate({ from: "/$namespace/$chainId" });
  const { chainId } = useParams({ from: "/$namespace/$chainId" });
  const chain = useChainState((state) => state.getChain(chainId));
  if (!chain) return navigate({ to: "/$namespace" });

  return (
    <>
      <div key={chain._id} className="flex items-center justify-between">
        <Typography
          variant="h4"
          sx={{ color: "#4C4E64DE" }}
          className="select-none"
        >
          {chain.name}
        </Typography>

        <ChainButtons chain={chain} />
      </div>
    </>
  );
}

export const Route = createFileRoute("/$namespace/$chainId")({
  component: ChainPage,
  loader: async ({ params }) => {
    await requireChains();
    const chainState = useChainState.getState();
    const chains = chainState.chains;

    if (typeof chains === "undefined")
      throw redirect({ to: "/$namespace", params });

    const selectedChain = chainState.getChain(params.chainId);
    if (!selectedChain) throw redirect({ to: "/$namespace", params });
  },
});
