"use client";

import { createStore } from "zustand";
import { persist } from "zustand/middleware";

import { UserSubscription } from "@/entities/subscriptions/types";

export enum ERetainingFunnel {
  Red = "red",
  Green = "green",
  Purple = "purple",
  Stay50 = "stay50",
}

export interface RetainingChoice {
  step: string;
  choiceId: string | number;
  choiceTitle: string;
  timestamp: number;
}

export interface RetainingJourney {
  startedAt: number;
  updatedAt: number;
  currentStep: string;
  choices: RetainingChoice[];
  funnel: ERetainingFunnel;
  completedSteps: string[];
}

interface RetainingState {
  funnel: ERetainingFunnel;
  cancellingSubscription: UserSubscription | null;
  journey: RetainingJourney | null;
}

export type RetainingActions = {
  setFunnel: (funnel: ERetainingFunnel) => void;
  setCancellingSubscription: (cancellingSubscription: UserSubscription) => void;
  setRetainingData: (data: {
    funnel: ERetainingFunnel;
    cancellingSubscription: UserSubscription;
  }) => void;
  clearRetainingData: () => void;

  // Journey tracking methods
  startJourney: (subscriptionId: string) => void;
  addChoice: (choice: Omit<RetainingChoice, "timestamp">) => void;
  updateCurrentStep: (step: string) => void;
  completeStep: (step: string) => void;
  getJourneyData: () => RetainingJourney | null;
};

export type RetainingStore = RetainingState & RetainingActions;

const initialState: RetainingState = {
  funnel: ERetainingFunnel.Red,
  cancellingSubscription: null,
  journey: null,
};

export const createRetainingStore = (
  initState: RetainingState = initialState
) => {
  return createStore<RetainingStore>()(
    persist(
      (set, get) => ({
        ...initState,
        setFunnel: (funnel: ERetainingFunnel) => set({ funnel }),
        setCancellingSubscription: (cancellingSubscription: UserSubscription) =>
          set({ cancellingSubscription }),
        setRetainingData: (data: {
          funnel: ERetainingFunnel;
          cancellingSubscription: UserSubscription;
        }) => set(data),
        clearRetainingData: () => set(initialState),

        // Journey tracking methods
        startJourney: (_subscriptionId: string) => {
          const now = Date.now();
          const journey: RetainingJourney = {
            startedAt: now,
            updatedAt: now,
            currentStep: "appreciate-choice",
            choices: [],
            funnel: ERetainingFunnel.Red,
            completedSteps: [],
          };
          set({ journey });
        },

        addChoice: (choice: Omit<RetainingChoice, "timestamp">) => {
          const state = get();
          if (!state.journey) return;
          const newChoice: RetainingChoice = {
            ...choice,
            timestamp: Date.now(),
          };

          // Remove any existing choice for the same step (user changed mind)
          const filteredChoices = state.journey.choices.filter(
            c => c.step !== choice.step
          );

          const updatedJourney: RetainingJourney = {
            ...state.journey,
            choices: [...filteredChoices, newChoice],
            updatedAt: Date.now(),
          };

          set({ journey: updatedJourney });
        },

        updateCurrentStep: (step: string) => {
          const state = get();
          if (!state.journey) return;

          const updatedJourney: RetainingJourney = {
            ...state.journey,
            currentStep: step,
            updatedAt: Date.now(),
          };

          set({ journey: updatedJourney });
        },

        completeStep: (step: string) => {
          const state = get();
          if (!state.journey) return;

          const completedSteps = [...state.journey.completedSteps];
          if (!completedSteps.includes(step)) {
            completedSteps.push(step);
          }

          const updatedJourney: RetainingJourney = {
            ...state.journey,
            completedSteps,
            updatedAt: Date.now(),
          };

          set({ journey: updatedJourney });
        },

        getJourneyData: () => {
          const state = get();
          return state.journey;
        },
      }),
      { name: "retaining-storage" }
    )
  );
};
