"use client";

import { useEffect, useMemo, useState } from "react";

import { Skeleton } from "@/components/ui";
import { IFunnelPaymentVariant } from "@/entities/session/funnel/types";

import { useMultiPageNavigationContext, VideoGuidesOffer } from "..";
import { useProductSelection } from "../ProductSelectionProvider";

import styles from "./VideoGuidesOffers.module.scss";

// Зашитые проценты скидки: первый товар - 50%, остальные - 45%
const FIRST_PRODUCT_DISCOUNT = 50;
const OTHER_PRODUCTS_DISCOUNT = 45;

export default function VideoGuidesOffers() {
  const { navigation } = useMultiPageNavigationContext();
  const data = navigation.currentItem;

  const offers = useMemo(() => {
    // Используем данные с сервера и добавляем oldPrice на основе зашитого процента скидки
    const serverOffers = data?.variants ?? [];
    return serverOffers.map((offer: IFunnelPaymentVariant, index: number) => {
      // Первый товар имеет скидку 50%, остальные - 45%
      const discountPercent =
        index === 0 ? FIRST_PRODUCT_DISCOUNT : OTHER_PRODUCTS_DISCOUNT;
      // Рассчитываем oldPrice: если price это цена со скидкой X%, то oldPrice = price / (1 - X/100)
      const oldPrice = Math.round(offer.price / (1 - discountPercent / 100));
      return {
        ...offer,
        oldPrice,
      };
    });
  }, [data]);
  const [activeOffer, setActiveOffer] = useState<string>("");
  const { setSelectedProduct } = useProductSelection();

  useEffect(() => {
    if (offers[0]) {
      setActiveOffer(offers[0]?.id);
      setSelectedProduct(offers[0]);
    }
  }, [offers, setSelectedProduct]);

  const handleOfferClick = (offer: IFunnelPaymentVariant) => {
    setActiveOffer(offer.id);
    setSelectedProduct(offer);
  };

  return (
    <div className={styles.container}>
      {offers.map((offer, index) => (
        <VideoGuidesOffer
          offer={offer}
          key={offer.id}
          isActive={activeOffer === offer.id}
          isFirstOffer={index === 0}
          onClick={() => handleOfferClick(offer)}
        />
      ))}
    </div>
  );
}

export function VideoGuidesOffersSkeleton() {
  return <Skeleton style={{ height: "400px" }} />;
}
