import { useTranslations } from "@/hooks/translations";
import styles from "./styles.module.scss";
import { addCurrency, ELocalesPlacement } from "@/locales";
import { useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { useEffect, useState } from "react";
import { actions, selectors } from "@/store";
import metricService, { EGoals, EMetrics } from "@/services/metric/metricService";
import routes from "@/routes";
import Button from "@/components/PalmistryV1/components/Button";
import Loader from "@/components/Loader";
import EmailSubstrate from "@/components/PalmistryV1/components/EmailSubstrate";
import PriceList from "@/components/pages/ABDesign/v1/components/PriceList";
import EmailsList from "@/components/PalmistryV1/components/EmailsList";
import { useFunnel } from "@/hooks/funnel/useFunnel";

const productWeights: Record<number, number> = {
    100: 1, // 10%
    500: 1, // 10%
    900: 3, // 30%
    1376: 5 // 50%
}

function TrialChoiceV1() {
    const { translate } = useTranslations(ELocalesPlacement.PalmistryV1);
    const navigate = useNavigate();
    const dispatch = useDispatch();
    const { products, isPending, currency, getProperty } = useFunnel({
        funnel: ELocalesPlacement.PalmistryV1,
        paymentPlacement: "main"
    });
    const popularProduct = products[products.length - 1];

    // const { flags } = useMetricABFlags();
    // const isLongText = flags?.text?.[0] === "on";

    const [isDisabled, setIsDisabled] = useState(true);

    const selectedPrice = useSelector(selectors.selectSelectedPrice);
    const email = useSelector(selectors.selectEmail);
    const homeConfig = useSelector(selectors.selectHome);

    const handlePriceItem = () => {
        metricService.reachGoal(EGoals.SELECT_TRIAL, [EMetrics.YANDEX, EMetrics.KLAVIYO]);
        metricService.reachGoal(EGoals.AURA_SELECT_TRIAL, [EMetrics.KLAVIYO]);
        setIsDisabled(false);
    };

    const handleNext = () => {
        if (isDisabled) {
            return;
        }
        dispatch(
            actions.siteConfig.update({
                home: { pathFromHome: homeConfig.pathFromHome, isShowNavbar: false },
            })
        );
        navigate(routes.client.palmistryV1TrialPayment());
    };

    // useEffect(() => {
    //     metricService.reachGoal(EGoals.TRIAL_CHOICE_PAGE_VISIT, [EMetrics.YANDEX, EMetrics.KLAVIYO]);
    //     metricService.reachGoal(EGoals.AURA_TRIAL_CHOICE_PAGE_VISIT, [EMetrics.KLAVIYO]);
    // }, []);

    useEffect(() => {
        if (popularProduct) {
            dispatch(actions.payment.update({
                activeProduct: popularProduct
            }))
            setIsDisabled(false);
        }
    }, [popularProduct])

    return (
        <div className={styles.container}>
            {!isPending && (
                <>
                    <EmailSubstrate className={styles["email-substrate"]} email={email} />
                    {/* {!isLongText && (
            <Title className={styles.title} variant="h2">
              {getText("text.0")}
            </Title>
          )} */}
                    {/* <p className={styles.text}>{getLongText(locale)}</p> */}
                    <p className={styles.text}>
                        {translate("/trial-choice.v1.paragraph1", {
                            br: <br />
                        })}
                    </p>
                    <ul className={styles.list}>
                        {Array.from({ length: 4 }).map((_, index) => (
                            <li key={index} className={styles.listItem}>
                                {translate(`/trial-choice.v1.points.point${index + 1}`)}
                            </li>
                        ))}
                    </ul>
                    <p
                        className={styles.text}
                        style={{
                            marginTop: "16px"
                        }}
                    >
                        {translate("/trial-choice.v1.paragraph2", {
                            price: addCurrency((Math.max(...products.map(product => product.trialPrice || 0)) / 100).toFixed(2), currency)
                        })}
                    </p>
                    <div className={styles["price-container"]}>
                        <p className={styles["auxiliary-text"]}>{translate(String(getProperty("text.1")?.value))}</p>
                        <PriceList
                            products={products}
                            activeItem={selectedPrice}
                            classNameItem={styles["price-item"]}
                            classNameItemActive={`${styles["price-item-active"]}`}
                            classNamePricesContainer={styles["prices-container"]}
                            currency={currency}
                            click={handlePriceItem}
                            preActiveItems={[popularProduct?.id]}
                        />
                    </div>

                    {!!products.length && <EmailsList
                        products={products.map(product => ({ ...product, weight: productWeights[product.trialPrice || 100] }))}
                    />}

                    <Button
                        className={styles.button}
                        disabled={isDisabled}
                        onClick={handleNext}
                    >
                        {translate("next")}
                    </Button>
                </>
            )}
            {isPending && <Loader className={styles.loader} />}
        </div>
    );
}

export default TrialChoiceV1