import { ArrowDownIcon } from "@src/assets/icons";
import { Modal } from "@src/components/Modal";
import { useSwapContext } from "@src/context";
import { Chain } from "@src/models";
import { useMemo, useState } from "react";
import { SwapPanelType } from "../../../SwapView";
import { ChainPicker } from "./ChainPicker";

type Props = {
  chain: Chain | undefined;
  type: SwapPanelType;
  className?: string;
};

export const ChainPanel = ({ chain, type, className }: Props) => {
  const { srcChainLocked, dstChainLocked } = useSwapContext();

  const projectLockedDestinationChain = useMemo(
    () => type === "destination" && dstChainLocked,
    [type, dstChainLocked],
  );

  const projectLockedSourceChain = useMemo(
    () => type === "source" && srcChainLocked,
    [type, srcChainLocked],
  );

  const [chainPickerModalOpen, setChainPickerModalOpen] = useState(false);

  return (
    <>
      {chainPickerModalOpen && (
        <Modal onClose={() => setChainPickerModalOpen(false)}>
          <ChainPicker
            type={type}
            onClose={() => setChainPickerModalOpen(false)}
          />
        </Modal>
      )}

      <button
        type="button"
        disabled={projectLockedDestinationChain || projectLockedSourceChain}
        onClick={() => setChainPickerModalOpen(true)}
        className={`${className || ""}`}
      >
        <div className="flex justify-between items-center p-4 gap-8">
          <div className="flex flex-col font-medium items-start">
            <p className="text-xs opacity-60">
              {type === "source" ? "From:" : "To:"}
            </p>
            <p className={`${chain ? "" : "opacity-60"}`}>
              {chain ? chain.displayName : "Select"}
            </p>
          </div>
          {!projectLockedDestinationChain && !projectLockedSourceChain && (
            <div className="w-4 h-2 fill-t_text_primary">
              <ArrowDownIcon />
            </div>
          )}
        </div>
      </button>
    </>
  );
};
