import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:miapp_flutter/src/models/CategoriaModel.dart'; import 'dart:convert'; import '../controllers/CategoriaController.dart'; class NewCategoryPage extends StatefulWidget { const NewCategoryPage({Key? key}) : super(key: key); @override _NewCategoryPageState createState() => _NewCategoryPageState(); } class _NewCategoryPageState extends State { final _formKey = GlobalKey(); final _claveController = TextEditingController(); final _nombreController = TextEditingController(); DateTime _selectedDate = DateTime.now(); final _categoryController = CategoryController(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Nueva Categoría'), backgroundColor: Colors.blue, ), body: Padding( padding: const EdgeInsets.all(16.0), child: Form( key: _formKey, child: Column( children: [ TextFormField( controller: _claveController, decoration: const InputDecoration(labelText: 'Clave'), validator: (value) { if (value == null || value.isEmpty) { return 'Por favor ingrese una clave'; } return null; }, ), TextFormField( controller: _nombreController, decoration: const InputDecoration(labelText: 'Nombre'), validator: (value) { if (value == null || value.isEmpty) { return 'Por favor ingrese un nombre'; } return null; }, ), const SizedBox(height: 16.0), TextFormField( readOnly: true, decoration: InputDecoration( labelText: 'Fecha de Creación', hintText: DateFormat('yyyy-MM-dd').format(_selectedDate), ), onTap: () async { DateTime? pickedDate = await showDatePicker( context: context, initialDate: _selectedDate, firstDate: DateTime(2000), lastDate: DateTime(2101), ); if (pickedDate != null && pickedDate != _selectedDate) { setState(() { _selectedDate = pickedDate; }); } }, ), const SizedBox(height: 16.0), ElevatedButton( onPressed: () async { if (_formKey.currentState!.validate()) { CategoriaModel newCategory = CategoriaModel( id: 0, key: _claveController.text, name: _nombreController.text, createdDate: _selectedDate.millisecondsSinceEpoch, active: true, ); var response = await _categoryController.createCategory(newCategory); print('Datos de la categoría a enviar: ${json.encode(newCategory.toJson())}'); print(response); if (response['ok'] ) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Categoría creada con éxito')), ); Navigator.pushNamed(context,'home'); } else { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Error al crear categoría: ${response['body']}')), ); } } }, child: const Text('GUARDAR'), style: ElevatedButton.styleFrom( foregroundColor: Colors.white, backgroundColor: Colors.blue, ), ), ], ), ), ), ); } }