import React, { useState, useEffect } from "react";
import ResourceStoreItem from "../ResourceModal";
import { sumValues } from "../../../../utils/helpers";
import { IBankAccount, IConversionPair } from "typings";

const ResourceStore = (props: {
  bankAccount: IBankAccount | undefined;
  sellResource: (pairs: IConversionPair[]) => void;
}) => {
  const [conversionRate, setConversionRate] = useState<Number>(0.1);
  const [conversionPairs, setConversionPairs] = useState<
    IConversionPair[] | null
  >(null);

  useEffect(() => {
    if (props.bankAccount) {
      const pairs = props.bankAccount.resourceAccounts.map((resource) => ({
        resourceType: resource.resourceType,
        resourceAmount: 0,
        moneyAmount: 0,
      }));
      setConversionPairs(pairs);
    }
  }, []);

  const handleConversionPairs = (amount: number, resourceType: string) => {
    if (!conversionPairs) return;

    const existingObj = conversionPairs.find(
      (obj) => obj.resourceType === resourceType
    );

    const updatedPairs = conversionPairs.map((pair) => {
      if (pair.resourceType === existingObj?.resourceType) {
        return {
          ...pair,
          resourceAmount: amount,
          moneyAmount: amount * conversionRate.valueOf(),
        };
      } else {
        return pair;
      }
    });
    setConversionPairs(updatedPairs);
  };

  const getConversionPair = (resourceType: string) => {
    return conversionPairs?.find((obj) => obj.resourceType === resourceType);
  };

  const handleSellResources = async () => {
    if (conversionPairs) {
      const response = props.sellResource(conversionPairs);
      // if ok clear pairs
      // setConversionPairs(null);
    }
  };

  return (
    <div className="bg-gradient-to-tr from-purple-600 via-blue-600 to-indigo-700 h-auto p-1 rounded-xl rounded-xl col-span-2">
      <div className="bg-slate-900 text-white p-4 md:p-8 rounded-xl">
        <h1 className="text-white text-3xl font-bold">Sell Resources</h1>
        <div className="flex gap-4 mt-4">
          <div className="flex-1">
            {props.bankAccount &&
              props.bankAccount.resourceAccounts.map((resourceAccount, id) => (
                <div key={id} className="flex mb-4 gap-4">
                  <div className="flex-1">
                    <ResourceStoreItem
                      resourceAccount={resourceAccount}
                      conversionPair={getConversionPair(
                        resourceAccount.resourceType
                      )}
                      handleConversionPairs={handleConversionPairs}
                    />
                  </div>
                </div>
              ))}

            {conversionPairs && (
              <div className="bg-slate-200 rounded-lg p-3">
                <p className="mb-0 text-2xl font-bold text-black">
                  Grand total
                </p>
                <p className="mb-3 text-2xl font-bold underline text-green-700">
                  ${" "}
                  {sumValues(conversionPairs, "moneyAmount").toLocaleString(
                    "en-US",
                    {
                      minimumFractionDigits: 2,
                      maximumFractionDigits: 2,
                    }
                  )}
                </p>
                <button
                  onClick={handleSellResources}
                  className="bg-green-700 py-2 text-slate-900 rounded-lg font-bold w-28 text-center text-white"
                >
                  Sell Now
                </button>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default ResourceStore;
