import {
  Zone,
  ZoneFormData,
  MowingHistoryResponse,
  MowingStats,
  MowingFormData,
  Mower,
  MowerFormData,
  BulkMowingFormData,
  SeasonSettings
} from '../types/zone';

const APP_MODE = import.meta.env.VITE_ENV;
const API_BASE = APP_MODE == "development" ? new URL('api', import.meta.env.VITE_API_URL).toString() : import.meta.env.VITE_API_URL;

export const api = {
  async getZones(): Promise<Zone[]> {
    const response = await fetch(`${API_BASE}/zones`);
    //console.log(`${APP_MODE}`);
    //console.log(`${API_BASE}/zones`);
    if (!response.ok) throw new Error('Failed to fetch zones');
    return response.json();
  },

  async getZone(id: number): Promise<Zone> {
    const response = await fetch(`${API_BASE}/zones/${id}`);
    if (!response.ok) throw new Error('Failed to fetch zone');
    return response.json();
  },

  async createZone(data: ZoneFormData): Promise<Zone> {
    const formData = new FormData();
    formData.append('name', data.name);
    formData.append('area', data.area.toString());
    formData.append('scheduleType', data.scheduleType);
    
    if (data.scheduleType === 'interval' && data.intervalDays) {
      formData.append('intervalDays', data.intervalDays.toString());
    } else if (data.scheduleType === 'specific' && data.nextMowDate) {
      formData.append('nextMowDate', data.nextMowDate);
    }
    
    if (data.image) {
      formData.append('image', data.image);
    }

    const response = await fetch(`${API_BASE}/zones`, {
      method: 'POST',
      body: formData,
    });
    if (!response.ok) throw new Error('Failed to create zone');
    return response.json();
  },

  async updateZone(id: number, data: ZoneFormData): Promise<Zone> {
    const formData = new FormData();
    formData.append('name', data.name);
    formData.append('area', data.area.toString());
    formData.append('scheduleType', data.scheduleType);
    
    if (data.lastMowedDate) {
      formData.append('lastMowedDate', data.lastMowedDate);
    }
    
    if (data.scheduleType === 'interval' && data.intervalDays) {
      formData.append('intervalDays', data.intervalDays.toString());
    } else if (data.scheduleType === 'specific' && data.nextMowDate) {
      formData.append('nextMowDate', data.nextMowDate);
    }
    
    if (data.image) {
      formData.append('image', data.image);
    }

    const response = await fetch(`${API_BASE}/zones/${id}`, {
      method: 'PUT',
      body: formData,
    });
    console.log(response);
    if (!response.ok) throw new Error('Ошибка изменения данных зоны');
    return response.json();
  },

  async deleteZone(id: number): Promise<void> {
    const response = await fetch(`${API_BASE}/zones/${id}`, {
      method: 'DELETE',
    });
    if (!response.ok) throw new Error('Failed to delete zone');
  },

  async markAsMowed(id: number, data?: MowingFormData): Promise<Zone> {
    const response = await fetch(`${API_BASE}/zones/${id}/mow`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data || {}),
    });
    if (!response.ok) throw new Error('Failed to mark as mowed');
    return response.json();
  },

  async markAsTrimmed(id: number, data?: MowingFormData): Promise<void> {
    const response = await fetch(`${API_BASE}/zones/${id}/trim`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data || {}),
    });
    if (!response.ok) throw new Error('Failed to mark as trimmed');
  },
  async bulkMarkAsMowed(data: BulkMowingFormData): Promise<void> {
    const response = await fetch(`${API_BASE}/zones/bulk-mow`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });
    if (!response.ok) throw new Error('Failed to record bulk mowing session');
  },

  async getMowingHistory(zoneId?: number, limit = 10, offset = 0): Promise<MowingHistoryResponse> {
    const params = new URLSearchParams({
      limit: limit.toString(),
      offset: offset.toString(),
    });
    if (zoneId) {
      params.append('zoneId', zoneId.toString());
    }

    const response = await fetch(`${API_BASE}/history?${params}`);
    if (!response.ok) throw new Error('Failed to fetch mowing history');
    return response.json();
  },

  async getMowingStats(period = 30): Promise<MowingStats> {
    const response = await fetch(`${API_BASE}/history/stats?period=${period}`);
    if (!response.ok) throw new Error('Failed to fetch mowing statistics');
    return response.json();
  },

  async getMowers(): Promise<Mower[]> {
    const response = await fetch(`${API_BASE}/mowers`);
    if (!response.ok) throw new Error('Failed to fetch mowers');
    return response.json();
  },

  async createMower(data: MowerFormData): Promise<Mower> {
    const response = await fetch(`${API_BASE}/mowers`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });
    if (!response.ok) throw new Error('Failed to create mower');
    return response.json();
  },

  async getSeasonSettings(): Promise<SeasonSettings> {
    const response = await fetch(`${API_BASE}/season`);
    if (!response.ok) throw new Error('Failed to fetch season settings');
    return response.json();
  },

  async updateSeasonSettings(data: SeasonSettings): Promise<SeasonSettings> {
    const response = await fetch(`${API_BASE}/season`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });
    if (!response.ok) throw new Error('Failed to update season settings');
    return response.json();
  },

};