import 'dart:convert';
import 'dart:io';

import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:get/get_state_manager/src/simple/get_controllers.dart';
import 'package:http/http.dart' as http;
import 'package:image_picker/image_picker.dart';
import 'package:nearle/Models/supportticket/support_ticket.dart';

class SupportTicketController extends GetxController {
  final RxList<SupportTicketModel> tickets = <SupportTicketModel>[].obs;
  final RxBool isLoading = true.obs;
  final RxString errorMessage = ''.obs;
  final RxBool isSubmitting = false.obs;

  @override
  void onInit() {
    super.onInit();
    fetchTickets();
  }

  Future<void> fetchTickets() async {
    try {
      isLoading(true);
      errorMessage('');

      const userId = 1242;
      final url = Uri.parse(
          'https://jupiter.nearle.app/live/api/v1/partners/getridersupport/?userid=$userId');

      final response = await http.get(url, headers: {
        'Accept': 'application/json',
      });

      if (response.statusCode != 200) {
        throw Exception('Server error: ${response.statusCode}');
      }

      final Map<String, dynamic> jsonResponse = json.decode(response.body);
      if (jsonResponse['status'] != true) {
        throw Exception(jsonResponse['message'] ?? 'Unknown error');
      }

      final List<dynamic> data = jsonResponse['data'];
      tickets.assignAll(data.map((e) => SupportTicketModel.fromJson(e)).toList());
    } catch (e) {
      errorMessage(e.toString());
    } finally {
      isLoading(false);
    }
  }

  Future<bool> createTicket({
    required int userid,
    required String category,
    required String priority,
    required String subject,
    required String issue,
    List<XFile>? attachments,
  }) async {
    try {
      isSubmitting(true);

      // Step 1: Upload image if attached (adjust endpoint if needed)
      String? imageUrl;
      if (attachments != null && attachments.isNotEmpty) {
        // For simplicity, assume first image; upload to a temp endpoint or your main one
        final imageFile = File(attachments.first.path);
        final imageBytes = await imageFile.readAsBytes();
        final imageName = attachments.first.name;

        // Example image upload (replace with your actual image upload endpoint)
        final uploadUrl = Uri.parse('https://jupiter.nearle.app/live/api/v1/partners/uploadimage/'); // Adjust URL
        final imageRequest = http.MultipartRequest('POST', uploadUrl)
          ..files.add(http.MultipartFile.fromBytes('image', imageBytes, filename: imageName));
        imageRequest.headers['Accept'] = 'application/json';

        final imageResponse = await imageRequest.send();
        if (imageResponse.statusCode == 200) {
          final imageJson = await http.Response.fromStream(imageResponse);
          imageUrl = json.decode(imageJson.body)['image_url']; // Assume response has 'image_url'
        } else {
          throw Exception('Image upload failed');
        }
      }

      // Step 2: Create ticket with POST
      final postUrl = Uri.parse('https://jupiter.nearle.app/live/api/v1/partners/createridersupport/');
      final body = json.encode({
        'userid': userid,
        'category': category,
        'priority': priority,
        'subject': subject,
        'issue': issue,
        'image': imageUrl, // null if no image
      });

      final response = await http.post(
        postUrl,
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        body: body,
      );

      if (response.statusCode != 200) {
        throw Exception('Failed to create ticket: ${response.statusCode}');
      }

      final Map<String, dynamic> jsonResponse = json.decode(response.body);
      if (jsonResponse['status'] != true) {
        throw Exception(jsonResponse['message'] ?? 'Unknown error');
      }

      // Refresh tickets to show new one
      await fetchTickets();
      return true;
    } catch (e) {
      errorMessage(e.toString());
      return false;
    } finally {
      isSubmitting(false);
    }
  }
}

