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

const ResourceStore = (props: { bankAccount: IBankAccount | undefined }) => {
  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 = () => {
    // Do something..
    console.log(conversionPairs);
  };

  return (
    <div className="bg-slate-800 rounded-lg p-4 col-span-2">
      <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) => (
              <div 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>
  );
};

export default ResourceStore;
