import apiClient from '@/lib/api/client';

export interface FeedingData {
  childId: string;
  type: 'breast_left' | 'breast_right' | 'breast_both' | 'bottle' | 'solid';
  duration?: number;
  amount?: number;
  unit?: 'ml' | 'oz';
  notes?: string;
  timestamp?: string;
}

export interface SleepData {
  childId: string;
  startTime: string;
  endTime: string;
  quality: 'excellent' | 'good' | 'fair' | 'poor';
  notes?: string;
}

export interface DiaperData {
  childId: string;
  type: 'wet' | 'dirty' | 'both' | 'clean';
  timestamp: string;
  rash: boolean;
  notes?: string;
}

export interface Activity {
  id: string;
  childId: string;
  type: 'feeding' | 'sleep' | 'diaper';
  timestamp: string;
  data: Record<string, any>;
  createdAt: string;
  updatedAt: string;
}

export interface DailySummary {
  date: string;
  feedingCount: number;
  sleepHours: number;
  diaperCount: number;
  activities: Activity[];
}

class TrackingService {
  async logFeeding(data: FeedingData): Promise<Activity> {
    const response = await apiClient.post('/api/v1/activities', {
      childId: data.childId,
      type: 'feeding',
      timestamp: data.timestamp || new Date().toISOString(),
      data: {
        feedingType: data.type,
        duration: data.duration,
        amount: data.amount,
        unit: data.unit,
        notes: data.notes,
      },
    });
    return response.data.data;
  }

  async logSleep(data: SleepData): Promise<Activity> {
    const response = await apiClient.post('/api/v1/activities', {
      childId: data.childId,
      type: 'sleep',
      timestamp: data.startTime,
      data: {
        startTime: data.startTime,
        endTime: data.endTime,
        quality: data.quality,
        duration: this.calculateDuration(data.startTime, data.endTime),
        notes: data.notes,
      },
    });
    return response.data.data;
  }

  async logDiaper(data: DiaperData): Promise<Activity> {
    const response = await apiClient.post('/api/v1/activities', {
      childId: data.childId,
      type: 'diaper',
      timestamp: data.timestamp,
      data: {
        diaperType: data.type,
        rash: data.rash,
        notes: data.notes,
      },
    });
    return response.data.data;
  }

  async getActivities(childId: string, filters?: {
    type?: string;
    startDate?: string;
    endDate?: string;
    limit?: number;
  }): Promise<Activity[]> {
    const params = new URLSearchParams({
      childId,
      ...filters,
    } as Record<string, string>);

    const response = await apiClient.get(`/api/v1/activities?${params.toString()}`);
    return response.data.data;
  }

  async getActivityById(activityId: string): Promise<Activity> {
    const response = await apiClient.get(`/api/v1/activities/${activityId}`);
    return response.data.data;
  }

  async updateActivity(activityId: string, data: Partial<Activity>): Promise<Activity> {
    const response = await apiClient.patch(`/api/v1/activities/${activityId}`, data);
    return response.data.data;
  }

  async deleteActivity(activityId: string): Promise<void> {
    await apiClient.delete(`/api/v1/activities/${activityId}`);
  }

  async getDailySummary(childId: string, date?: string): Promise<DailySummary> {
    const params = new URLSearchParams({
      childId,
      date: date || new Date().toISOString().split('T')[0],
    });

    const response = await apiClient.get(`/api/v1/activities/daily-summary?${params.toString()}`);
    return response.data.data;
  }

  private calculateDuration(startTime: string, endTime: string): number {
    const start = new Date(startTime);
    const end = new Date(endTime);
    return Math.floor((end.getTime() - start.getTime()) / 1000 / 60); // duration in minutes
  }
}

export const trackingService = new TrackingService();
