I need help with my flutter code. It can't create lists. I'm receiving error 400: import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

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

// ---------------------------------
// 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'];

        // Navegar para a tela inicial após o login
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder: (context) => HomePage(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',
          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!')));
      Navigator.pop(context);
    } else {
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text('Erro ao cadastrar.')));
    }
  }

  @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'),
            ),
          ],
        ),
      ),
    );
  }
}

// ---------------------------------
// HomePage
// ---------------------------------
class HomePage extends StatelessWidget {
  final String token;
  final String email;

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          'Página Inicial',
          style: TextStyle(color: Colors.white),
        ),
        backgroundColor: const Color.fromARGB(255, 128, 0, 0),
      ),
      drawer: _buildDrawer(context),
      body: Center(
        child: Text(
          'Bem-vindo, $email!',
          style: TextStyle(fontSize: 24),
        ),
      ),
    );
  }

  Widget _buildDrawer(BuildContext context) {
    return 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.home),
            title: Text('Página Inicial'),
            onTap: () {
              Navigator.pop(context);
              // Já estamos na HomePage
            },
          ),
          ListTile(
            leading: Icon(Icons.chat),
            title: Text('Chats'),
            onTap: () {
              Navigator.pop(context);
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => ChatListPage(token: token, email: email),
                ),
              );
            },
          ),
          ListTile(
            leading: Icon(Icons.list),
            title: Text('Listas de Tarefas'),
            onTap: () {
              Navigator.pop(context);
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => TaskListsPage(token: token, email: email),
                ),
              );
            },
          ),
          ListTile(
            leading: Icon(Icons.logout),
            title: Text('Logout'),
            onTap: () {
              Navigator.pop(context);
              _logout(context);
            },
          ),
        ],
      ),
    );
  }

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

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

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

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

class _ChatListPageState extends State<ChatListPage> {
  List<Map<String, dynamic>> chats = [];

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

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

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

      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        setState(() {
          chats = List<Map<String, dynamic>>.from(data);
        });
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Erro ao carregar chats: ${response.statusCode}')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Erro: ${e.toString()}')),
      );
    }
  }

  void _openChat(Map<String, dynamic> chat) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => ChatPage(
          token: widget.token,
          email: widget.email,
          conversaId: chat['id'].toString(),
        ),
      ),
    );
  }

  Future<void> _deleteChat(String chatId) async {
    final url = Uri.parse('https://barra.cos.ufrj.br/rest/conversas?id=eq.$chatId');
    final headers = {
      'Authorization': 'Bearer ${widget.token}',
      'accept': 'application/json',
    };

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

      if (response.statusCode == 204) {
        setState(() {
          chats.removeWhere((chat) => chat['id'].toString() == chatId);
        });
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Erro ao deletar chat: ${response.statusCode}')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Erro: ${e.toString()}')),
      );
    }
  }

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

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

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

  Widget _buildDrawer() {
    return 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.home),
            title: Text('Página Inicial'),
            onTap: () {
              Navigator.pop(context);
              Navigator.pushReplacement(
                context,
                MaterialPageRoute(
                  builder: (context) => HomePage(token: widget.token, email: widget.email),
                ),
              );
            },
          ),
          ListTile(
            leading: Icon(Icons.chat),
            title: Text('Chats'),
            onTap: () {
              Navigator.pop(context);
              // Já estamos na tela de Chats
            },
          ),
          ListTile(
            leading: Icon(Icons.list),
            title: Text('Listas de Tarefas'),
            onTap: () {
              Navigator.pop(context);
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => TaskListsPage(token: widget.token, email: widget.email),
                ),
              );
            },
          ),
          ListTile(
            leading: Icon(Icons.logout),
            title: Text('Logout'),
            onTap: () {
              Navigator.pop(context);
              _logout();
            },
          ),
        ],
      ),
    );
  }

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

  // Método build
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Chats', style: TextStyle(color: Colors.white)),
        backgroundColor: const Color.fromARGB(255, 128, 0, 0),
      ),
      drawer: _buildDrawer(),
      body: ListView.builder(
        itemCount: chats.length,
        itemBuilder: (context, index) {
          final chat = chats[index];
          return ListTile(
            title: Text('Chat ${chat['id']}'),
            onTap: () => _openChat(chat),
            trailing: IconButton(
              icon: Icon(Icons.delete),
              onPressed: () => _deleteChat(chat['id'].toString()),
            ),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _createNewChat,
        backgroundColor: const Color.fromARGB(255, 128, 0, 0),
        child: Icon(Icons.add),
      ),
    );
  }
}

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

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

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

class _TaskListsPageState extends State<TaskListsPage> {
  List<Map<String, dynamic>> taskLists = [];
  final textController = TextEditingController();

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

  Future<void> _fetchTaskLists() async {
    final url = Uri.parse('https://barra.cos.ufrj.br/rest/tarefasv2?email=eq.${widget.email}');
    final headers = {
      'Authorization': 'Bearer ${widget.token}',
      'accept': 'application/json',
    };

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

      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        setState(() {
          taskLists = List<Map<String, dynamic>>.from(data);
        });
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
              content:
                  Text('Erro ao carregar listas de tarefas: ${response.statusCode}')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Erro: ${e.toString()}')),
      );
    }
  }

  void _openTaskList(Map<String, dynamic> taskList) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => TaskListPage(
          token: widget.token,
          email: widget.email,
          taskListId: taskList['id'].toString(),
          titulo: taskList['titulo'] ?? 'Lista de Tarefas',
        ),
      ),
    );
  }

  Future<void> _deleteTaskList(String taskListId) async {
    final url = Uri.parse('https://barra.cos.ufrj.br/rest/tarefasv2?id=eq.$taskListId');
    final headers = {
      'Authorization': 'Bearer ${widget.token}',
      'accept': 'application/json',
    };

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

      if (response.statusCode == 204) {
        setState(() {
          taskLists.removeWhere((taskList) => taskList['id'].toString() == taskListId);
        });
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
              content:
                  Text('Erro ao deletar lista de tarefas: ${response.statusCode}')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Erro: ${e.toString()}')),
      );
    }
  }

  Future<void> _createNewTaskList(String title) async {
    if (title.trim().isEmpty) {
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text('O título não pode ser vazio.')));
      return;
    }

    final url = Uri.parse('https://barra.cos.ufrj.br/rest/tarefasv2');
    final headers = {
      'Authorization': 'Bearer ${widget.token}',
      'Content-Type': 'application/json',
    };
    final body = json.encode({
      'email': widget.email,
      'titulo': title,
      'valor': [],
      'atributos': {},
    });

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

      if (response.statusCode == 201) {
        _fetchTaskLists();
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text('Lista criada com sucesso!')));
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
              content:
                  Text('Erro ao criar lista de tarefas: ${response.statusCode}')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Erro: ${e.toString()}')),
      );
    }
  }

  void _showCreateTaskListDialog() {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text("Nova Lista de Tarefas"),
          content: TextField(
            controller: textController,
            decoration: InputDecoration(hintText: "Nome da lista"),
          ),
          actions: [
            TextButton(
              onPressed: () {
                _createNewTaskList(textController.text.trim());
                textController.clear();
                Navigator.pop(context);
              },
              child: Text("Criar"),
            ),
            TextButton(
              onPressed: () {
                textController.clear();
                Navigator.pop(context);
              },
              child: Text("Cancelar"),
            ),
          ],
        );
      },
    );
  }

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

  Widget _buildDrawer() {
    return 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.home),
            title: Text('Página Inicial'),
            onTap: () {
              Navigator.pop(context);
              Navigator.pushReplacement(
                context,
                MaterialPageRoute(
                  builder: (context) => HomePage(token: widget.token, email: widget.email),
                ),
              );
            },
          ),
          ListTile(
            leading: Icon(Icons.chat),
            title: Text('Chats'),
            onTap: () {
              Navigator.pop(context);
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => ChatListPage(token: widget.token, email: widget.email),
                ),
              );
            },
          ),
          ListTile(
            leading: Icon(Icons.list),
            title: Text('Listas de Tarefas'),
            onTap: () {
              Navigator.pop(context);
              // Já estamos na tela de Listas de Tarefas
            },
          ),
          ListTile(
            leading: Icon(Icons.logout),
            title: Text('Logout'),
            onTap: () {
              Navigator.pop(context);
              _logout();
            },
          ),
        ],
      ),
    );
  }

  // Método build
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Listas de Tarefas', style: TextStyle(color: Colors.white)),
        backgroundColor: const Color.fromARGB(255, 128, 0, 0),
      ),
      drawer: _buildDrawer(),
      body: ListView.builder(
        itemCount: taskLists.length,
        itemBuilder: (context, index) {
          final taskList = taskLists[index];
          return ListTile(
            title: Text(taskList['titulo'] ?? 'Lista ${taskList['id']}'),
            onTap: () => _openTaskList(taskList),
            trailing: IconButton(
              icon: Icon(Icons.delete),
              onPressed: () => _deleteTaskList(taskList['id'].toString()),
            ),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _showCreateTaskListDialog,
        backgroundColor: const Color.fromARGB(255, 128, 0, 0),
        child: Icon(Icons.add),
      ),
    );
  }
}

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

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

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

class _TaskListPageState extends State<TaskListPage> {
  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/rest/tarefasv2?select=valor&id=eq.${widget.taskListId}');
    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/rest/tarefasv2?id=eq.${widget.taskListId}');
    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'] == true) {
        _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();
  }

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

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

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

  Widget _buildDrawer() {
    return 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.home),
            title: Text('Página Inicial'),
            onTap: () {
              Navigator.pop(context);
              Navigator.pushReplacement(
                context,
                MaterialPageRoute(
                  builder: (context) =>
                      HomePage(token: widget.token, email: widget.email),
                ),
              );
            },
          ),
          ListTile(
            leading: Icon(Icons.chat),
            title: Text('Chats'),
            onTap: () {
              Navigator.pop(context);
              _navegarParaChatList();
            },
          ),
          ListTile(
            leading: Icon(Icons.list),
            title: Text('Listas de Tarefas'),
            onTap: () {
              Navigator.pop(context);
              _navegarParaTaskLists();
            },
          ),
          ListTile(
            leading: Icon(Icons.logout),
            title: Text('Logout'),
            onTap: () {
              Navigator.pop(context);
              _logout();
            },
          ),
        ],
      ),
    );
  }

  // Método build
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          widget.titulo,
          style: TextStyle(color: Colors.white),
        ),
        backgroundColor: const Color.fromARGB(255, 128, 0, 0),
      ),
      drawer: _buildDrawer(),
      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;
  final String? conversaId;

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

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

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

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

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

    final url = conversaId != null
        ? Uri.parse('https://barra.cos.ufrj.br/rest/conversas?id=eq.$conversaId')
        : Uri.parse('https://barra.cos.ufrj.br/rest/conversas');
    final headers = {
      'Authorization': 'Bearer ${widget.token}',
      'accept': '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'].toString();
          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;
    });
    _scrollToBottom();

    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: SingleChildScrollView(
          child: ListBody(
            children: [
              Text('O chat gerou a seguinte lista de tarefas:'),
              SizedBox(height: 10),
              ...tarefas.map((tarefa) => Text('- $tarefa')).toList(),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              // Continuar o chat
            },
            child: Text('Continuar o chat'),
          ),
          TextButton(
            onPressed: () async {
              Navigator.pop(context);
              // Criar nova 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 {
  // Primeiro, permitir ao usuário selecionar em qual lista adicionar as tarefas
  // Buscar todas as listas de tarefas do usuário
  final taskListsUrl = Uri.parse('https://barra.cos.ufrj.br/rest/tarefasv2?email=eq.${widget.email}');
  final taskListsHeaders = {
    'Authorization': 'Bearer ${widget.token}',
    'accept': 'application/json',
  };

  List<Map<String, dynamic>> taskLists = [];

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

    if (response.statusCode == 200) {
      final data = json.decode(response.body);
      taskLists = List<Map<String, dynamic>>.from(data);
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Erro ao carregar listas de tarefas: ${response.statusCode}')),
      );
      return;
    }
  } catch (e) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('Erro: ${e.toString()}')),
    );
    return;
  }

  // Se o usuário não tiver listas de tarefas, pedir para criar uma nova
  if (taskLists.isEmpty) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('Você não tem nenhuma lista de tarefas.')),
    );
    return;
  }

  // Exibir um diálogo para o usuário escolher a lista de tarefas
  String? selectedTaskListId = await showDialog<String>(
    context: context,
    builder: (context) => SimpleDialog(
      title: Text('Selecione uma lista de tarefas'),
      children: taskLists
          .map((taskList) => SimpleDialogOption(
                onPressed: () {
                  Navigator.pop(context, taskList['id'].toString());
                },
                child: Text(taskList['titulo'] ?? 'Lista ${taskList['id']}'),
              ))
          .toList(),
    ),
  );

  if (selectedTaskListId == null) {
    return; // Usuário cancelou
  }

  // Obter as tarefas atuais da lista selecionada
  List<Map<String, dynamic>> tarefasAtuais = [];
  if (!apagarAnterior) {
    // Buscar tarefas existentes
    final tarefasUrl = Uri.parse(
        'https://barra.cos.ufrj.br/rest/tarefasv2?select=valor&id=eq.$selectedTaskListId');
    final tarefasHeaders = {
      'Authorization': 'Bearer ${widget.token}',
      'Content-Type': 'application/json',
    };

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

    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 updateUrl = Uri.parse(
      'https://barra.cos.ufrj.br/rest/tarefasv2?id=eq.$selectedTaskListId');
  final updateHeaders = {
    'Authorization': 'Bearer ${widget.token}',
    'Content-Type': 'application/json',
  };
  final body = json.encode({
    'valor': novasTarefas,
  });

  final updateResponse =
      await http.patch(updateUrl, headers: updateHeaders, body: body);

  if (updateResponse.statusCode != 204) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
          content: Text(
              'Erro ao atualizar tarefas: ${updateResponse.statusCode} ${updateResponse.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) => TaskListsPage(
          token: widget.token,
          email: widget.email,
        ),
      ),
    );
  }

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

  void _scrollToBottom() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_scrollController.hasClients) {
        _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
      }
    });
  }

  Widget _buildDrawer() {
    return 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.home),
            title: Text('Página Inicial'),
            onTap: () {
              Navigator.pop(context);
              Navigator.pushReplacement(
                context,
                MaterialPageRoute(
                  builder: (context) =>
                      HomePage(token: widget.token, email: widget.email),
                ),
              );
            },
          ),
          ListTile(
            leading: Icon(Icons.chat),
            title: Text('Chats'),
            onTap: () {
              Navigator.pop(context);
              _navegarParaChatList();
            },
          ),
          ListTile(
            leading: Icon(Icons.list),
            title: Text('Listas de Tarefas'),
            onTap: () {
              Navigator.pop(context);
              _navegarParaListaDeTarefas();
            },
          ),
          ListTile(
            leading: Icon(Icons.logout),
            title: Text('Logout'),
            onTap: () {
              Navigator.pop(context);
              _logout();
            },
          ),
        ],
      ),
    );
  }

  // Método build
  @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: _buildDrawer(),
      body: Column(
        children: [
          Expanded(
            child: isLoading && messages.isEmpty
                ? Center(child: CircularProgressIndicator())
                : ListView.builder(
                    controller: _scrollController,
                    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,
                    onSubmitted: (value) {
                      if (!isLoading) {
                        _enviarMensagem(value);
                      }
                    },
                  ),
                ),
                IconButton(
                  icon: Icon(Icons.send),
                  onPressed: isLoading
                      ? null
                      : () => _enviarMensagem(textController.text),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}