import React, { useState } from "react";
import { NETWORK_LOGO_URLS, NETWORK_NAME_TO_CHAIN_ID } from "./utils";
import { ArrowLeft } from "lucide-react";
import TokenAllocation from "./TokenAllocation";

interface NetworkInfo {
  name: string;
  icon: string;
}

interface NetworkAllocation {
  name: string;
  chainId: number;
  amount: string;
}

function SelectNetwork({
  availableNetworks,
  selectedNetworksPay,
  setSelectedNetworksPay,
  fromToken,
  onBack,
  onDone,
  type = "SWAP",
}: {
  availableNetworks: NetworkInfo[];
  selectedNetworksPay: NetworkAllocation[];
  setSelectedNetworksPay: (networks: NetworkAllocation[]) => void;
  fromToken: any;
  onBack: () => void;
  onDone: (networks: NetworkAllocation[]) => void;
  type?: "SWAP" | "TRANSFER";
}) {
  const [showAllocation, setShowAllocation] = useState(false);
  // Initialize tempSelectedNetworks with existing selections if any
  const [tempSelectedNetworks, setTempSelectedNetworks] = useState<string[]>(
    selectedNetworksPay.map((network) => network.name)
  );

  const handleNetworkSelect = (networkName: string) => {
    setTempSelectedNetworks((prev) => {
      if (prev.includes(networkName)) {
        return prev.filter((net) => net !== networkName);
      } else {
        return [...prev, networkName];
      }
    });
  };

  const isNetworkSelected = (networkName: string) => {
    return tempSelectedNetworks.includes(networkName);
  };

  // Filter networks based on fromToken's chainIds and non-zero balances
  const availableChainIds =
    fromToken?.chainIds?.map((chain: any) => chain.chainId) || [];
  const filteredNetworks = availableNetworks.filter((network) => {
    const chainId = NETWORK_NAME_TO_CHAIN_ID[network.name];
    const tokenChainInfo = fromToken?.chainIds?.find(
      (chain: any) => chain.chainId === chainId
    );
    const chainBalance = tokenChainInfo?.balance ?? "0";
    return availableChainIds.includes(chainId) && parseFloat(chainBalance) > 0;
  });

  console.log(type);

  if (showAllocation) {
    return (
      <TokenAllocation
        selectedNetworks={tempSelectedNetworks}
        fromToken={fromToken}
        onBack={() => {
          setShowAllocation(false);
          // When editing, don't reset the temp selections
          if (selectedNetworksPay.length === 0) {
            setTempSelectedNetworks([]);
          }
        }}
        onDone={(allocations) => {
          setSelectedNetworksPay(allocations);
          onDone(allocations);
        }}
        // Pass existing allocations when editing
        initialAllocations={selectedNetworksPay}
      />
    );
  }

  // Show message if no networks with balance
  if (filteredNetworks.length === 0) {
    return (
      <div
        style={{
          width: "100%",
          background: "#fff",
          borderRadius: 20,
          fontFamily: "Inter, sans-serif",
          paddingBottom: 24,
        }}
      >
        <div
          style={{
            display: "flex",
            alignItems: "center",
            marginBottom: 8,
            position: "relative",
          }}
        >
          <button
            onClick={onBack}
            style={{
              background: "none",
              border: "none",
              fontSize: 22,
              color: "#222",
              cursor: "pointer",
              position: "absolute",
              left: 0,
              fontFamily: "Inter, sans-serif",
            }}
          >
            <ArrowLeft style={{ width: 24, height: 24, color: "#717680" }} />
          </button>
          <span
            style={{
              fontWeight: 600,
              fontSize: 20,
              width: "100%",
              textAlign: "center",
            }}
          >
            Select networks
          </span>
        </div>

        <div
          style={{
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            justifyContent: "center",
            padding: "40px 20px",
            color: "#717680",
            textAlign: "center",
          }}
        >
          <p style={{ fontSize: 15, margin: 0 }}>
            No networks available with {fromToken?.symbol} balance
          </p>
        </div>

        <div style={{ display: "flex", gap: 12, marginTop: "auto" }}>
          <button
            onClick={onBack}
            style={{
              width: "100%",
              border: "1px solid #D5D7DA",
              background: "#fff",
              color: "#414651",
              fontWeight: 600,
              fontSize: 16,
              borderRadius: 8,
              padding: "12px 0",
              cursor: "pointer",
            }}
          >
            Back
          </button>
        </div>
      </div>
    );
  }

  return (
    <div
      style={{
        width: "100%",
        background: "#fff",
        borderRadius: 20,
        fontFamily: "Inter, sans-serif",
        paddingBottom: 24,
      }}
    >
      <div
        style={{
          display: "flex",
          alignItems: "center",
          marginBottom: 8,
          position: "relative",
        }}
      >
        <button
          onClick={() => {
            onBack();
            // Reset temp selection when going back
            setTempSelectedNetworks([]);
          }}
          style={{
            background: "none",
            border: "none",
            fontSize: 22,
            color: "#222",
            cursor: "pointer",
            position: "absolute",
            left: 0,
            fontFamily: "Inter, sans-serif",
          }}
        >
          <ArrowLeft style={{ width: 24, height: 24, color: "#717680" }} />
        </button>
        <span
          style={{
            fontWeight: 600,
            fontSize: 20,
            width: "100%",
            textAlign: "center",
          }}
        >
          Select networks
        </span>
      </div>

      <div style={{ marginBottom: 16 }}>
        <p
          style={{
            color: "#717680",
            fontSize: 14,
            margin: "0 0 24px 0",
            textAlign: "center",
          }}
        >
          Select one or more networks for your{" "}
          {type === "SWAP" ? "swap" : "transfer"}
        </p>
      </div>

      <div style={{ marginBottom: 24 }}>
        {filteredNetworks.map((network) => {
          const chainId = NETWORK_NAME_TO_CHAIN_ID[network.name];
          const tokenChainInfo = fromToken?.chainIds?.find(
            (chain: any) => chain.chainId === chainId
          );
          const chainBalance = tokenChainInfo?.balance ?? "0";
          const formattedBalance =
            parseFloat(chainBalance) / Math.pow(10, fromToken?.decimals || 6);

          const isSelected = isNetworkSelected(network.name);

          return (
            <div
              key={network.name}
              style={{
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
                padding: "16px",
                border: isSelected ? "1px solid #3662E3" : "1px solid #D5D7DA",
                borderRadius: 12,
                cursor: "pointer",
                marginBottom: 8,
                transition: "all 0.2s ease",
                background: isSelected ? "#F6F8FE" : "#fff",
              }}
              onClick={() => handleNetworkSelect(network.name)}
            >
              <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                <div
                  style={{
                    width: 20,
                    height: 20,
                    border: "2px solid",
                    borderColor: isSelected ? "#4664E9" : "#E9EAEB",
                    borderRadius: "4px",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    background: isSelected ? "#4664E9" : "transparent",
                  }}
                >
                  {isSelected && (
                    <div
                      style={{
                        width: "10px",
                        height: "6px",
                        borderLeft: "2px solid white",
                        borderBottom: "2px solid white",
                        transform: "rotate(-45deg)",
                        marginTop: "-2px",
                      }}
                    ></div>
                  )}
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <img
                    src={NETWORK_LOGO_URLS[chainId]}
                    alt={network.name}
                    style={{ width: 24, height: 24 }}
                  />
                  <span
                    style={{
                      fontWeight: 500,
                      fontSize: 16,
                      color: "#414651",
                    }}
                  >
                    {network.name}
                  </span>
                </div>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span
                  style={{
                    color: "#000",
                    fontSize: 14,
                    fontWeight: 600,
                  }}
                >
                  {formattedBalance.toFixed(6)} {fromToken?.symbol}
                </span>
              </div>
            </div>
          );
        })}
      </div>

      <div style={{ display: "flex", gap: 12, marginTop: "auto" }}>
        <button
          onClick={() => {
            onBack();
            // Reset temp selection when going back
            setTempSelectedNetworks([]);
          }}
          style={{
            flex: 1,
            border: "1px solid #D5D7DA",
            background: "#fff",
            color: "#414651",
            fontWeight: 600,
            fontSize: 16,
            borderRadius: 8,
            padding: "12px 0",
            cursor: "pointer",
          }}
        >
          Cancel
        </button>
        <button
          onClick={() => setShowAllocation(true)}
          style={{
            flex: 1,
            border: "none",
            background: tempSelectedNetworks.length > 0 ? "#4664E9" : "#D5D7DA",
            color: "#fff",
            fontWeight: 600,
            fontSize: 16,
            borderRadius: 8,
            padding: "12px 0",
            cursor: tempSelectedNetworks.length > 0 ? "pointer" : "not-allowed",
          }}
          disabled={tempSelectedNetworks.length === 0}
        >
          Next
        </button>
      </div>
    </div>
  );
}

export default SelectNetwork;
