import 'package:dio/dio.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../data/help_chat_service.dart';

class HelpChatMessage {
  final String role; // 'user' | 'assistant'
  final String content;
  const HelpChatMessage({required this.role, required this.content});

  Map<String, String> toJson() => {'role': role, 'content': content};
}

class HelpChatState {
  final List<HelpChatMessage> messages;
  final bool sending;
  final String? error;

  const HelpChatState({
    this.messages = const [],
    this.sending = false,
    this.error,
  });

  HelpChatState copyWith({
    List<HelpChatMessage>? messages,
    bool? sending,
    String? error,
    bool clearError = false,
  }) => HelpChatState(
    messages: messages ?? this.messages,
    sending: sending ?? this.sending,
    error: clearError ? null : (error ?? this.error),
  );
}

class HelpChatController extends Notifier<HelpChatState> {
  @override
  HelpChatState build() => const HelpChatState();

  Future<void> send(String text) async {
    final trimmed = text.trim();
    if (trimmed.isEmpty || state.sending) return;

    final newMessages = [
      ...state.messages,
      HelpChatMessage(role: 'user', content: trimmed),
    ];
    state = state.copyWith(
      messages: newMessages,
      sending: true,
      clearError: true,
    );

    try {
      final reply = await ref
          .read(helpChatServiceProvider)
          .ask(newMessages.map((m) => m.toJson()).toList());
      state = state.copyWith(
        messages: [
          ...newMessages,
          HelpChatMessage(role: 'assistant', content: reply),
        ],
        sending: false,
      );
    } catch (e) {
      String msg = 'No se pudo enviar el mensaje';
      if (e is DioException) {
        final data = e.response?.data;
        if (data is Map && data['detail'] != null)
          msg = data['detail'].toString();
      }
      state = state.copyWith(sending: false, error: msg);
    }
  }

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

final helpChatControllerProvider =
    NotifierProvider<HelpChatController, HelpChatState>(HelpChatController.new);
