import 'dart:io';
import 'package:flutter/material.dart';
import 'package:gen_rentals/Screens/HelpScreens/HelpScreen.dart';
import 'package:gen_rentals/Screens/HelpScreens/TicketChatScreen.dart';
import 'package:gen_rentals/Services/api_calling.dart';
import '../Models/HelpAndEnquiryModels/TicketChatDisplayResponse.dart';
import '../Models/HelpAndEnquiryModels/ticketListResponse.dart';
import '../Utility/CustomSnackbar.dart';
import 'package:http/http.dart' as http;
import 'dart:io';
import 'package:path/path.dart' as path;

class HelpAndEnquiryProvider extends ChangeNotifier {
  bool _isLoading = false;
  bool get isLoading => _isLoading;

  String? _message;
  String? get message => _message;

  int? _balance;
  int? get balance => _balance;

  Future<bool> submitEnquiry({
    required String sessionId,
    required String accId,
    required String name,
    required String email,
    required String mobile,
    required String requirement,
    required String note,
  }) async {
    try {
      _isLoading = true;
      _message = null;
      notifyListeners();

      final response = await ApiCalling.submitEnquiryApi(
        sessionId,
        accId,
        name,
        email,
        mobile,
        requirement,
        note,
      );

      _isLoading = false;

      if (response != null) {
        _message = response.message;
        _balance = response.balance;

        notifyListeners();

        if (response.error == 0) {
          // success
          debugPrint("✅ Enquiry submitted successfully: ${response.message}");
          return true;
        } else {
          // failed
          debugPrint("⚠️ Failed to submit enquiry: ${response.message}");
          return false;
        }
      } else {
        _isLoading = false;
        notifyListeners();
        debugPrint("❌ Null response received.");
        return false;
      }
    } catch (e) {
      _isLoading = false;
      notifyListeners();
      debugPrint("❌ Exception in submitEnquiry: $e");
      return false;
    }
  }


  String? _errorMessage;
  TicketListResponse? _ticketListResponse;
  String? get errorMessage => _errorMessage;
  TicketListResponse? get ticketListResponse => _ticketListResponse;
  /// ✅ Fetch ticket list from API
  Future<void> fetchTicketList({
    required String sessionId,
    required String accId,
  }) async {
    _isLoading = true;
    _errorMessage = null;
    notifyListeners();

    try {
      final response =
      await ApiCalling.fetchTicketListApi(sessionId, accId,);

      if (response != null && response.error == "0") {
        _ticketListResponse = response;
      } else {
        _errorMessage = response?.message ?? "Something went wrong";
      }
    } catch (e) {
      debugPrint("❌ Provider Error (fetchTicketList): $e");
      _errorMessage = e.toString();
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// ✅ Optional: Clear state (useful on logout or refresh)
  void clearTickets() {
    _ticketListResponse = null;
    _errorMessage = null;
    notifyListeners();
  }


  TicketChatDisplayResponse? _chatResponse;
  TicketChatDisplayResponse? get chatResponse => _chatResponse;

  /// Fetch chat details for a specific ticket
  Future<void> fetchTicketChatDisplay({
    required String sessionId,
    required String accId,
    required String ticketId,
  }) async {
    _isLoading = true;
    _errorMessage = null;
    notifyListeners();

    try {
      final response = await ApiCalling.fetchTicketChatDisplayApi(
        sessionId,
        accId,
        ticketId,
      );

      if (response != null && response.error == "0") {
        _chatResponse = response;
        _errorMessage = null;
      } else {
        _chatResponse = null;
        _errorMessage = response?.message ?? "Something went wrong";
      }

      /// Force UI to rebuild after data change
      notifyListeners();

    } catch (e) {
      debugPrint("❌ Provider Error (fetchTicketChatDisplay): $e");
      _errorMessage = e.toString();
      _chatResponse = null;
      notifyListeners(); //  also notify here
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }


  /// Optional: Clear data (for refresh or reset)
  void clearChatData() {
    _chatResponse = null;
    _errorMessage = null;
    notifyListeners();
  }

  /// Send a Message Provider fun
  bool _isSending = false;
  bool get isSending => _isSending;

  void _setSending(bool value) {
    _isSending = value;
    notifyListeners();
  }

  Future<void> sendMessage(
      BuildContext context, {
        required String sessionId,
        required String accId,
        required String ticketId,
        required String msgText,
        required List<File> images,
      }) async {
    _setSending(true);
    try {
      //  Create a copy so the original list can’t be modified during iteration
      final safeImages = List<File>.from(images);

      List<http.MultipartFile> multipartImages = [];
      for (var file in safeImages) {
        final multipartFile = await http.MultipartFile.fromPath(
          'images[]',
          file.path,
          filename: path.basename(file.path),
        );
        multipartImages.add(multipartFile);
      }
      final response = await ApiCalling.addMessageApi(
        sessionId,
        accId,
        ticketId,
        msgText,
        multipartImages,
      );

      // Check if widget is still mounted before showing dialogs
      if (!context.mounted) return;

      if (response != null && response?.error == 0) {
        CustomSnackBar.showSuccess(
          context: context,
          message: response?.message ?? "Message sent successfully!",
        );

        // here it not refressing the chat screen when msg submit
        if (context.mounted) {
          fetchTicketChatDisplay(
            sessionId: sessionId,
            accId: accId,
            ticketId: ticketId,
          );
        }
      } else {
        CustomSnackBar.showError(
          context: context,
          message: response?.message ?? "Failed to send message!",
        );
      }
    } catch (e) {
      debugPrint("❌ sendMessage error: $e");

      // Check if widget is still mounted before showing error
      if (context.mounted) {
        CustomSnackBar.showError(
          context: context,
          message: "Error sending message",
        );
      }
    } finally {
      _setSending(false);
    }
  }

  /// Create New Ticket Provider fun
  bool _isCreatingTicket = false;
  bool get isCreatingTicket => _isCreatingTicket;

  void _setCreatingTicket(bool value) {
    _isCreatingTicket = value;
    notifyListeners();
  }

  Future<void> createTicket({
    required BuildContext context,
    required String sessionId,
    required String accId,
    required String type,
    required String description,
    required String orderId,
    required String otherReason,
    required List<File> images,
  }) async {
    _setCreatingTicket(true);
    try {
      final response = await ApiCalling.addTicketApi(
        sessionId,
        accId,
        type,
        description,
        orderId,
        otherReason,
        images,
      );

      // Check if widget is still mounted before showing dialogs
      if (!context.mounted) return;
      if (response != null && response?.error == 0) {
        CustomSnackBar.showSuccess(
            context: context,
            message: response?.message ?? "Ticket created successfully!",
        );
        //Navigator.pop(context); // close bottom sheet or dialog if open
        if (context.mounted) {
          Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => HelpScreen(sessionId: sessionId, accId: accId))
          );
        }
      } else {

        CustomSnackBar.showError(
          context: context,
          message: response?.message ?? "Failed to create ticket",
        );
      }
    } catch (e) {
      debugPrint("❌ createTicket error: $e");
      CustomSnackBar.showWarning(
        context: context,
        message: "Something went wrong. Please try again.",
      );
    } finally {
      _setCreatingTicket(false);
    }
  }
}








