import 'package:dio/dio.dart';
import '../models/vehicle.dart';
import 'api_client.dart';

class MaintenanceLog {
  final String id;
  final String type;
  final String? description;
  final int? cost;
  final int? mileage;
  final DateTime performedAt;
  final DateTime? nextDueAt;
  final int? nextDueMileage;

  const MaintenanceLog({
    required this.id,
    required this.type,
    this.description,
    this.cost,
    this.mileage,
    required this.performedAt,
    this.nextDueAt,
    this.nextDueMileage,
  });

  factory MaintenanceLog.fromJson(Map<String, dynamic> json) => MaintenanceLog(
        id: json['id'] as String,
        type: json['type'] as String,
        description: json['description'] as String?,
        cost: json['cost'] as int?,
        mileage: json['mileage'] as int?,
        performedAt: DateTime.parse(json['performedAt'] as String),
        nextDueAt: json['nextDueAt'] != null
            ? DateTime.parse(json['nextDueAt'] as String)
            : null,
        nextDueMileage: json['nextDueMileage'] as int?,
      );
}

class CalendarEvent {
  final String id;
  final String type; // RESERVATION | MAINTENANCE | BLOCK
  final DateTime startDate;
  final DateTime endDate;
  final String? status;
  final String label;

  const CalendarEvent({
    required this.id,
    required this.type,
    required this.startDate,
    required this.endDate,
    this.status,
    required this.label,
  });

  factory CalendarEvent.fromJson(Map<String, dynamic> json) => CalendarEvent(
        id: json['id'] as String,
        type: json['type'] as String,
        startDate: DateTime.parse(json['startDate'] as String),
        endDate: DateTime.parse(json['endDate'] as String),
        status: json['status'] as String?,
        label: json['label'] as String,
      );
}

class VehicleService {
  final _client = ApiClient.instance;

  Future<VehicleListResponse> getVehicles({
    int page = 1,
    int pageSize = 20,
    String? status,
    String? search,
  }) async {
    final res = await _client.get('/vehicles', params: {
      'page': page,
      'pageSize': pageSize,
      'status': ?status,
      if (search != null && search.isNotEmpty) 'search': search,
    });
    return VehicleListResponse.fromJson(res.data as Map<String, dynamic>);
  }

  Future<Vehicle> getVehicle(String id) async {
    final res = await _client.get('/vehicles/$id');
    return Vehicle.fromJson(res.data as Map<String, dynamic>);
  }

  Future<Vehicle> createVehicle(Map<String, dynamic> data) async {
    final res = await _client.post('/vehicles', data: data);
    return Vehicle.fromJson(res.data as Map<String, dynamic>);
  }

  Future<Vehicle> updateVehicle(String id, Map<String, dynamic> data) async {
    final res = await _client.patch('/vehicles/$id', data: data);
    return Vehicle.fromJson(res.data as Map<String, dynamic>);
  }

  Future<void> deleteVehicle(String id) async {
    await _client.delete('/vehicles/$id');
  }

  Future<void> togglePublish(String id, bool publish) async {
    await _client.patch('/vehicles/$id/publish', data: {'isPublished': publish});
  }

  Future<Vehicle> uploadPhotos(String id, List<String> filePaths) async {
    final formData = FormData.fromMap({
      'photos': [
        for (final path in filePaths)
          await MultipartFile.fromFile(path),
      ],
    });
    final res = await _client.dio.post(
      '/vehicles/$id/photos',
      data: formData,
      options: Options(headers: {'Content-Type': 'multipart/form-data'}),
    );
    final body = res.data;
    final payload = (body is Map<String, dynamic> && body.containsKey('data'))
        ? body['data']
        : body;
    return Vehicle.fromJson(payload as Map<String, dynamic>);
  }

  Future<Vehicle> deletePhoto(String id, int idx) async {
    final res = await _client.delete('/vehicles/$id/photos/$idx');
    return Vehicle.fromJson(res.data as Map<String, dynamic>);
  }

  Future<List<MaintenanceLog>> getMaintenance(String id) async {
    final res = await _client.get('/vehicles/$id/maintenance');
    final list = res.data as List<dynamic>;
    return list
        .map((e) => MaintenanceLog.fromJson(e as Map<String, dynamic>))
        .toList();
  }

  Future<MaintenanceLog> addMaintenance(
      String id, Map<String, dynamic> data) async {
    final res = await _client.post('/vehicles/$id/maintenance', data: data);
    return MaintenanceLog.fromJson(res.data as Map<String, dynamic>);
  }

  Future<List<CalendarEvent>> getCalendar(
      String id, int year, int month) async {
    final res = await _client.get('/vehicles/$id/calendar',
        params: {'year': year, 'month': month});
    final list = res.data as List<dynamic>;
    return list
        .map((e) => CalendarEvent.fromJson(e as Map<String, dynamic>))
        .toList();
  }

  Future<CalendarEvent> createCalendarBlock(
      String id, Map<String, dynamic> data) async {
    final res =
        await _client.post('/vehicles/$id/calendar/blocks', data: data);
    return CalendarEvent.fromJson(res.data as Map<String, dynamic>);
  }

  Future<void> deleteCalendarBlock(String id, String blockId) async {
    await _client.delete('/vehicles/$id/calendar/blocks/$blockId');
  }
}
