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:Intaleq/constant/box_name.dart';
import 'package:Intaleq/constant/colors.dart';
import 'package:Intaleq/constant/links.dart';
import 'package:Intaleq/constant/style.dart';
import 'package:Intaleq/controller/functions/crud.dart';
import 'package:Intaleq/main.dart';
import 'package:Intaleq/views/widgets/elevated_btn.dart';
import 'package:http_parser/http_parser.dart';
import 'package:mime/mime.dart';

import '../../../constant/api_key.dart';
import '../../../print.dart';
import '../../../views/widgets/mydialoug.dart';

class ComplaintController extends GetxController {
  bool isLoading = false;
  final formKey = GlobalKey<FormState>();
  final complaintController = TextEditingController();
  final suggestionController = TextEditingController();
  List feedBack = [];
  @override
  void onInit() {
    super.onInit();
    getLatestRidesForPassengers();
  }

  getLatestRidesForPassengers() async {
    isLoading = true;
    update();
    var res = await CRUD().get(link: AppLink.getFeedBack, payload: {
      'passengerId': box.read(BoxName.passengerID).toString(),
    });
    if (res != 'failure') {
      var d = jsonDecode(res)['message'];
      feedBack = d;
    }

    isLoading = false;
    update();
  }

  void addComplaint() async {
    isLoading = true;
    update();
    var res = await CRUD().post(link: AppLink.addFeedBack, payload: {
      'passengerId': box.read(BoxName.passengerID).toString(),
      'feedBack': complaintController.text
    });
    // var d = jsonDecode(res);
    if (res != 'failure') {
      Get.defaultDialog(
          title: 'Success'.tr,
          titleStyle: AppStyle.title,
          middleText: 'Complaint data saved successfully'.tr,
          middleTextStyle: AppStyle.title,
          confirm: MyElevatedButton(
              kolor: AppColor.greenColor,
              title: 'Ok'.tr,
              onPressed: () {
                Get.back();
                // Get.back();
              }));
    }

    isLoading = false;
    update();
  }

  var isUploading = false.obs;
  var uploadSuccess = false.obs;
  late String audioLink = '';
  Future<void> uploadAudioFile(File audioFile) async {
    try {
      isUploading.value = true;

      // Prepare the file upload
      var uri = Uri.parse('${AppLink.IntaleqCairoServer}/upload_audio.php');
      var request = http.MultipartRequest('POST', uri);

      // Add the file to the request with MIME type
      var mimeType = lookupMimeType(audioFile.path);
      request.headers.addAll({
        'Authorization':
            'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials.toString()))}',
      });
      request.files.add(
        await http.MultipartFile.fromPath(
          'audio',
          audioFile.path,
          contentType: mimeType != null ? MediaType.parse(mimeType) : null,
        ),
      );

      // Send the request
      var response = await request.send();

      // Convert response to string for parsing
      var responseBody = await http.Response.fromStream(response);

      // After the upload request
      if (response.statusCode == 200) {
        var jsonResponse = jsonDecode(responseBody.body);

        if (jsonResponse['status'] == 'Audio file uploaded successfully.') {
          uploadSuccess.value = true;
          audioLink = jsonResponse['link']; // Get the audio link
          Get.back();
          Get.snackbar('Success'.tr, 'Audio uploaded successfully.'.tr,
              backgroundColor: const Color.fromARGB(255, 89, 185, 115));
        } else {
          uploadSuccess.value = false;
        }
      } else {
        uploadSuccess.value = false;
      }
    } catch (e) {
      uploadSuccess.value = false;
    } finally {
      isUploading.value = false;
    }
  }

  var customerServiceSolutions;
  var passengerReport;
  var driverReport;
  var isloading = false;
  Future<void> geminiAudio(payload, String audioLink, String complain) async {
    String prompt = '''
  Analyze the following complaint between a passenger and driver in a ride-hailing service. The complaint includes an audio link for reference. Provide two possible solutions for customer service to resolve the issue, and generate a detailed report for both the passenger and the driver.

  Complaint details:
  - Passenger: $complain
  - Driver: [Driver's complaint]
  - Ride Information: {ride details such as start_location, end_location, date, price, status, and rating details}
  - Audio Link: [$audioLink]

  Output the result in JSON format with the following structure:
  {
    "customerServiceSolutions": [
      "solution1",
      "solution2"
    ],
    "passengerReport": {
      "solution": "Passenger's solution" if passenger right,
      "complaint": "Passenger's complaint",
      "rideDetails": {detailed ride info}
    },
    "driverReport": {
      "complaint": "Driver's complaint",
      "rideDetails": {detailed ride info}
    }
  } the response in arabic language with egypt
  ''';

    var requestBody = jsonEncode({
      "contents": [
        {
          "parts": [
            {"text": "$payload $prompt"}
          ]
        }
      ],
      "generationConfig": {
        "temperature": 1,
        "topK": 64,
        "topP": 0.95,
        "maxOutputTokens": 8192,
        "stopSequences": []
      },
      "safetySettings": [
        {
          "category": "HARM_CATEGORY_HARASSMENT",
          "threshold": "BLOCK_MEDIUM_AND_ABOVE"
        },
        {
          "category": "HARM_CATEGORY_HATE_SPEECH",
          "threshold": "BLOCK_MEDIUM_AND_ABOVE"
        },
        {
          "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
          "threshold": "BLOCK_MEDIUM_AND_ABOVE"
        },
        {
          "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
          "threshold": "BLOCK_MEDIUM_AND_ABOVE"
        }
      ]
    });

    final response = await http.post(
      Uri.parse(
          'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.0-pro:generateContent?key=${AK.geminiApi}'),
      headers: {'Content-Type': 'application/json'},
      body: requestBody,
    );

    if (response.statusCode == 200) {
      var responseData = jsonDecode(response.body);
      var result = responseData['candidates'][0]['content']['parts'][0]['text'];
      Log.print('result: ${result}');

      // Clean up the result by removing surrounding backticks if they exist
      result = result.replaceAll(RegExp(r'^```json\s*|\s*```$'), '');

      // Attempt to decode the cleaned result as JSON
      try {
        var jsonResult = jsonDecode(result);

        // Access customer service solutions and reports for both passenger and driver
        customerServiceSolutions = jsonResult['customerServiceSolutions'];
        passengerReport = jsonResult['passengerReport'];
        driverReport = jsonResult['driverReport'];
        update();
        // Use the data accordingly
        // For example, log the reports or display them in a UI dialog

        update();
      } catch (e) {
        MyDialog().getDialog(
            'Error'.tr,
            'Unable to parse the response as JSON. Please check the format and try again.'
                .tr, () {
          Get.back();
        });
      }
    } else {
      Get.snackbar(
          'Error', "Request failed with status: ${response.statusCode}",
          backgroundColor: AppColor.redColor);
    }
  }
}
