import 'package:dio/dio.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../api/api_client_provider.dart';

part 'extension_notifier.g.dart';

// States
sealed class ExtensionData {
  const ExtensionData();
}

class ExtensionIdleData extends ExtensionData {
  const ExtensionIdleData();
}

class ExtensionRespondingData extends ExtensionData {
  const ExtensionRespondingData();
}

class ExtensionShowGoodbyeData extends ExtensionData {
  const ExtensionShowGoodbyeData();
}

class ExtensionSubmittingData extends ExtensionData {
  const ExtensionSubmittingData();
}

class ExtensionCompleteData extends ExtensionData {
  const ExtensionCompleteData();
}

class ExtensionErrorData extends ExtensionData {
  final String message;
  const ExtensionErrorData(this.message);
}

@Riverpod(keepAlive: true)
class MitraExtension extends _$MitraExtension {
  @override
  ExtensionData build() => const ExtensionIdleData();

  Future<void> respond(String sessionId, {required String extensionId, required bool accepted}) async {
    state = const ExtensionRespondingData();
    try {
      await ref.read(apiClientProvider).post('/api/mitra/chat-requests/sessions/$sessionId/extend-response', data: {
        'extension_id': extensionId,
        'accepted': accepted,
      });
      if (!accepted) {
        state = const ExtensionShowGoodbyeData();
      } else {
        state = const ExtensionIdleData();
      }
    } on DioException catch (e) {
      final code = e.response?.data?['error']?['code'];
      if (code == 'EXTENSION_RESOLVED') {
        state = const ExtensionShowGoodbyeData();
      } else {
        state = const ExtensionErrorData('Gagal merespon perpanjangan.');
      }
    }
  }

  Future<void> submitGoodbye(String sessionId, String message) async {
    state = const ExtensionSubmittingData();
    try {
      await ref.read(apiClientProvider).post('/api/shared/sessions/$sessionId/close-message', data: {
        'message': message,
      });
      state = const ExtensionCompleteData();
    } on DioException catch (e) {
      final code = e.response?.data?['error']?['code'];
      if (code == 'SESSION_NOT_ACTIVE' || e.response?.statusCode == 409) {
        state = const ExtensionCompleteData();
      } else {
        state = const ExtensionErrorData('Gagal mengirim pesan penutup.');
      }
    } catch (e) {
      state = const ExtensionErrorData('Gagal mengirim pesan penutup.');
    }
  }

  void reset() {
    state = const ExtensionIdleData();
  }
}
