import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:http_parser/http_parser.dart';

import '../../../core/network/api_client.dart';
import '../models/incident.dart';

final incidentServiceProvider = Provider<IncidentService>((ref) {
  return IncidentService(ref.read(apiClientProvider));
});

class IncidentService {
  IncidentService(this._dio);
  final Dio _dio;

  Future<List<UnitOption>> listUnits() async {
    final res = await _dio.get<List<dynamic>>(
      '/incidents/units',
      options: Options(
        receiveTimeout: const Duration(seconds: 6),
        sendTimeout: const Duration(seconds: 6),
      ),
    );
    return (res.data ?? [])
        .whereType<Map>()
        .map((e) => UnitOption.fromJson(Map<String, dynamic>.from(e)))
        .toList();
  }

  /// Devuelve la unidad asignada al domicilio (vía su ruta).
  /// `null` si el backend responde 404 (sin ruta o sin unidad).
  Future<UnitOption?> getAddressUnit(String addressId) async {
    try {
      final res = await _dio.get<Map<String, dynamic>>(
        '/addresses/$addressId/unit',
        options: Options(
          receiveTimeout: const Duration(seconds: 6),
          sendTimeout: const Duration(seconds: 6),
        ),
      );
      if (res.data == null) return null;
      return UnitOption.fromJson(res.data!);
    } on DioException catch (e) {
      if (e.response?.statusCode == 404) return null;
      rethrow;
    }
  }

  Future<IncidentReport> createIncident({
    required String category,
    required String description,
    int? unitId,
    File? photo,
  }) async {
    final form = FormData.fromMap({
      'category': category,
      'description': description,
      if (unitId != null) 'unit_id': unitId,
      if (photo != null)
        'photo': await MultipartFile.fromFile(
          photo.path,
          filename: photo.path.split(Platform.pathSeparator).last,
          contentType: MediaType('image', _ext(photo.path)),
        ),
    });

    final res = await _dio.post<Map<String, dynamic>>(
      '/incidents',
      data: form,
      options: Options(contentType: 'multipart/form-data'),
    );
    return IncidentReport.fromJson(res.data!);
  }

  Future<List<IncidentReport>> myIncidents() async {
    final res = await _dio.get<List<dynamic>>('/incidents/me');
    return (res.data ?? [])
        .whereType<Map>()
        .map((e) => IncidentReport.fromJson(Map<String, dynamic>.from(e)))
        .toList();
  }

  String _ext(String path) {
    final dot = path.lastIndexOf('.');
    if (dot == -1) return 'jpeg';
    final ext = path.substring(dot + 1).toLowerCase();
    if (ext == 'jpg') return 'jpeg';
    return ext;
  }
}
