import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useApi } from '../composables/useApi'
import type { Activity, DataPoint, ZonesResponse, PowerCurveResponse, FitnessEntry, DiaryEntry, WeeklyStats, PersonalRecord, CalendarDay, MonthlyTrend, FtpDetection, WeeklyDigest, ProgressSummary } from '../types/models'

export const useActivitiesStore = defineStore('activities', () => {
  const { api } = useApi()
  const activities = ref<Activity[]>([])
  const total = ref(0)
  const loading = ref(false)

  async function fetchActivities(limit = 20, offset = 0) {
    loading.value = true
    try {
      const { data } = await api.get('/activities', { params: { limit, offset } })
      activities.value = data.items
      total.value = data.total
    } finally {
      loading.value = false
    }
  }

  async function fetchActivity(id: string): Promise<Activity> {
    const { data } = await api.get<Activity>(`/activities/${id}`)
    return data
  }

  async function fetchStream(id: string): Promise<DataPoint[]> {
    const { data } = await api.get<DataPoint[]>(`/activities/${id}/stream`)
    return data
  }

  async function fetchZones(id: string): Promise<ZonesResponse> {
    const { data } = await api.get<ZonesResponse>(`/activities/${id}/zones`)
    return data
  }

  async function fetchPowerCurve(id: string): Promise<PowerCurveResponse> {
    const { data } = await api.get<PowerCurveResponse>(`/activities/${id}/power-curve`)
    return data
  }

  async function uploadFit(file: File): Promise<Activity> {
    const form = new FormData()
    form.append('file', file)
    const { data } = await api.post<Activity>('/activities/upload', form)
    activities.value.unshift(data)
    total.value++
    return data
  }

  async function fetchAiSummary(id: string, force = false): Promise<string> {
    const { data } = await api.post<{ summary: string }>(`/activities/${id}/ai-summary`, { force })
    return data.summary
  }

  async function fetchFitness(days = 90): Promise<FitnessEntry[]> {
    const { data } = await api.get<FitnessEntry[]>('/rider/fitness', { params: { days } })
    return data
  }

  async function deleteActivity(id: string): Promise<void> {
    await api.delete(`/activities/${id}`)
    activities.value = activities.value.filter(a => a.id !== id)
    total.value--
  }

  async function fetchDiary(id: string): Promise<DiaryEntry> {
    const { data } = await api.get<DiaryEntry>(`/activities/${id}/diary`)
    return data
  }

  async function updateDiary(id: string, diary: Partial<DiaryEntry>): Promise<DiaryEntry> {
    const { data } = await api.put<DiaryEntry>(`/activities/${id}/diary`, diary)
    return data
  }

  async function fetchPersonalRecords(): Promise<PersonalRecord[]> {
    const { data } = await api.get<PersonalRecord[]>('/rider/personal-records')
    return data
  }

  async function fetchWeeklyStats(weeks = 8): Promise<WeeklyStats[]> {
    const { data } = await api.get<WeeklyStats[]>('/rider/weekly-stats', { params: { weeks } })
    return data
  }

  async function fetchActivityCalendar(months = 12): Promise<CalendarDay[]> {
    const { data } = await api.get<CalendarDay[]>('/rider/activity-calendar', { params: { months } })
    return data
  }

  async function fetchMonthlyTrends(months = 12): Promise<MonthlyTrend[]> {
    const { data } = await api.get<MonthlyTrend[]>('/rider/monthly-trends', { params: { months } })
    return data
  }

  async function detectFtp(): Promise<FtpDetection> {
    const { data } = await api.get<FtpDetection>('/rider/detect-ftp')
    return data
  }

  async function fetchWeeklyDigest(): Promise<WeeklyDigest> {
    const { data } = await api.get<WeeklyDigest>('/rider/weekly-digest')
    return data
  }

  async function fetchProgressSummary(): Promise<ProgressSummary> {
    const { data } = await api.get<ProgressSummary>('/rider/progress-summary')
    return data
  }

  async function fetchAiProgress(): Promise<string> {
    const { data } = await api.get<{ analysis: string }>('/rider/ai-progress')
    return data.analysis
  }

  return { activities, total, loading, fetchActivities, fetchActivity, fetchStream, fetchZones, fetchPowerCurve, uploadFit, fetchAiSummary, fetchFitness, deleteActivity, fetchDiary, updateDiary, fetchWeeklyStats, fetchPersonalRecords, fetchActivityCalendar, fetchMonthlyTrends, detectFtp, fetchWeeklyDigest, fetchProgressSummary, fetchAiProgress }
})
