import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';

class ApiService {
  // Use 10.0.2.2 for Android Emulator, localhost for iOS/Web
  static final String baseUrl = Platform.isAndroid
      ? 'http://10.0.2.2:3000'
      : 'http://localhost:3000';

  final Dio _dio = Dio(
    BaseOptions(
      baseUrl: baseUrl,
      connectTimeout: const Duration(seconds: 10),
      receiveTimeout: const Duration(seconds: 10),
    ),
  );

  // Get Initial Master Data (Groups, Species, Breeds, Diseases)
  Future<Map<String, dynamic>> getInitialData() async {
    try {
      final response = await _dio.get('/common/initial-data');
      return response.data;
    } catch (e) {
      debugPrint('Error fetching initial data: $e');
      rethrow;
    }
  }

  // Register Pet
  Future<Map<String, dynamic>> registerPet({
    required int userId,
    required String name,
    required String species,
    required String breed,
    required String gender,
    required bool isNeutered,
    DateTime? birthDate,
    required bool isDateUnknown,
    double? weight,
    String? registrationNumber,
    File? profileImage,
    List<String>? diseases,
    List<String>? pastDiseases,
    List<String>? healthConcerns,
  }) async {
    try {
      final formData = await _createPetFormData(
        userId: userId,
        name: name,
        species: species,
        breed: breed,
        gender: gender,
        isNeutered: isNeutered,
        birthDate: birthDate,
        isDateUnknown: isDateUnknown,
        weight: weight,
        registrationNumber: registrationNumber,
        profileImage: profileImage,
        diseases: diseases,
        pastDiseases: pastDiseases,
        healthConcerns: healthConcerns,
      );

      final response = await _dio.post('/pets', data: formData);
      return response.data;
    } catch (e) {
      debugPrint('Error registering pet: $e');
      rethrow;
    }
  }

  Future<Map<String, dynamic>> updatePet({
    required int petId,
    required String name,
    required String species,
    required String breed,
    required String gender,
    required bool isNeutered,
    DateTime? birthDate,
    required bool isDateUnknown,
    double? weight,
    String? registrationNumber,
    File? profileImage,
    List<String>? diseases,
    List<String>? pastDiseases,
    List<String>? healthConcerns,
  }) async {
    try {
      final formData = await _createPetFormData(
        name: name,
        species: species,
        breed: breed,
        gender: gender,
        isNeutered: isNeutered,
        birthDate: birthDate,
        isDateUnknown: isDateUnknown,
        weight: weight,
        registrationNumber: registrationNumber,
        profileImage: profileImage,
        diseases: diseases,
        pastDiseases: pastDiseases,
        healthConcerns: healthConcerns,
      );

      final response = await _dio.put('/pets/$petId', data: formData);
      return response.data;
    } catch (e) {
      debugPrint('Error updating pet: $e');
      rethrow;
    }
  }

  // Helper: Create FormData
  Future<FormData> _createPetFormData({
    required String name,
    required String species,
    required String breed,
    required String gender,
    required bool isNeutered,
    DateTime? birthDate,
    required bool isDateUnknown,
    double? weight,
    String? registrationNumber,
    File? profileImage,
    List<String>? diseases,
    List<String>? pastDiseases,
    List<String>? healthConcerns,
    int? userId, // Optional (only for register)
  }) async {
    final map = {
      if (userId != null) 'userId': userId,
      'name': name,
      'species': species,
      'breed': breed,
      'gender': gender,
      'isNeutered': isNeutered,
      'birthDate': birthDate?.toIso8601String(),
      'isDateUnknown': isDateUnknown,
      'weight': weight,
      'registrationNumber': registrationNumber,
      'diseases': diseases != null ? jsonEncode(diseases) : '[]',
      'pastDiseases': pastDiseases != null ? jsonEncode(pastDiseases) : '[]',
      'healthConcerns': healthConcerns != null
          ? jsonEncode(healthConcerns)
          : '[]',
    };

    if (profileImage != null) {
      map['profileImage'] = await MultipartFile.fromFile(
        profileImage.path,
        filename: profileImage.path.split('/').last,
      );
    }

    return FormData.fromMap(map);
  }

  // Get Pets
  Future<List<dynamic>> getPets(int userId) async {
    try {
      final response = await _dio.get(
        '/pets',
        queryParameters: {'userId': userId},
      );
      return response.data;
    } catch (e) {
      debugPrint('Error fetching pets: $e');
      rethrow;
    }
  }

  // --- Schedule APIs ---

  // Get Monthly Schedules
  Future<List<dynamic>> getSchedules({
    required String petId,
    required int year,
    required int month,
  }) async {
    try {
      final response = await _dio.get(
        '/schedules',
        queryParameters: {'petId': petId, 'year': year, 'month': month},
      );
      return response.data;
    } catch (e) {
      debugPrint('Error fetching schedules: $e');
      rethrow;
    }
  }

  // Create Schedule
  Future<Map<String, dynamic>> createSchedule(Map<String, dynamic> data) async {
    try {
      final response = await _dio.post('/schedules', data: data);
      return response.data;
    } catch (e) {
      debugPrint('Error creating schedule: $e');
      rethrow;
    }
  }

  // Update Schedule
  Future<Map<String, dynamic>> updateSchedule(
    String id,
    Map<String, dynamic> data,
  ) async {
    try {
      final response = await _dio.put('/schedules/$id', data: data);
      return response.data;
    } catch (e) {
      debugPrint('Error updating schedule: $e');
      rethrow;
    }
  }

  // Delete Schedule
  Future<void> deleteSchedule(String id) async {
    try {
      await _dio.delete('/schedules/$id');
    } catch (e) {
      debugPrint('Error deleting schedule: $e');
      rethrow;
    }
  }
}
