/**
 * TabataFit Activity Store
 * Workout history, streak, stats — persisted via AsyncStorage
 */

import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import AsyncStorage from '@react-native-async-storage/async-storage'
import type { WorkoutResult, DayActivity } from '../types'

interface ActivityState {
  history: WorkoutResult[]
  streak: { current: number; longest: number }

  // Actions
  addWorkoutResult: (result: WorkoutResult) => void
}

function getDateString(timestamp: number) {
  return new Date(timestamp).toISOString().split('T')[0]
}

function calculateStreak(history: WorkoutResult[]): { current: number; longest: number } {
  if (history.length === 0) return { current: 0, longest: 0 }

  const uniqueDays = new Set(history.map(r => getDateString(r.completedAt)))
  const sortedDays = Array.from(uniqueDays).sort().reverse()

  const today = getDateString(Date.now())
  const yesterday = getDateString(Date.now() - 86400000)
  const hasRecentActivity = sortedDays[0] === today || sortedDays[0] === yesterday

  if (!hasRecentActivity) return { current: 0, longest: calculateLongest(sortedDays) }

  let current = 1
  for (let i = 0; i < sortedDays.length - 1; i++) {
    const diff = new Date(sortedDays[i]).getTime() - new Date(sortedDays[i + 1]).getTime()
    if (diff <= 86400000) {
      current++
    } else {
      break
    }
  }

  return { current, longest: Math.max(current, calculateLongest(sortedDays)) }
}

function calculateLongest(sortedDays: string[]): number {
  if (sortedDays.length === 0) return 0
  let longest = 1
  let streak = 1
  for (let i = 0; i < sortedDays.length - 1; i++) {
    const diff = new Date(sortedDays[i]).getTime() - new Date(sortedDays[i + 1]).getTime()
    if (diff <= 86400000) {
      streak++
      longest = Math.max(longest, streak)
    } else {
      streak = 1
    }
  }
  return longest
}

export const useActivityStore = create<ActivityState>()(
  persist(
    (set) => ({
      history: [],
      streak: { current: 0, longest: 0 },

      addWorkoutResult: (result) =>
        set((state) => {
          const newHistory = [result, ...state.history]
          const newStreak = calculateStreak(newHistory)
          return {
            history: newHistory,
            streak: newStreak,
          }
        }),
    }),
    {
      name: 'tabatafit-activity',
      storage: createJSONStorage(() => AsyncStorage),
    }
  )
)

// Standalone helper functions (use outside selectors)
export function getWeeklyActivity(history: WorkoutResult[]): DayActivity[] {
  const days: DayActivity[] = []
  const today = new Date()
  const startOfWeek = new Date(today)
  startOfWeek.setDate(today.getDate() - today.getDay())

  for (let i = 0; i < 7; i++) {
    const date = new Date(startOfWeek)
    date.setDate(startOfWeek.getDate() + i)
    const dateStr = getDateString(date.getTime())
    const workoutsOnDay = history.filter(
      r => getDateString(r.completedAt) === dateStr
    )
    days.push({
      date: String(i),
      completed: workoutsOnDay.length > 0,
      workoutCount: workoutsOnDay.length,
    })
  }
  return days
}
