import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:sis_flutter/data/session/session_storage.dart';
import 'package:sis_flutter/models/usuario_model.dart';
import 'package:sis_flutter/services/usuario_session_service.dart';
import 'package:sis_flutter/viewmodels/login_view_model.dart';
import 'package:sis_flutter/viewmodels/tarea_view_model.dart';
import 'package:sis_flutter/viewmodels/viewmodels.dart';
import 'package:sis_flutter/widgets/app_dropdown_search.dart';

import '../../models/actividad_model.dart';
import '../../themes/themes.dart';

class HomeBody extends StatefulWidget {
  const HomeBody({
    super.key,
  });

  @override
  State<HomeBody> createState() => _HomeBodyState();
}

class _HomeBodyState extends State<HomeBody> {
  Usuario? _usuario;
  List<Usuario> _usuariosList = [];
  TextEditingController _usuariosController = TextEditingController();

  @override
  void initState() {
    super.initState();
    final idUsuario =
        Provider.of<LoginViewModel>(context, listen: false).idUsuario;
    _fetchActividad(idUsuario);
    _loadUsuarios();
  }

  @override
  void dispose() {
    super.dispose();
  }

  Future<void> _loadUsuarios() async {
    final usuario = await getUsuarioFromSessionStorage();
    final idUsuario = usuario.id;
    final usuariosList =
        await Provider.of<UsuariosViewModel>(context, listen: false)
            .fetchUsuarios(idUsuario, 20, 0);
    setState(() {
      _usuario = usuario;
      _usuariosList = usuariosList;
    });
  }

  Future _fetchActividad(String? idUsuario) async {
    idUsuario ??= Provider.of<LoginViewModel>(context, listen: false).idUsuario;
    Provider.of<PrioridadesViewMode>(context, listen: false)
        .fetchActividad(idUsuario);
  }

  @override
  Widget build(BuildContext context) {
    var vm = Provider.of<PrioridadesViewMode>(context);
    var actividadDetalle = vm.actividadList;

    var usuario = Provider.of<LoginViewModel>(context, listen: false);

    final height = MediaQuery.of(context).size.height;

    return SafeArea(
      child: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              padding: const EdgeInsets.all(10),
              decoration: const BoxDecoration(
                  color: Colors.white,
                  borderRadius:
                      BorderRadius.vertical(bottom: Radius.circular(15))),
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Text("Bienvenido ",
                          style: TextStyle(
                            fontSize: 25,
                          )),
                      Text(_usuario!.name! ?? usuario.name!,
                          style: const TextStyle(
                              fontSize: 45,
                              fontWeight: FontWeight.bold,
                              height: -1)),
                      const SizedBox(height: 10),
                      Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10),
                          ),
                          child: AppDropdownSearch<Usuario>(
                            controller: _usuariosController,
                            itemAsString: (u) => u.name!,
                            selectedItem: _usuario,
                            compareFn: (item1, item2) {
                              return item1.id == item2.id;
                            },
                            onChanged: (selectedUsuario) {
                              if (selectedUsuario != null) {
                                _fetchActividad(selectedUsuario.id);
                              }
                            },
                            items: _usuariosList,
                            etiqueta: "Actividades",
                          )),
                    ]),
              ),
            ),
            const SizedBox(height: 10),
            SizedBox(
              width: double.infinity,
              height: height * 0.9,
              child: ListView.builder(
                  itemCount: actividadDetalle.length,
                  itemBuilder: (context, index) {
                    var actividad = actividadDetalle[index];

                    return _infoCard(actividad);
                  }),
            ),
          ],
        ),
      ),
    );
  }

  Card _infoCard(Actividad actividad) {
    List<Widget> tareaWidgets = [];
    for (var tarea in actividad.tareas!) {
      final posicion = (actividad.tareas!.indexOf(tarea) + 1).toString();
      tareaWidgets.add(
        ListTile(
          title: Text(tarea.contenido!),
          subtitle: Text("Subtarea ${tarea.iops}"),
        ),
      );
    }
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 8),
      elevation: 4,
      shape: BeveledRectangleBorder(borderRadius: BorderRadius.circular(6.0)),
      child: ExpansionTile(
        backgroundColor: Colors.white24,
        leading: const Icon(Icons.local_fire_department_rounded),
        title: Text(
          "${actividad.nombreProyecto!} - ${actividad.nombre!} ",
          style: const TextStyle(
              fontSize: 20, fontWeight: FontWeight.bold, color: Colors.black54),
          strutStyle: const StrutStyle(fontWeight: FontWeight.bold),
        ),
        trailing: const Icon(Icons.arrow_drop_down),
        subtitle: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(actividad.avance!),
            const SizedBox(width: 10),
            Expanded(
              child: ClipRRect(
                borderRadius: const BorderRadius.all(Radius.circular(10)),
                child: LinearProgressIndicator(
                    value: double.parse(actividad.avance!) / 100,
                    backgroundColor: Colors.grey,
                    valueColor: const AlwaysStoppedAnimation(AppTheme.primary)),
              ),
            ),
          ],
        ),
        children: tareaWidgets,
      ),
    );
  }
}
