Vou te dar um código. Depois te passo as instruções: import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

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

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

/// Modelo para Mensagem
class Message {
  final String papel;
  final String conteudo;

  Message({required this.papel, required this.conteudo});

  factory Message.fromJson(Map<String, dynamic> json) {
    return Message(
      papel: json['papel'],
      conteudo: json['conteudo'],
    );
  }
}

/// Modelo para Conversa
class Conversa {
  final String id;
  final String criacao;
  final String ultimaAlteracao;
  final List<Message> mensagens;

  Conversa({
    required this.id,
    required this.criacao,
    required this.ultimaAlteracao,
    required this.mensagens,
  });

  factory Conversa.fromJson(Map<String, dynamic> json) {
    var msgs = (json['mensagens'] as List)
        .map((msg) => Message.fromJson(msg))
        .toList();

    return Conversa(
      id: json['id'],
      criacao: json['criacao'],
      ultimaAlteracao: json['ultima_alteracao'],
      mensagens: msgs,
    );
  }
}

/// Modelo para Resposta da API
class RespostaApi {
  final String? pergunta;
  final List<String>? tarefas;

  RespostaApi({this.pergunta, this.tarefas});

  factory RespostaApi.fromJson(Map<String, dynamic> json) {
    return RespostaApi(
      pergunta: json['pergunta'],
      tarefas: json['tarefas'] != null ? List<String>.from(json['tarefas']) : null,
    );
  }
}

/// Widget do Drawer (Menu Lateral)
class AppDrawer extends StatelessWidget {
  final String token;
  final String email;

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

  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: ListView(
        padding: EdgeInsets.zero,
        children: <Widget>[
          DrawerHeader(
            decoration: BoxDecoration(
              color: Colors.blue,
            ),
            child: Text(
              'Menu',
              style:
                  TextStyle(color: Colors.white, fontSize: 24),
            ),
          ),
          ListTile(
            leading: Icon(Icons.list),
            title: Text('Lista de Tarefas'),
            onTap: () {
              Navigator.pushReplacement(
                context,
                MaterialPageRoute(
                  builder: (context) =>
                      TaskListPage(token: token, email: email),
                ),
              );
            },
          ),
          ListTile(
            leading: Icon(Icons.chat),
            title: Text('Chat'),
            onTap: () {
              Navigator.pushReplacement(
                context,
                MaterialPageRoute(
                  builder: (context) =>
                      ChatPage(token: token, email: email),
                ),
              );
            },
          ),
          ListTile(
            leading: Icon(Icons.chat_bubble_outline),
            title: Text('Iniciar outra conversa'),
            onTap: () {
              Navigator.pushReplacement(
                context,
                MaterialPageRoute(
                  builder: (context) =>
                      ChatPage(token: token, email: email, iniciarNovaConversa: true),
                ),
              );
            },
          ),
          ListTile(
            leading: Icon(Icons.logout),
            title: Text('Logout'),
            onTap: () {
              // Implementar lógica de logout (por exemplo, limpar token armazenado)
              Navigator.pushAndRemoveUntil(
                context,
                MaterialPageRoute(builder: (context) => LoginPage()),
                (route) => false,
              );
            },
          ),
        ],
      ),
    );
  }
}

/// Página de Login
class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

/// Estado da Página de Login
class _LoginPageState extends State<LoginPage> {
  final emailController = TextEditingController();
  final passwordController = TextEditingController();

  /// Função para realizar o login
  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'];
        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()}')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Login'),
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: SingleChildScrollView( // Para evitar overflow no teclado
          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'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

/// Página de Cadastro
class SignUpPage extends StatefulWidget {
  @override
  _SignUpPageState createState() => _SignUpPageState();
}

/// Estado da Página de Cadastro
class _SignUpPageState extends State<SignUpPage> {
  final emailController = TextEditingController();
  final passwordController = TextEditingController();
  final confirmPasswordController = TextEditingController();
  final phoneController = TextEditingController();
  final nomeController = TextEditingController();

  /// Função para realizar o cadastro
  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 url = Uri.parse('https://barra.cos.ufrj.br:443/rest/rpc/registra_usuario');

    try {
      final response = await http.post(
        url,
        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.')));
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Ocorreu um erro: ${e.toString()}')),
      );
    }
  }

  /// Função para criar tarefas no servidor após o cadastro
  Future<void> criarTarefas(String token, String email) async {
    final url = Uri.parse('https://barra.cos.ufrj.br:443/rest/tarefas');
    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'),
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: SingleChildScrollView( // Evitar overflow ao abrir o teclado
          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')),
            ],
          ),
        ),
      ),
    );
  }
}

/// Página de Lista de Tarefas
class TaskListPage extends StatefulWidget {
  final String token;
  final String email;

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

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

/// Estado da Página de Lista de Tarefas
class _TaskListPageState extends State<TaskListPage> {
  List<Map<String, dynamic>> tasks = [];
  final textController = TextEditingController();

  bool _tasksLoaded = false;
  Map<String, Timer> _deleteTimers = {};

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

  /// Função para buscar tarefas do servidor
  Future<void> fetchTasks() async {
    final url = Uri.parse(
        'https://barra.cos.ufrj.br:443/rest/tarefas?email=eq.${widget.email}');
    try {
      final response = await http.get(
        url,
        headers: {
          'Authorization': 'Bearer ${widget.token}',
          'Content-Type': 'application/json'
        },
      );

      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        setState(() {
          tasks.clear();
          if (data.isNotEmpty) {
            tasks.addAll(List<Map<String, dynamic>>.from(data[0]['valor']));
          }
          for (var task in tasks) {
            task['isBeingDeleted'] = false;
            task['isAnimating'] = false;
          }
          _tasksLoaded = true;
        });
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
              content:
                  Text('Erro ao carregar tarefas: ${response.statusCode}')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Ocorreu um erro: ${e.toString()}')),
      );
    }
  }

  /// Função para adicionar uma nova tarefa
  Future<void> addTask(String title) async {
    if (title.trim().isEmpty) return;

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

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

  /// Função para atualizar tarefas no servidor
  Future<void> updateTasksOnServer() async {
    final url = Uri.parse(
        'https://barra.cos.ufrj.br:443/rest/tarefas?email=eq.${widget.email}');
    try {
      final response = await http.patch(
        url,
        headers: {
          'Authorization': 'Bearer ${widget.token}',
          'Content-Type': 'application/json'
        },
        body: json.encode({'email': widget.email, 'valor': tasks}),
      );

      if (response.statusCode != 204) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
              content: Text(
                  'Erro ao atualizar tarefas: ${response.statusCode} ${response.body}')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Ocorreu um erro: ${e.toString()}')),
      );
    }
  }

  /// Função para alternar o status de conclusão de uma tarefa
  void _toggleCompletion(int index) {
    setState(() {
      var task = tasks[index];
      task['concluida'] = !task['concluida'];
      task['isAnimating'] = true;

      tasks.removeAt(index);

      if (task['concluida'] == true) {
        int newIndex = tasks.indexWhere((t) => t['concluida'] == true);
        if (newIndex == -1) {
          tasks.add(task);
        } else {
          tasks.insert(newIndex, task);
        }
      } else {
        int newIndex = tasks.lastIndexWhere((t) => t['concluida'] == false);
        tasks.insert(newIndex + 1, task);
      }

      Future.delayed(Duration(milliseconds: 500), () {
        setState(() {
          task['isAnimating'] = false;
        });
      });
    });

    updateTasksOnServer();
  }

  /// Função para deletar uma tarefa com opção de desfazer
  void _deleteTaskWithUndo(int index) {
    final task = tasks[index];
    setState(() {
      tasks[index]['isBeingDeleted'] = true;
    });

    _deleteTimers[task['titulo']] = Timer(Duration(seconds: 3), () {
      if (mounted &&
          tasks.contains(task) &&
          task['isBeingDeleted'] == true) {
        _deleteTask(index);
      }
    });

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('Tarefa "${task['titulo']}" será deletada em 3 segundos'),
        action: SnackBarAction(
          label: 'Desfazer',
          onPressed: () {
            _undoDeleteTask(index);
          },
        ),
      ),
    );
  }

  /// Função para desfazer a exclusão de uma tarefa
  void _undoDeleteTask(int index) {
    final task = tasks[index];
    setState(() {
      tasks[index]['isBeingDeleted'] = false;
    });

    _deleteTimers[task['titulo']]?.cancel();
    _deleteTimers.remove(task['titulo']);

    updateTasksOnServer();
  }

  /// Função para deletar uma tarefa permanentemente
  void _deleteTask(int index) {
    final task = tasks[index];
    _deleteTimers[task['titulo']]?.cancel();
    _deleteTimers.remove(task['titulo']);

    setState(() {
      tasks.removeAt(index);
    });
    updateTasksOnServer();
  }

  /// Função para calcular a posição topo de uma tarefa (usado em animações)
  double _calculateTopPosition(int index) {
    double itemHeight = 86.0;
    return index * itemHeight;
  }

  @override
  Widget build(BuildContext context) {
    if (!_tasksLoaded) {
      return Scaffold(
        appBar: AppBar(
          title: const Text('Lista de Tarefas'),
          backgroundColor: const Color.fromARGB(255, 128, 0, 0),
        ),
        drawer: AppDrawer(token: widget.token, email: widget.email),
        body: Center(child: CircularProgressIndicator()),
      );
    }

    List<Widget> taskWidgets = [];
    for (var i = 0; i < tasks.length; i++) {
      final task = tasks[i];
      final isBeingDeleted = task['isBeingDeleted'] == true;
      final isCompleted = task['concluida'] == true;
      final topPosition = _calculateTopPosition(i);

      final backgroundColor = isBeingDeleted
          ? Colors.red
          : (i % 3 == 0
              ? const Color.fromARGB(255, 99, 12, 0)
              : i % 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;

      Widget taskWidget = AnimatedPositioned(
        key: ValueKey(task['titulo']),
        duration: Duration(milliseconds: 500),
        curve: Curves.easeInOut,
        top: topPosition,
        left: 0,
        right: 0,
        child: TweenAnimationBuilder<double>(
          key:
              ValueKey(task['titulo'] + task['isAnimating'].toString()),
          tween: Tween(begin: task['isAnimating'] ? 0.1 : 0.0, end: 0.0),
          duration: Duration(milliseconds: 500),
          builder: (context, tilt, child) {
            return Transform(
              transform: Matrix4.rotationZ(tilt),
              alignment: Alignment.center,
              child: child,
            );
          },
          child: Dismissible(
            key: ValueKey(task['titulo'] + "dismissible"),
            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 {
              int currentIndex = tasks.indexOf(task);
              if (direction == DismissDirection.endToStart) {
                _deleteTaskWithUndo(currentIndex);
                return false;
              } else if (direction == DismissDirection.startToEnd) {
                _toggleCompletion(currentIndex);
                return false;
              }
              return false;
            },
            child: Container(
              margin:
                  const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
              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: (_) {
                        int currentIndex = tasks.indexOf(task);
                        _toggleCompletion(currentIndex);
                      },
                    ),
                    isBeingDeleted
                        ? IconButton(
                            icon: const Icon(Icons.undo),
                            onPressed: () {
                              int currentIndex = tasks.indexOf(task);
                              _undoDeleteTask(currentIndex);
                            },
                          )
                        : IconButton(
                            icon: const Icon(Icons.delete),
                            onPressed: () {
                              int currentIndex = tasks.indexOf(task);
                              _deleteTaskWithUndo(currentIndex);
                            },
                          ),
                  ],
                ),
              ),
            ),
          ),
        ),
      );

      taskWidgets.add(taskWidget);
    }

    double totalHeight = tasks.length * 86.0;

    return Scaffold(
      appBar: AppBar(
        title: const Text('Lista de Tarefas'),
        backgroundColor: const Color.fromARGB(255, 128, 0, 0),
      ),
      drawer: AppDrawer(token: widget.token, email: widget.email),
      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: SingleChildScrollView(
              child: SizedBox(
                height: totalHeight,
                child: Stack(
                  children: taskWidgets,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

/// Página de Chat
class ChatPage extends StatefulWidget {
  final String token;
  final String email;
  final bool iniciarNovaConversa;

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

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

/// Estado da Página de Chat
class _ChatPageState extends State<ChatPage> {
  String? conversaId;
  List<Message> mensagens = [];
  TextEditingController _controller = TextEditingController();
  bool podeEnviar = true;
  bool isLoading = true;

  @override
  void initState() {
    super.initState();
    if (widget.iniciarNovaConversa) {
      criarNovaConversa();
    } else {
      verificarOuCriarConversa();
    }
  }

  /// Função para verificar se já existe uma conversa ou criar uma nova
  Future<void> verificarOuCriarConversa() async {
    print(widget.email);
    final url = Uri.parse(
        'https://barra.cos.ufrj.br:443/rest/conversas?email=eq.${widget.email}');
    try {
      final response = await http.get(
        url,
        headers: {
          'Authorization': 'Bearer ${widget.token}',
          'Content-Type': 'application/json',
        },
      );

      if (response.statusCode == 200) {
        List<dynamic> data = json.decode(response.body);
        if (data.isNotEmpty) {
          setState(() {
            conversaId = data.first['id'];
            mensagens = List<Message>.from(
                data.first['mensagens'].map((msg) => Message.fromJson(msg)));
            isLoading = false;
          });
        } else {
          await criarNovaConversa();
        }
      } else {
        throw Exception('Falha ao carregar conversas: ${response.statusCode}');
      }
    } catch (e) {
      setState(() {
        isLoading = false;
      });
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Erro ao carregar conversas: ${e.toString()}')),
      );
    }
  }

  /// Função para criar uma nova conversa
  Future<void> criarNovaConversa() async {
    final url = Uri.parse('https://barra.cos.ufrj.br:443/rest/rpc/cria_conversa');

    try {
      final response = await http.post(
        url,
        headers: {
          'Authorization': 'Bearer ${widget.token}',
          'Content-Type': 'application/json',
        },
      );

      if (response.statusCode == 200) {
        var data = json.decode(response.body);
        setState(() {
          conversaId = data['uuid'];
          mensagens = []; // Inicialmente vazia
          isLoading = false;
        });
        // Carregar mensagens após criar conversa, se necessário
        await carregarMensagens();
      } else {
        throw Exception('Falha ao criar conversa: ${response.statusCode}');
      }
    } catch (e) {
      setState(() {
        isLoading = false;
      });
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Erro ao criar conversa: ${e.toString()}')),
      );
    }
  }

  /// Função para carregar mensagens da conversa
  Future<void> carregarMensagens() async {
    if (conversaId == null) return;

    final url = Uri.parse(
        'https://barra.cos.ufrj.br:443/rest/conversas?id=eq.$conversaId');

    try {
      final response = await http.get(
        url,
        headers: {
          'Authorization': 'Bearer ${widget.token}',
          'Content-Type': 'application/json',
        },
      );

      if (response.statusCode == 200) {
        List<dynamic> data = json.decode(response.body);
        if (data.isNotEmpty) {
          setState(() {
            mensagens = List<Message>.from(
                data.first['mensagens'].map((msg) => Message.fromJson(msg)));
          });
        }
      } else {
        throw Exception('Falha ao carregar mensagens: ${response.statusCode}');
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Erro ao carregar mensagens: ${e.toString()}')),
      );
    }
  }

  /// Função para enviar uma mensagem
  Future<void> enviarMensagem(String texto) async {
    if (!podeEnviar || conversaId == null || texto.trim().isEmpty){
      return;}

    setState(() {
      podeEnviar = false;
      mensagens.add(Message(papel: 'usuario', conteudo: texto.trim()));
    });

    final url = Uri.parse('https://barra.cos.ufrj.br:443/rest/rpc/envia_resposta');

    try {
      final response = await http.post(
        url,
        headers: {
          'Authorization': 'Bearer ${widget.token}',
          'Content-Type': 'application/json',
        },
        body: json.encode({
          'conversa_id': conversaId,
          'resposta': texto.trim(),
        }),
      );

      if (response.statusCode == 200) {
        var data = json.decode(response.body);
        if (data['pergunta'] != null) {
          setState(() {
            mensagens.add(Message(papel: 'assistente', conteudo: data['pergunta']));
          });
        }
        if (data['tarefas'] != null) {
          List<String> tarefas = List<String>.from(data['tarefas']);
          if (tarefas.isNotEmpty) {
            await mostrarDialogoTarefas(tarefas);
          }
        }

        // Recarregar mensagens para garantir sincronização
        await carregarMensagens();

        setState(() {
          podeEnviar = true;
        });
      } else {
        throw Exception('Falha ao enviar resposta: ${response.statusCode}');
      }
    } catch (e) {
      setState(() {
        podeEnviar = true;
      });
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Erro ao enviar mensagem: ${e.toString()}')),
      );
    }
  }

  /// Função para mostrar diálogo após receber tarefas
  Future<void> mostrarDialogoTarefas(List<String> tarefas) async {
    return showDialog<void>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('Tarefas Geradas'),
          content: SingleChildScrollView(
            child: ListBody(
              children: tarefas.map((t) => Text(t)).toList(),
            ),
          ),
          actions: <Widget>[
            TextButton(
              child: Text('Continuar Chat'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            TextButton(
              child: Text('Criar nova Lista'),
              onPressed: () {
                Navigator.of(context).pop();
                Navigator.pushReplacement(
                  context,
                  MaterialPageRoute(
                    builder: (context) => TaskListPage(
                        token: widget.token, email: widget.email),
                  ),
                );
              },
            ),
            TextButton(
              child: Text('Adicionar à Lista Existente'),
              onPressed: () {
                // Implementar lógica para adicionar à lista existente
                // Por exemplo, navegar para TaskListPage e adicionar as tarefas
                Navigator.of(context).pop();
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => TaskListPage(
                        token: widget.token, email: widget.email),
                  ),
                );
              },
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Chat'),
      ),
      drawer: AppDrawer(token: widget.token, email: widget.email),
      body: isLoading
          ? Center(child: CircularProgressIndicator())
          : Column(
              children: [
                Expanded(
                  child: ListView.builder(
                    reverse: true, // Para manter as mensagens mais recentes na parte inferior
                    padding: EdgeInsets.all(16.0),
                    itemCount: mensagens.length,
                    itemBuilder: (context, index) {
                      final msg = mensagens[mensagens.length - 1 - index];
                      return Align(
                        alignment: msg.papel == 'usuario'
                            ? Alignment.centerRight
                            : Alignment.centerLeft,
                        child: Container(
                          padding: EdgeInsets.all(10),
                          margin: EdgeInsets.symmetric(vertical: 5),
                          decoration: BoxDecoration(
                            color: msg.papel == 'usuario'
                                ? Colors.blue[100]
                                : Colors.grey[300],
                            borderRadius: BorderRadius.circular(10),
                          ),
                          child: Text(msg.conteudo),
                        ),
                      );
                    },
                  ),
                ),
                Divider(height: 1),
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 8),
                  color: Colors.white,
                  child: Row(
                    children: [
                      Expanded(
                        child: TextField(
                          controller: _controller,
                          enabled: podeEnviar,
                          decoration: InputDecoration.collapsed(
                            hintText: 'Digite sua mensagem',
                          ),
                        ),
                      ),
                      IconButton(
                        icon: Icon(Icons.send),
                        onPressed: podeEnviar
                            ? () {
                                String texto = _controller.text.trim();
                                if (texto.isNotEmpty) {
                                  enviarMensagem(texto);
                                  _controller.clear();
                                }
                              }
                            : null,
                      ),
                    ],
                  ),
                ),
              ],
            ),
    );
  }
}