import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:prosappco/src/authentication/authentication_repository.dart';
import 'package:prosappco/src/components/pop_appbar.dart';
import 'package:prosappco/src/components/primary_btn.dart';
import '../components/schedule_picker.dart';

class HorarioScreen extends StatelessWidget {
  Map<String, Schedule> horarios;
  HorarioScreen({super.key, required this.horarios});

  final uid = AuthenticationRepository.instance.getCurrentUserUid();
  bool lunesValue = false;
  bool martesValue = false;
  bool miercolesValue = false;
  bool juevesValue = false;
  bool viernesValue = false;
  bool sabadoValue = false;
  bool domingoValue = false;
  bool jornadaContinuaLunes = false;

  Future<void> updateHorario(BuildContext context) async {
    try {
      Map<String, dynamic> horariosMap = {};
      horarios.forEach((key, value) {
        horariosMap[key] = {
          'habilitado': value.habilitado,
          'jornadaContinua': value.jornadaContinua,
          'range1Hour1': value.range1Hour1 != null
              ? value.range1Hour1!.format(context).toString()
              : null,
          'range1Hour2': value.range1Hour2 != null
              ? value.range1Hour2!.format(context).toString()
              : null,
          'range2Hour1': value.range2Hour1 != null
              ? value.range2Hour1!.format(context).toString()
              : null,
          'range2Hour2': value.range2Hour2 != null
              ? value.range2Hour2!.format(context).toString()
              : null,
        };
      });

      await FirebaseFirestore.instance.collection('users').doc(uid).update({
        'horario': horariosMap,
      });
    } catch (e) {
      print('Error al actualizar el horario: $e');
    }
  }

  int _dayOfWeekToInt(String dayOfWeek) {
    switch (dayOfWeek) {
      case 'Lunes':
        return 1;
      case 'Martes':
        return 2;
      case 'Miercoles':
        return 3;
      case 'Jueves':
        return 4;
      case 'Viernes':
        return 5;
      case 'Sabado':
        return 6;
      case 'Domingo':
        return 7;
      default:
        throw ArgumentError('Invalid day of week: $dayOfWeek');
    }
  }

  @override
  Widget build(BuildContext context) {
    final sortedHorarios = Map.fromEntries(
      horarios.entries.toList()
        ..sort(
            (a, b) => _dayOfWeekToInt(a.key).compareTo(_dayOfWeekToInt(b.key))),
    );
    return SafeArea(
      child: Scaffold(
        appBar: PopAppbar(
            onPressed: () {
              Navigator.pop(context);
            },
            label: 'Horario'),
        body: SingleChildScrollView(
          child: Column(
            children: [
              const Divider(
                height: 5,
              ),
              Column(
                children: sortedHorarios.entries.map<Widget>(
                  (entry) {
                    return SchedulePicker(
                      name: entry.key,
                      schedule: entry.value,
                    );
                  },
                ).toList(),
              ),
              Padding(
                padding: const EdgeInsets.only(top: 30, bottom: 30),
                child: PrimaryButtom(
                  onPressed: () async {
                    await updateHorario(context);
                    Navigator.pop(context);
                  },
                  label: 'Guardar',
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
