"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 WhatReasonAnswer {
  id: number;
  title: string;
  funnel: ERetainingFunnel;
}

interface ButtonsProps {
  answers: WhatReasonAnswer[];
}

export default function Buttons({ answers }: ButtonsProps) {
  const router = useRouter();

  const { setFunnel, addChoice, updateCurrentStep } = useRetainingStore(
    state => state
  );

  const [activeAnswer, setActiveAnswer] = useState<WhatReasonAnswer | null>(
    null
  );

  const handleNext = (answer: WhatReasonAnswer) => {
    setActiveAnswer(answer);
    setFunnel(answer.funnel);

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

    const timer = setTimeout(() => {
      let nextStep = "";
      let nextRoute = "";

      if (answer.funnel === ERetainingFunnel.Red) {
        nextStep = "second-chance";
        nextRoute = ROUTES.retainingFunnelSecondChance();
      }
      if (answer.funnel === ERetainingFunnel.Green) {
        nextStep = "stop-for-30-days";
        nextRoute = ROUTES.retainingFunnelStopFor30Days();
      }
      if (answer.funnel === ERetainingFunnel.Purple) {
        nextStep = "change-mind";
        nextRoute = ROUTES.retainingFunnelChangeMind();
      }

      if (nextStep) {
        updateCurrentStep(nextStep);
        router.push(nextRoute);
      }
    }, 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>
  );
}
