import { CloseIcon } from "@src/assets/icons";
import { Chain, Web3Environment } from "@src/models";
import { useMemo } from "react";
import { Virtuoso } from "react-virtuoso";
import { SwapPanelType } from "../../../../SwapView";
import { ChainItem } from "./ChainItem";
import { IS_PRODUCTION_ENV } from "@src/constants";

type Props = {
  type: SwapPanelType;
  supportedChains: Chain[];
  setSrcChain: (chain: Chain) => void;
  setDstChain: (chain: Chain) => void;
  onClose: () => void;
};
export const ChainPicker = ({
  type,
  supportedChains,
  setSrcChain,
  setDstChain,
  onClose,
}: Props) => {
  const filteredChains = useMemo(() => {
    return supportedChains.filter(
      ({ web3Environment, swapSupported }) =>
        !IS_PRODUCTION_ENV ||
        (web3Environment === Web3Environment.MAINNET && swapSupported),
    );
  }, [supportedChains]);

  const select = (selectedChainId: string) => {
    const chain = supportedChains.find(
      ({ chainId }) => chainId === selectedChainId,
    );

    if (!chain) {
      throw new Error(
        `ChainPicker > selected chain id that is absent in supportedChains list.`,
      );
    }

    type === "source" ? setSrcChain(chain) : setDstChain(chain);
    onClose();
  };

  return (
    <div className="flex flex-col h-full">
      <div className="flex justify-between">
        <div className="text-base/4 text-t_text_primary mb-4">{`Pick chain`}</div>
        <div
          className="w-4 h-4 fill-t_text_primary cursor-pointer"
          onClick={onClose}
        >
          <CloseIcon />
        </div>
      </div>
      <div className="horizontal-separator" />
      <div className="h-full pt-4">
        {filteredChains.length ? (
          <Virtuoso
            style={{ height: "100%" }}
            data={filteredChains}
            itemContent={(_, chain) => (
              <ChainItem chain={chain} type={type} onClick={select} />
            )}
          />
        ) : (
          <div className="flex justify-center mt-4">"No chain found."</div>
        )}
      </div>
    </div>
  );
};
