/**
 * Workout Program Store
 * Tracks completion of body-zone workout programs
 */

import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import AsyncStorage from '@react-native-async-storage/async-storage'
import type { WorkoutProgram } from '../types/workoutProgram'

// ─── Types ──────────────────────────────────────────────────────

interface ProgramCompletion {
  completedAt: string
  tabatasCompleted: number[]
}

interface WorkoutProgramState {
  // Completion tracking
  completions: Record<string, ProgramCompletion>

  // Actions
  completeProgram: (programId: string, tabataPosition?: number) => void
  resetProgram: (programId: string) => void

  // Getters
  isProgramCompleted: (programId: string) => boolean
  getCompletedCount: () => number
  getRecommendedNext: (programs: WorkoutProgram[]) => WorkoutProgram | null
  getTabatasCompleted: (programId: string) => number[]
}

// ─── Store ──────────────────────────────────────────────────────

export const useWorkoutProgramStore = create<WorkoutProgramState>()(
  persist(
    (set, get) => ({
      completions: {},

      completeProgram: (programId, tabataPosition) => {
        set(state => {
          const existing = state.completions[programId]
          if (tabataPosition !== undefined) {
            // Mark specific tabata as completed
            const tabatasCompleted = existing
              ? [...existing.tabatasCompleted.filter(t => t !== tabataPosition), tabataPosition]
              : [tabataPosition]
            const isDone = tabatasCompleted.length >= 3
            return {
              completions: {
                ...state.completions,
                [programId]: {
                  completedAt: isDone ? new Date().toISOString() : existing?.completedAt ?? '',
                  tabatasCompleted,
                },
              },
            }
          }
          // Mark entire program as completed
          return {
            completions: {
              ...state.completions,
              [programId]: {
                completedAt: new Date().toISOString(),
                tabatasCompleted: [1, 2, 3],
              },
            },
          }
        })
      },

      resetProgram: (programId) => {
        set(state => {
          const { [programId]: _, ...rest } = state.completions
          return { completions: rest }
        })
      },

      isProgramCompleted: (programId) => {
        const completion = get().completions[programId]
        return !!completion && completion.tabatasCompleted.length >= 3
      },

      getCompletedCount: () => {
        return Object.values(get().completions).filter(
          c => c.tabatasCompleted.length >= 3,
        ).length
      },

      getRecommendedNext: (programs) => {
        const { completions } = get()
        // Find first incomplete program, prioritizing Beginner → Intermediate → Advanced
        const levelOrder = { Beginner: 0, Intermediate: 1, Advanced: 2 }
        const sorted = [...programs].sort(
          (a, b) => levelOrder[a.level] - levelOrder[b.level],
        )
        return (
          sorted.find(p => {
            const c = completions[p.id]
            return !c || c.tabatasCompleted.length < 3
          }) ?? null
        )
      },

      getTabatasCompleted: (programId) => {
        return get().completions[programId]?.tabatasCompleted ?? []
      },
    }),
    {
      name: 'tabatafit-workout-program-storage',
      storage: {
        getItem: async (name) => {
          const value = await AsyncStorage.getItem(name)
          return value ? JSON.parse(value) : null
        },
        setItem: async (name, value) => {
          await AsyncStorage.setItem(name, JSON.stringify(value))
        },
        removeItem: async (name) => {
          await AsyncStorage.removeItem(name)
        },
      },
    },
  ),
)
