import React, { useState, useEffect } from "react";
import { IInventoryItem, IStakingSource, IStake, IOption } from "typings";
import {
  calculateRemainingTime,
  getObjectFromArray,
} from "../../../utils/helpers";
import SelectDropdown from "../SelectDropdown";
import Image from "next/image";

const StakingSource = (props: {
  stakingSource: IStakingSource;
  inventoryItems: IInventoryItem[] | null | undefined;
  claimStake: (stakingEventId: number) => void;
  startStake: (
    inventoryItemId: string,
    storeItemId: number,
    wellId: string
  ) => void;
}) => {
  const [activeStakes, setActiveStakes] = useState<IStake[]>([]);
  const [selectedInventoryItemId, setSelectedInventoryItemId] = useState<
    string | null
  >(null);
  const [selectedStoreItemId, setSelectedStoreItemId] = useState<number | null>(
    null
  );
  const [selectedWellId, setSelectedWellId] = useState<string | null>(null);
  const [showInfo, setShowInfo] = useState(false);

  // Check if claimable every second
  useEffect(() => {
    const updatedActiveStakes = props.stakingSource.activeStakes.map(
      (stake) => {
        const remainingTime = calculateRemainingTime(
          stake.startTime,
          stake.durationInMins
        );

        const obj = {
          ...stake,
          remainingTime: remainingTime,
        };

        return obj;
      }
    );

    const intervalId = setInterval(() => {
      setActiveStakes(updatedActiveStakes);
    }, 1000);

    return () => {
      clearInterval(intervalId);
    };
  });

  const handleStartMining = () => {
    if (selectedInventoryItemId && selectedWellId && selectedStoreItemId) {
      props.startStake(
        selectedInventoryItemId,
        selectedStoreItemId,
        selectedWellId
      );
    }
  };

  const handleClaim = (stakingEventId: number) => {
    props.claimStake(stakingEventId);
  };

  const handleSelectChange = (
    wellId: string,
    inventoryItemId: string,
    storeitemId: number
  ) => {
    setSelectedWellId(wellId);
    setSelectedStoreItemId(storeitemId);
    setSelectedInventoryItemId(inventoryItemId);
  };

  const Countdown = (props: { remainingTime: number }) => {
    const hours = Math.floor((props.remainingTime / (1000 * 60 * 60)) % 24)
      .toString()
      .padStart(2, "0");
    const minutes = Math.floor((props.remainingTime / (1000 * 60)) % 60)
      .toString()
      .padStart(2, "0");
    const seconds = Math.floor((props.remainingTime / 1000) % 60)
      .toString()
      .padStart(2, "0");
    return (
      <span className="font-bold">
        {hours} : {minutes} : {seconds}
      </span>
    );
  };

  const RenderButtonOrCountdown = (props: { stake: IStake }) => {
    if (!props.stake.remainingTime) return <p>Error</p>;

    if (props.stake.remainingTime <= 0) {
      return (
        <button
          onClick={() => handleClaim(props.stake.id)}
          className="bg-green-600 text-white px-4 py-2 rounded-lg font-bold text-center"
        >
          Claim
        </button>
      );
    } else {
      return <Countdown remainingTime={props.stake.remainingTime} />;
    }
  };

  const isActive = (item: IInventoryItem): boolean => {
    return props.stakingSource.activeStakes.some(
      (obj) => obj.inventoryItemId === item.id
    );
  };

  return (
    <div className="flex">
      <Image
        src={"/assets/moons/" + props.stakingSource.image}
        alt="Moon"
        width={300}
        height={300}
        style={{ objectFit: "contain" }}
        className="mr-4"
      />
      <div className="max-w-md text-white bg-gradient-to-tr from-purple-600 via-blue-600 to-indigo-700 md:rounded-xl p-1">
        <div className="bg-slate-900 md:rounded-xl p-4">
          <div className="">
            <h3 className="text-3xl font-bold mb-2">
              {props.stakingSource.name}{" "}
              <span>
                (
                {props.stakingSource.resourceWells.reduce(
                  (x, y) => x + y.supply,
                  0
                )}
                )
              </span>
            </h3>
            <p className="text-sm">{props.stakingSource.description}</p>
          </div>
          <h3 className="mt-4 mb-2 text-2xl font-bold">Inventory</h3>
          <div className="">
            {activeStakes.length > 0 && (
              <div className="">
                {activeStakes.map((stake, id) => (
                  <div
                    key={id}
                    className="border border-white rounded-xl p-3 mb-2 bg-black/20"
                  >
                    <p className="font-bold text-xl mb-2">
                      {props.inventoryItems &&
                        getObjectFromArray(
                          props.inventoryItems,
                          "id",
                          stake.inventoryItemId
                        )?.storeItem.name}
                    </p>
                    <p>
                      <span className="font-bold">Resource: </span>
                      {stake.resourceType}
                    </p>
                    <p className="mb-2">
                      <span className="font-bold">Yield: </span>
                      {stake.stakeAmount}
                    </p>
                    <RenderButtonOrCountdown stake={stake} />
                  </div>
                ))}
              </div>
            )}
            {props.inventoryItems && (
              <div className="">
                {props.inventoryItems.map(
                  (item, id) =>
                    !isActive(item) && (
                      <div
                        key={id}
                        className="border border-white rounded-xl p-3 mb-2 bg-black/20"
                      >
                        <p className="font-bold text-xl mb-2">
                          {item.storeItem.name}
                        </p>
                        <div className="flex">
                          <SelectDropdown
                            options={props.stakingSource.resourceWells.map(
                              (well): IOption => ({
                                value: well.id,
                                label: well.resourceType + ` (${well.supply})`,
                              })
                            )}
                            onChange={(value) =>
                              handleSelectChange(
                                value,
                                item.id,
                                item.storeItem.id
                              )
                            }
                            isActive={selectedInventoryItemId === item.id}
                          />
                          {selectedInventoryItemId === item.id ? (
                            <button
                              onClick={handleStartMining}
                              className="bg-slate-100 text-slate-900 px-4 py-2 rounded-lg font-bold w-28 text-center ml-2"
                            >
                              Activate
                            </button>
                          ) : (
                            <></>
                          )}
                        </div>
                      </div>
                    )
                )}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default StakingSource;
