"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";

import { useRetainingStore } from "@/providers/retaining-store-provider";
import { ROUTES } from "@/shared/constants/client-routes";
import { ERetainingFunnel } from "@/types";

import { RetainingButton } from "../..";

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

export interface ChangeMindAnswer {
  id: number;
  title: string;
}

interface ButtonsProps {
  answers: ChangeMindAnswer[];
}

export default function Buttons({ answers }: ButtonsProps) {
  const router = useRouter();
  // usePreloadImages([
  //     images("vip_member.png")
  // ])

  const [activeAnswer, setActiveAnswer] = useState<ChangeMindAnswer | null>(
    null
  );
  const { funnel, addChoice } = useRetainingStore(state => state);

  const handleNext = (answer: ChangeMindAnswer) => {
    setActiveAnswer(answer);

    // Track user choice
    addChoice({
      step: "change-mind",
      choiceId: answer.id,
      choiceTitle: answer.title,
    });

    const timer = setTimeout(() => {
      if (funnel === ERetainingFunnel.Red) {
        router.push(ROUTES.retainingFunnelStopFor30Days());
      }
      if (funnel === ERetainingFunnel.Green) {
        router.push(ROUTES.retainingFunnelSecondChance());
      }
      if (funnel === ERetainingFunnel.Purple) {
        router.push(ROUTES.retainingFunnelSecondChance());
      }
    }, 1000);
    return () => clearTimeout(timer);
  };

  return (
    <div className={styles.answers}>
      {answers.map(answer => (
        <RetainingButton
          key={answer.id}
          className={styles.answer}
          active={activeAnswer?.id === answer.id}
          onClick={() => handleNext(answer)}
        >
          {answer.title}
        </RetainingButton>
      ))}
    </div>
  );
}
