"use client";

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

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

import { useProductSelection } from "../ProductSelectionContext";

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

import { Offer } from "..";

interface OffersProps {
  products: Promise<IFunnelPaymentVariant[]>;
}

export default function Offers({ products }: OffersProps) {
  const offers = use(products);
  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" }} />;
}
