Na hora de perguntar  se quero adicionar as tarefas à lista ou criar uma nova lista, quero que as tarefas fiquem visíveis na caixa: import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Gerenciador de Tarefas',
        debugShowCheckedModeBanner: false,
        theme: ThemeData(primarySwatch: Colors.blue),
        home: LoginPage());
  }
}

// ---------------------------------
// LoginPage
// ---------------------------------
class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final emailController = TextEditingController();
  final passwordController = TextEditingController();

  Future<void> fazerLogin(String email, String senha) async {
    final url = Uri.parse('https://barra.cos.ufrj.br:443/rest/rpc/fazer_login');
    final Map<String, String> headers = {
      'accept': 'application/json',
      'Content-Type': 'application/json',
    };
    final Map<String, String> body = {
      'email': email,
      'senha': senha,
    };
    final String jsonBody = json.encode(body);

    try {
      final response =
          await http.post(url, headers: headers, body: jsonBody);
      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        final token = data['token'];

        // Verificar se o usuário já tem uma conversa
        bool possuiConversa = await verificarConversa(token);

        if (possuiConversa) {
          // Se tiver conversa, ir para o Chat
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(
              builder: (context) => ChatPage(token: token, email: email),
            ),
          );
        } else {
          // Se não tiver, ir para a lista de tarefas
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(
              builder: (context) => TaskListPage(token: token, email: email),
            ),
          );
        }
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
              content:
                  Text('Erro: ${response.statusCode} - ${response.body}')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Ocorreu um erro: ${e.toString()}')),
      );
    }
  }

  Future<bool> verificarConversa(String token) async {
    final url = Uri.parse('https://barra.cos.ufrj.br/rest/conversas');
    final headers = {
      'Authorization': 'Bearer $token',
      'accept': 'application/json',
    };

    try {
      final response = await http.get(url, headers: headers);

      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        return data.isNotEmpty;
      } else {
        return false;
      }
    } catch (e) {
      return false;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Login',
        style: TextStyle (color: Colors.white),
        ),
        backgroundColor: const Color.fromARGB(255, 128, 0, 0),
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
                controller: emailController,
                decoration: InputDecoration(labelText: 'Email')),
            TextField(
                controller: passwordController,
                decoration: InputDecoration(labelText: 'Senha'),
                obscureText: true),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () => fazerLogin(
                  emailController.text, passwordController.text),
              child: Text('Login'),
            ),
            TextButton(
              onPressed: () {
                Navigator.push(context,
                    MaterialPageRoute(builder: (context) => SignUpPage()));
              },
              child: Text('Criar conta'),
            ),
          ],
        ),
      ),
    );
  }
}

// ---------------------------------
// SignUpPage
// ---------------------------------
class SignUpPage extends StatefulWidget {
  @override
  _SignUpPageState createState() => _SignUpPageState();
}

class _SignUpPageState extends State<SignUpPage> {
  final emailController = TextEditingController();
  final nomeController = TextEditingController();
  final passwordController = TextEditingController();
  final confirmPasswordController = TextEditingController();
  final phoneController = TextEditingController();

  Future<void> signUp() async {
    if (passwordController.text != confirmPasswordController.text) {
      ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('As senhas não coincidem.')));
      return;
    }

    final Map<String, dynamic> body = {
      'celular': '21900000000',
      'email': emailController.text,
      'nome': nomeController.text,
      'senha': passwordController.text,
    };

    if (phoneController.text.isNotEmpty) {
      body['celular'] = phoneController.text;
    }

    final response = await http.post(
      Uri.parse('https://barra.cos.ufrj.br:443/rest/rpc/registra_usuario'),
      headers: {'Content-Type': 'application/json'},
      body: json.encode(body),
    );

    if (response.statusCode == 200) {
      ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Usuário cadastrado com sucesso!')));
      final loginResponse = await http.post(
        Uri.parse('https://barra.cos.ufrj.br:443/rest/rpc/fazer_login'),
        headers: {
          'accept': 'application/json',
          'Content-Type': 'application/json',
        },
        body: json.encode({
          'email': emailController.text,
          'senha': passwordController.text,
        }),
      );

      if (loginResponse.statusCode == 200) {
        final loginData = json.decode(loginResponse.body);
        final String token = loginData['token'];
        await criarTarefas(token, emailController.text);
        Navigator.pop(context);
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('Erro ao obter token de login.')));
      }
    } else {
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text('Erro ao cadastrar.')));
    }
  }

  Future<void> criarTarefas(String token, String email) async {
    final url = Uri.parse('https://barra.cos.ufrj.br:443/rest/tarefasv2');
    final headers = {
      'Authorization': 'Bearer $token',
      'Content-Type': 'application/json',
    };
    final body = json.encode({
      'email': email,
      'valor': [],
    });

    try {
      final response = await http.post(url, headers: headers, body: body);

      if (response.statusCode != 201) {
        print(
            'Erro ao criar tarefas: ${response.statusCode} - ${response.body}');
      }
    } catch (e) {
      print('Erro: ${e.toString()}');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Cadastro',
        style: TextStyle (color: Colors.white),
        ),
        backgroundColor: const Color.fromARGB(255, 128, 0, 0),
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
                controller: emailController,
                decoration: InputDecoration(labelText: 'Email')),
            TextField(
                controller: nomeController,
                decoration: InputDecoration(labelText: 'Nome')),
            TextField(
                controller: passwordController,
                decoration: InputDecoration(labelText: 'Senha'),
                obscureText: true),
            TextField(
                controller: confirmPasswordController,
                decoration: InputDecoration(labelText: 'Confirmar Senha'),
                obscureText: true),
            TextField(
                controller: phoneController,
                decoration: InputDecoration(labelText: 'Celular')),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: signUp,
              child: Text('Cadastrar'),
            ),
          ],
        ),
      ),
    );
  }
}

// ---------------------------------
// TaskListPage
// ---------------------------------
class TaskListPage extends StatefulWidget {
  final String token;
  final String email;

  const TaskListPage({required this.token, required this.email});

  @override
  _TaskListPageState createState() => _TaskListPageState();
}

class _TaskListPageState extends State<TaskListPage> {
  final List<Map<String, dynamic>> tasks = [];
  final textController = TextEditingController();

  @override
  void initState() {
    super.initState();
    fetchTasks();
  }

  Future<void> fetchTasks() async {
    final url = Uri.parse(
        'https://barra.cos.ufrj.br:443/rest/tarefasv2?select=valor&email=eq.${widget.email}');
    final headers = {
      'Authorization': 'Bearer ${widget.token}',
      'Content-Type': 'application/json',
    };

    final response = await http.get(url, headers: headers);

    if (response.statusCode == 200) {
      final data = json.decode(response.body);
      if (data.isNotEmpty) {
        setState(() {
          tasks.clear();
          tasks.addAll(
              List<Map<String, dynamic>>.from(data[0]['valor']));
        });
      }
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
            content:
                Text('Erro ao carregar tarefas: ${response.statusCode}')),
      );
    }
  }

  Future<void> addTask(String title) async {
    if (title.trim().isEmpty) return;

    setState(() {
      tasks.insert(0, {
        'titulo': title.trim(),
        'concluida': false,
        'isBeingDeleted': false
      });
    });

    await updateTasksOnServer();
    textController.clear();
  }

  Future<void> updateTasksOnServer() async {
    final url = Uri.parse(
        'https://barra.cos.ufrj.br:443/rest/tarefasv2?email=eq.${widget.email}');
    final headers = {
      'Authorization': 'Bearer ${widget.token}',
      'Content-Type': 'application/json',
    };
    final body = json.encode({
      'valor': tasks,
    });

    final response = await http.patch(url, headers: headers, body: body);

    if (response.statusCode != 204) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
            content: Text(
                'Erro ao atualizar tarefas: ${response.statusCode} ${response.body}')),
      );
    } else {
      fetchTasks();
    }
  }

  void _toggleCompletion(int index) {
    setState(() {
      tasks[index]['concluida'] = !tasks[index]['concluida'];
      _sortTasks();
    });
    updateTasksOnServer();
  }

  void _deleteTaskWithUndo(int index) {
    setState(() {
      tasks[index]['isBeingDeleted'] = true;
    });

    Future.delayed(const Duration(seconds: 3), () {
      if (mounted && tasks.length > index && tasks[index]['isBeingDeleted']) {
        _deleteTask(index);
      }
    });
  }

  void _undoDeleteTask(int index) {
    setState(() {
      tasks[index]['isBeingDeleted'] = false;
    });
    updateTasksOnServer();
  }

  void _sortTasks() {
    tasks.sort((a, b) {
      if (a['concluida'] && !b['concluida']) {
        return 1;
      } else if (!a['concluida'] && b['concluida']) {
        return -1;
      } else {
        return 0;
      }
    });
  }

  void _deleteTask(int index) {
    setState(() {
      tasks.removeAt(index);
    });
    updateTasksOnServer();
  }

  // Adicionar métodos para o Drawer
  void _logout() {
    Navigator.pushReplacement(
      context,
      MaterialPageRoute(builder: (context) => LoginPage()),
    );
  }

  void _navegarParaChat() {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => ChatPage(
          token: widget.token,
          email: widget.email,
        ),
      ),
    );
  }

  void _iniciarNovaConversa() async {
    bool sucesso = await criarNovaConversa();

    if (sucesso) {
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(
          builder: (context) => ChatPage(
            token: widget.token,
            email: widget.email,
          ),
        ),
      );
    }
  }

  Future<bool> criarNovaConversa() async {
    final url = Uri.parse('https://barra.cos.ufrj.br/rest/rpc/cria_conversa');
    final headers = {
      'Authorization': 'Bearer ${widget.token}',
      'Content-Type': 'application/json',
    };

    try {
      final response = await http.post(url, headers: headers);

      if (response.statusCode == 200) {
        return true;
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Erro ao criar nova conversa.')),
        );
        return false;
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Erro: ${e.toString()}')),
      );
      return false;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Gerenciador de Tarefas',
        style: TextStyle (color: Colors.white),
        ),
        backgroundColor: const Color.fromARGB(255, 128, 0, 0),
      ),
      drawer: Drawer(
        child: ListView(
          children: [
            // Cabeçalho do Drawer
            DrawerHeader(
              decoration: BoxDecoration(
                color: const Color.fromARGB(255, 128, 0, 0),
              ),
              child: Text(
                'Menu',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 24,
                ),
              ),
            ),
            // Itens do Drawer
            ListTile(
              leading: Icon(Icons.list),
              title: Text('Lista de Tarefas'),
              onTap: () {
                Navigator.pop(context);
                // Já estamos na Lista de Tarefas
              },
            ),
            ListTile(
              leading: Icon(Icons.chat),
              title: Text('Chat'),
              onTap: () {
                Navigator.pop(context);
                _navegarParaChat();
              },
            ),
            ListTile(
              leading: Icon(Icons.refresh),
              title: Text('Iniciar outra conversa'),
              onTap: () {
                Navigator.pop(context);
                _iniciarNovaConversa();
              },
            ),
            ListTile(
              leading: Icon(Icons.logout),
              title: Text('Logout'),
              onTap: () {
                Navigator.pop(context);
                _logout();
              },
            ),
          ],
        ),
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: TextField(
              controller: textController,
              onSubmitted: (value) {
                addTask(value);
              },
              decoration: const InputDecoration(
                labelText: 'Adicionar Tarefa',
              ),
            ),
          ),
          Expanded(
            child: ListView.builder(
              itemCount: tasks.length,
              itemBuilder: (context, index) {
                final task = tasks[index];
                final isBeingDeleted = task['isBeingDeleted'] == true;
                final isCompleted = task['concluida'] == true;
                final backgroundColor = isBeingDeleted
                    ? Colors.red
                    : (index % 3 == 0
                        ? const Color.fromARGB(255, 99, 12, 0)
                        : index % 3 == 1
                            ? const Color.fromARGB(255, 245, 245, 245)
                            : const Color.fromARGB(255, 0, 63, 5));
                final textColor = backgroundColor ==
                            const Color.fromARGB(255, 0, 63, 5) ||
                        backgroundColor == const Color.fromARGB(255, 99, 12, 0)
                    ? Colors.white
                    : Colors.black;

                return Padding(
                  padding: const EdgeInsets.symmetric(
                      horizontal: 16.0, vertical: 8.0),
                  child: Dismissible(
                    key: UniqueKey(),
                    background: Container(
                      color: Colors.green,
                      alignment: Alignment.centerLeft,
                      padding: const EdgeInsets.only(left: 20.0),
                      child: const Icon(Icons.check, color: Colors.white),
                    ),
                    secondaryBackground: Container(
                      color: Colors.red,
                      alignment: Alignment.centerRight,
                      padding: const EdgeInsets.only(right: 20.0),
                      child: const Icon(Icons.delete, color: Colors.white),
                    ),
                    confirmDismiss: (direction) async {
                      if (direction == DismissDirection.endToStart) {
                        _deleteTaskWithUndo(index);
                        return false;
                      } else if (direction == DismissDirection.startToEnd) {
                        _toggleCompletion(index);
                        return false;
                      }
                      return false;
                    },
                    child: Container(
                      decoration: BoxDecoration(
                        color: backgroundColor,
                        borderRadius: BorderRadius.circular(8.0),
                        border: Border.all(
                          color: const Color.fromARGB(255, 0, 42, 116),
                          width: 2.0,
                        ),
                      ),
                      child: ListTile(
                        title: Text(
                          task['titulo'],
                          style: TextStyle(
                            color: textColor,
                            decoration: isCompleted
                                ? TextDecoration.lineThrough
                                : TextDecoration.none,
                          ),
                        ),
                        trailing: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Checkbox(
                              value: isCompleted,
                              onChanged: (_) => _toggleCompletion(index),
                            ),
                            isBeingDeleted
                                ? IconButton(
                                    icon: const Icon(Icons.undo),
                                    onPressed: () => _undoDeleteTask(index),
                                  )
                                : IconButton(
                                    icon: const Icon(Icons.delete),
                                    onPressed: () => _deleteTaskWithUndo(index),
                                  ),
                          ],
                        ),
                      ),
                    ),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

// ---------------------------------
// ChatPage
// ---------------------------------
class ChatPage extends StatefulWidget {
  final String token;
  final String email;

  const ChatPage({
    required this.token,
    required this.email,
  });

  @override
  _ChatPageState createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage> {
  List<Map<String, dynamic>> messages = [];
  final textController = TextEditingController();
  bool isLoading = false;
  String? conversaId;

  @override
  void initState() {
    super.initState();
    _carregarConversa();
  }

  Future<void> _carregarConversa() async {
    setState(() {
      isLoading = true;
    });

    final url = Uri.parse('https://barra.cos.ufrj.br/rest/conversas');
    final headers = {
      'Authorization': 'Bearer ${widget.token}',
      'Content-Type': 'application/json',
    };

    try {
      final response = await http.get(url, headers: headers);

      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        if (data.isNotEmpty) {
          final conversa = data[0];
          conversaId = conversa['id'];
          setState(() {
            messages = List<Map<String, dynamic>>.from(conversa['mensagens']);
          });
        } else {
          // Se não houver conversa, cria uma nova
          await _iniciarConversa();
        }
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
              content: Text(
                  'Erro ao carregar conversas: ${response.statusCode}')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Erro: ${e.toString()}')),
      );
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  Future<void> _iniciarConversa() async {
    final url = Uri.parse('https://barra.cos.ufrj.br/rest/rpc/cria_conversa');
    final headers = {
      'Authorization': 'Bearer ${widget.token}',
      'Content-Type': 'application/json',
    };

    try {
      final response = await http.post(url, headers: headers);

      if (response.statusCode == 200) {
        await _carregarConversa();
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
              content:
                  Text('Erro ao criar conversa: ${response.statusCode}')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Erro: ${e.toString()}')),
      );
    }
  }

  Future<void> _enviarMensagem(String texto) async {
    if (texto.trim().isEmpty) return;
    if (conversaId == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Conversa não iniciada.')),
      );
      return;
    }

    setState(() {
      messages.add({'papel': 'usuario', 'conteudo': texto.trim()});
      isLoading = true;
    });

    textController.clear();

    final url = Uri.parse('https://barra.cos.ufrj.br/rest/rpc/envia_resposta');
    final headers = {
      'Authorization': 'Bearer ${widget.token}',
      'Content-Type': 'application/json',
    };
    final body = json.encode({
      'conversa_id': conversaId!,
      'resposta': texto.trim(),
    });

    try {
      final response = await http.post(url, headers: headers, body: body);

      if (response.statusCode == 200) {
        final data = json.decode(response.body);

        if (data.containsKey('pergunta')) {
          // Resposta normal com uma pergunta
          setState(() {
            messages.add({
              'papel': 'assistente',
              'conteudo': data['pergunta'],
            });
          });
        } else if (data.containsKey('tarefas')) {
          // Recebeu lista de tarefas
          List<String> tarefas = List<String>.from(data['tarefas']);
          _exibirDialogoTarefas(tarefas);
        } else {
          // Mensagem inesperada
          setState(() {
            messages.add({
              'papel': 'assistente',
              'conteudo': 'Houve um erro ao processar a resposta do assistente.',
            });
          });
        }
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
              content:
                  Text('Erro ao enviar mensagem: ${response.statusCode}')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Erro: ${e.toString()}')),
      );
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  void _exibirDialogoTarefas(List<String> tarefas) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('O que deseja fazer?'),
        content: Text('O chat gerou uma lista de tarefas.'),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              // Continuar o chat
            },
            child: Text('Continuar o chat'),
          ),
          TextButton(
            onPressed: () async {
              Navigator.pop(context);
              // Criar a lista de tarefas apagando as tarefas anteriores
              await _criarListaDeTarefas(tarefas, apagarAnterior: true);
            },
            child: Text('Criar nova lista de tarefas'),
          ),
          TextButton(
            onPressed: () async {
              Navigator.pop(context);
              // Adicionar as tarefas à lista existente
              await _criarListaDeTarefas(tarefas, apagarAnterior: false);
            },
            child: Text('Adicionar à lista existente'),
          ),
        ],
      ),
    );
  }

  Future<void> _criarListaDeTarefas(List<String> tarefas,
      {required bool apagarAnterior}) async {
    // Obter as tarefas atuais
    List<Map<String, dynamic>> tarefasAtuais = [];
    if (!apagarAnterior) {
      // Buscar tarefas existentes
      final url = Uri.parse(
          'https://barra.cos.ufrj.br/rest/tarefasv2?select=valor&email=eq.${widget.email}');
      final headers = {
        'Authorization': 'Bearer ${widget.token}',
        'Content-Type': 'application/json',
      };

      final response = await http.get(url, headers: headers);

      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        if (data.isNotEmpty) {
          tarefasAtuais =
              List<Map<String, dynamic>>.from(data[0]['valor'] ?? []);
        }
      }
    }

    // Preparar a lista atualizada de tarefas
    List<Map<String, dynamic>> novasTarefas = tarefas
        .map((tarefa) => {
              'titulo': tarefa,
              'concluida': false,
              'isBeingDeleted': false,
            })
        .toList();

    if (!apagarAnterior) {
      novasTarefas = [...tarefasAtuais, ...novasTarefas];
    }

    // Atualizar as tarefas no servidor
    final url = Uri.parse(
        'https://barra.cos.ufrj.br/rest/tarefasv2?email=eq.${widget.email}');
    final headers = {
      'Authorization': 'Bearer ${widget.token}',
      'Content-Type': 'application/json',
    };
    final body = json.encode({
      'valor': novasTarefas,
    });

    final response = await http.patch(url, headers: headers, body: body);

    if (response.statusCode != 204) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
            content: Text(
                'Erro ao atualizar tarefas: ${response.statusCode} ${response.body}')),
      );
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Lista de tarefas atualizada com sucesso!')),
      );
    }
  }

  void _logout() {
    Navigator.pushReplacement(
      context,
      MaterialPageRoute(builder: (context) => LoginPage()),
    );
  }

  void _navegarParaListaDeTarefas() {
    Navigator.pushReplacement(
      context,
      MaterialPageRoute(
        builder: (context) => TaskListPage(
          token: widget.token,
          email: widget.email,
        ),
      ),
    );
  }

  void _iniciarNovaConversa() async {
    final url = Uri.parse('https://barra.cos.ufrj.br/rest/rpc/cria_conversa');
    final headers = {
      'Authorization': 'Bearer ${widget.token}',
      'Content-Type': 'application/json',
    };

    try {
      final response = await http.post(url, headers: headers);

      if (response.statusCode == 200) {
        setState(() {
          messages.clear();
          conversaId = null;
        });
        await _carregarConversa();
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
              content:
                  Text('Erro ao iniciar nova conversa: ${response.statusCode}')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Erro: ${e.toString()}')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Chat',
        style: TextStyle (color: Colors.white),
        ),
        backgroundColor: const Color.fromARGB(255, 128, 0, 0),
      ),
      drawer: Drawer(
        child: ListView(
          children: [
            // Cabeçalho do Drawer
            DrawerHeader(
              decoration: BoxDecoration(
                color: const Color.fromARGB(255, 128, 0, 0),
              ),
              child: Text(
                'Menu',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 24,
                ),
              ),
            ),
            // Itens do Drawer
            ListTile(
              leading: Icon(Icons.list),
              title: Text('Lista de Tarefas'),
              onTap: () {
                Navigator.pop(context);
                _navegarParaListaDeTarefas();
              },
            ),
            ListTile(
              leading: Icon(Icons.chat),
              title: Text('Chat'),
              onTap: () {
                Navigator.pop(context);
                // Já estamos no Chat
              },
            ),
            ListTile(
              leading: Icon(Icons.refresh),
              title: Text('Iniciar outra conversa'),
              onTap: () {
                Navigator.pop(context);
                _iniciarNovaConversa();
              },
            ),
            ListTile(
              leading: Icon(Icons.logout),
              title: Text('Logout'),
              onTap: () {
                Navigator.pop(context);
                _logout();
              },
            ),
          ],
        ),
      ),
      body: Column(
        children: [
          Expanded(
            child: isLoading && messages.isEmpty
                ? Center(child: CircularProgressIndicator())
                : ListView.builder(
                    itemCount: messages.length,
                    itemBuilder: (context, index) {
                      final mensagem = messages[index];
                      final isUser = mensagem['papel'] == 'usuario';

                      return Align(
                        alignment: isUser
                            ? Alignment.centerRight
                            : Alignment.centerLeft,
                        child: Container(
                          margin: EdgeInsets.symmetric(
                            vertical: 5,
                            horizontal: 10,
                          ),
                          padding: EdgeInsets.all(10),
                          decoration: BoxDecoration(
                            color: isUser
                                ? Colors.blueAccent
                                : Colors.grey.shade300,
                            borderRadius: BorderRadius.circular(10),
                          ),
                          child: Text(
                            mensagem['conteudo'] ?? '',
                            style: TextStyle(
                              color: isUser ? Colors.white : Colors.black,
                            ),
                          ),
                        ),
                      );
                    },
                  ),
          ),
          if (isLoading && messages.isNotEmpty)
            Padding(
              padding: EdgeInsets.all(8.0),
              child: CircularProgressIndicator(),
            ),
          Padding(
            padding: EdgeInsets.all(8.0),
            child: Row(
              children: [
      Expanded(
        child: TextField(
          controller: textController,
          enabled: !isLoading,
          decoration: InputDecoration(
            hintText: 'Digite sua mensagem...',
            border: OutlineInputBorder(),
          ),
          textInputAction: TextInputAction.send, // Adiciona o botão de "Enviar" no teclado
          onSubmitted: (value) {
            if (!isLoading) {
              _enviarMensagem(value);
            }
          },
        ),
      ),
      IconButton(
        icon: Icon(Icons.send),
        onPressed: isLoading
            ? null
            : () => _enviarMensagem(textController.text),
      ),
    ],
            ),
          ),
        ],
      ),
    );
  }
}