import React, { FC, useEffect } from "react";
import { IPracingProps } from "../SingIn/register.types";
import {
  PlanBoxPriceDetails,
  PlanBoxStatus,
  PlanBoxUsers,
  PlanBoxWrapper,
} from "./PlanBox.styles";
import { Aligment, Icon } from "venice-ui";
import { Colors } from "../../untils/Theme";
import { checkLang, t } from "../../helpers/userHelper";
import { dictionary } from "../../untils/dictionary";
import { useLocation } from "react-router-dom";

interface IPlanBox {
  plan: IPracingProps;
  activePlan: string;
  handleClick: (planID: string, planName: string, currency: string) => void;
}

export const PlanBox: FC<IPlanBox> = ({ plan, activePlan, handleClick }) => {
  const [priceDetials, setPriceDetails] = React.useState({
    currency: "",
    price: 0,
    priceID: "",
  });
  const isActive = activePlan === plan.id;

  const getPriceDetails = React.useCallback(() => {
    const isPL = checkLang() === "pl";
    const currencyCode = isPL ? "pln" : "eur";
    const currencyLabel = isPL ? "PLN" : "EUR";

    const price = plan.prices.find((_item) => _item.currency === currencyCode);
    if (price) {
      setPriceDetails({  currency: currencyLabel, price: price.value, priceID: price.priceID });
      return;
    }

    // Fallback: use any available price to avoid empty state
    if (plan.prices.length > 0) {
      const fallback = plan.prices[0];
      const fallbackLabel = fallback.currency.toUpperCase();
      setPriceDetails({ ...priceDetials, currency: fallbackLabel, price: fallback.value, priceID: fallback.priceID });
    }
  }, [plan.prices]);
  useEffect(() => {
    getPriceDetails();
  }, [getPriceDetails]);

  return (
    <PlanBoxWrapper
      active={isActive}
      onClick={() => handleClick(plan.id, plan.codeName || '', priceDetials.priceID)}
    >
      <Aligment gap={10} direction="column">
        <div>{plan.name}</div>
        <PlanBoxUsers>
          {plan.users} {plan.users === 1 ? t(dictionary.planUser) : t(dictionary.planUsers)}
        </PlanBoxUsers>
        <div>
          {priceDetials.price} {priceDetials.currency}
        </div>
        <PlanBoxPriceDetails>+ {t(dictionary.vatPerMonth)}</PlanBoxPriceDetails>
        <PlanBoxStatus>
          {isActive && (
            <Icon
              name={"check_circle"}
              size={'md'}
              color={Colors.green}
              hoverColor={Colors.green}
            />
          )}
        </PlanBoxStatus>
      </Aligment>
    </PlanBoxWrapper>
  );
};
