"use client";

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

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

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

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

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

  const offers = useMemo(() => data?.variants ?? [], [data]);
  const [allOffers, setAllOffers] = useState<IFunnelPaymentVariant[]>([]);
  const [activeOffer, setActiveOffer] = useState<string>("");
  const { setSelectedProduct } = useProductSelection();

  useEffect(() => {
    const skipOffer: IFunnelPaymentVariant = {
      id: "main_skip_offer",
      key: "main.skip.offer",
      type: "one_time",
      price: 0,
      oldPrice: 0,
    };

    const offersWithSkip = [...offers, skipOffer];
    setAllOffers(offersWithSkip);
    setActiveOffer(offers[0]?.id || skipOffer.id);

    // Устанавливаем первый продукт как выбранный по умолчанию
    if (offers[0]) {
      setSelectedProduct(offers[0]);
    }
  }, [offers, setSelectedProduct]);

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

  return (
    <div className={styles.container}>
      {allOffers.map(offer => (
        <Offer
          offer={offer}
          key={offer.id}
          isActive={activeOffer === offer.id}
          onClick={() => handleOfferClick(offer)}
        />
      ))}
    </div>
  );
}

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