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

part 'session_closure_notifier.g.dart';

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

class ClosureInitialData extends SessionClosureData {
  const ClosureInitialData();
}

class ExtendingWaitingMitraData extends SessionClosureData {
  const ExtendingWaitingMitraData();
}

class ClosureShowGoodbyeData extends SessionClosureData {
  const ClosureShowGoodbyeData();
}

class ClosureSubmittingData extends SessionClosureData {
  const ClosureSubmittingData();
}

class ClosureCompleteData extends SessionClosureData {
  const ClosureCompleteData();
}

class ClosureErrorData extends SessionClosureData {
  final String message;
  const ClosureErrorData(this.message);
}

@Riverpod(keepAlive: true)
class SessionClosure extends _$SessionClosure {
  @override
  SessionClosureData build() => const ClosureInitialData();

  Future<void> requestExtension(String sessionId, {required int durationMinutes, required int price}) async {
    state = const ExtendingWaitingMitraData();
    try {
      await ref.read(apiClientProvider).post('/api/client/chat/session/$sessionId/extend', data: {
        'duration_minutes': durationMinutes,
        'price': price,
      });
      // Response will come via WebSocket (ChatBloc/ChatNotifier handles it)
    } catch (e) {
      state = const ClosureErrorData('Gagal meminta perpanjangan.');
    }
  }

  void declineExtension() {
    state = const ClosureShowGoodbyeData();
  }

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

  Future<void> submitGoodbye(String sessionId, String message) async {
    state = const ClosureSubmittingData();
    try {
      await ref.read(apiClientProvider).post('/api/shared/sessions/$sessionId/close-message', data: {
        'message': message,
      });
      state = const ClosureCompleteData();
      // The session is now completed server-side; refresh home snapshot so the
      // CTA returns to "Mulai Curhat" without waiting for the next poll tick.
      ref.invalidate(activeSessionProvider);
    } on DioException catch (e) {
      final code = e.response?.data?['error']?['code'];
      if (code == 'SESSION_NOT_ACTIVE' || e.response?.statusCode == 409) {
        state = const ClosureCompleteData();
        ref.invalidate(activeSessionProvider);
      } else {
        state = const ClosureErrorData('Gagal mengirim pesan penutup.');
      }
    } catch (e) {
      state = const ClosureErrorData('Gagal mengirim pesan penutup.');
    }
  }
}
