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

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import 'package:siro_driver/constant/box_name.dart';
import 'package:siro_driver/constant/links.dart';
import 'package:siro_driver/controller/functions/crud.dart';
import 'package:siro_driver/main.dart';
import 'package:http_parser/http_parser.dart';
import 'package:mime/mime.dart';
import 'package:siro_driver/controller/functions/encrypt_decrypt.dart';
import 'package:siro_driver/env/env.dart';
import 'package:siro_driver/print.dart';
import 'package:siro_driver/views/widgets/error_snakbar.dart';
import 'package:siro_driver/views/widgets/mydialoug.dart';

class ComplaintController extends GetxController {
  bool isLoading = false;
  final formKey = GlobalKey<FormState>();
  final complaintController = TextEditingController();

  List<dynamic> ridesList = [];
  Map<String, dynamic>? selectedRide;

  Map<String, dynamic>? passengerReport;
  Map<String, dynamic>? driverReport;

  var isUploading = false.obs;
  var uploadSuccess = false.obs;
  String audioLink = ''; // سيتم تخزين رابط الصوت هنا بعد الرفع
  String attachedFileName = '';

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

  void _showCustomSnackbar(String title, String message,
      {bool isError = false}) {
    if (title.toLowerCase() == 'success') {
      mySnackbarSuccess(message.tr);
    } else if (isError) {
      mySnackeBarError(message.tr);
    } else {
      mySnackbarWarning(message.tr);
    }
  }

  Future<void> getLatestRidesForDriver() async {
    isLoading = true;
    update();
    try {
      var res = await CRUD().get(link: AppLink.getRides, payload: {
        'driver_id': box.read(BoxName.driverID).toString(),
      });
      if (res != 'failure' && res != 'no_internet') {
        var decoded = jsonDecode(res);
        if (decoded['status'] == 'success') {
          ridesList = decoded['data'] ?? [];
          if (ridesList.isNotEmpty) {
            selectedRide = ridesList[0];
          }
        }
      }
    } catch (e) {
      Log.print("Error getting driver rides: $e");
    } finally {
      isLoading = false;
      update();
    }
  }

  void selectRide(Map<String, dynamic> ride) {
    selectedRide = ride;
    audioLink = '';
    attachedFileName = '';
    update();
  }

  Future<void> uploadAudioFile(File audioFile) async {
    try {
      isUploading.value = true;
      update();

      var uri = Uri.parse(AppLink.uploadAudio);
      var request = http.MultipartRequest('POST', uri);
      String token = r(box.read(BoxName.jwt)).toString().split(Env.addd)[0];
      final String fingerPrint = box.read(BoxName.deviceFingerprint)?.toString() ?? '';

      var mimeType = lookupMimeType(audioFile.path);
      request.headers.addAll({
        'Authorization': 'Bearer $token',
        'X-Device-FP': fingerPrint,
      });
      request.files.add(
        await http.MultipartFile.fromPath(
          'audio',
          audioFile.path,
          contentType: mimeType != null ? MediaType.parse(mimeType) : null,
        ),
      );

      var response = await request.send();
      var responseBody = await http.Response.fromStream(response);

      if (response.statusCode == 200) {
        var jsonResponse = jsonDecode(responseBody.body);
        if (jsonResponse['status'] == 'Audio file uploaded successfully.') {
          uploadSuccess.value = true;
          audioLink = jsonResponse['link'];
          attachedFileName = audioFile.path.split('/').last;
          _showCustomSnackbar('Success', 'Audio uploaded successfully.');
        } else {
          uploadSuccess.value = false;
          _showCustomSnackbar('Error', 'Failed to upload audio file.',
              isError: true);
        }
      } else {
        uploadSuccess.value = false;
        _showCustomSnackbar('Error', 'Server error: ${response.statusCode}',
            isError: true);
      }
    } catch (e) {
      uploadSuccess.value = false;
      _showCustomSnackbar(
          'Error', 'An application error occurred during upload.',
          isError: true);
    } finally {
      isUploading.value = false;
      update();
    }
  }

  Future<void> submitComplaintToServer() async {
    if (!formKey.currentState!.validate() || complaintController.text.isEmpty) {
      _showCustomSnackbar(
          'Error', 'Please describe your issue before submitting.',
          isError: true);
      return;
    }

    if (selectedRide == null) {
      _showCustomSnackbar('Error', 'Please select a ride before submitting.',
          isError: true);
      return;
    }

    isLoading = true;
    update();

    try {
      final rideId = selectedRide!['id'].toString();
      final complaint = complaintController.text;

      final responseData = await CRUD().post(
        link: AppLink.add_solve_all,
        payload: {
          'ride_id': rideId,
          'complaint_text': complaint,
          'audio_link': audioLink,
        },
      );

      if (responseData == 'failure' || responseData == 'no_internet' || responseData == 'token_expired') {
        _showCustomSnackbar(
            'Error', 'Failed to connect to the server. Please try again.',
            isError: true);
        return;
      }

      if (responseData['status'] == 'success') {
        passengerReport = responseData['data']['passenger_response'];
        driverReport = responseData['data']['driver_response'];
        update();

        MyDialogContent().getDialog(
            'Success'.tr, Text('Your complaint has been submitted.'.tr), () {
          Get.back();
          complaintController.clear();
          audioLink = '';
          attachedFileName = '';
          formKey.currentState?.reset();
        });
      } else {
        String errorMessage =
            responseData['message'] ?? 'An unknown server error occurred'.tr;
        _showCustomSnackbar('Submission Failed', errorMessage, isError: true);
      }
    } catch (e) {
      Log.print("Submit Complaint Error: $e");
      _showCustomSnackbar('Error', 'An application error occurred.'.tr,
          isError: true);
    } finally {
      isLoading = false;
      update();
    }
  }
}
