import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:get/get.dart';
import 'package:prosappco/src/authentication/authentication_repository.dart';
import 'package:prosappco/src/components/banner_photo.dart';
import 'package:prosappco/src/components/pop_appbar.dart';
import 'package:prosappco/src/components/primary_btn.dart';
import 'package:prosappco/src/components/schedule_picker.dart';
import 'package:prosappco/src/models/setting_model.dart';
import 'package:prosappco/src/screens/horario.dart';
import 'package:prosappco/src/screens/professional.dart';
import 'package:prosappco/src/screens/professional_direccion.dart';
import 'package:prosappco/src/services/select_image_profile.dart';

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

  @override
  State<ProfileProScreen> createState() => _ProfileProScreenState();
}

class _ProfileProScreenState extends State<ProfileProScreen> {
  final uid = AuthenticationRepository.instance.getCurrentUserUid();
  final TextEditingController _opcionalAddressController =
      TextEditingController();
  final TextEditingController _tarifaController = TextEditingController();

  File? image_portada;
  File? imagen_to_upload;

  bool domicilioValue = false;
  bool tarifaValue = false;
  bool sitioValue = false;
  var photoTemp = '';

  var _photo = '...';
  var _direccion = '...';
  var _ubicacion = '...';
  var _opcionalAddress = '...';
  int _tarifa = 0;
  SettingModel? settings;

  Map<String, Schedule>? _horarios;

  @override
  void initState() {
    super.initState();
    if (settings == null) {
      SettingModel.getSettings().then(
        (SettingModel value) => setState(() => settings = value),
      );
    }

    final uid = AuthenticationRepository.instance.getCurrentUserUid();

    if (_photo == '...') {
      AuthenticationRepository.instance.getBanner(uid.toString()).then(
            (String s) => setState(
              () {
                _photo = s;
              },
            ),
          );
    }

    if (_horarios == null) {
      Schedule.getHorarios(uid.toString()).then(
        (Map<String, Schedule> data) {
          setState(() {
            _horarios = data;
          });
        },
      );
    }

    if (_direccion == '...') {
      AuthenticationRepository.instance
          .getAddress(uid.toString())
          .then((String s) => setState(() {
                _direccion = s;
              }));
    }
    if (_ubicacion == '...') {
      AuthenticationRepository.instance.getUbicacion(uid.toString()).then(
            (String s) => setState(
              () {
                _ubicacion = s;
                if (_ubicacion == 'ambos') {
                  sitioValue = true;
                  domicilioValue = true;
                } else if (_ubicacion == 'sitio') {
                  sitioValue = true;
                } else if (_ubicacion == 'domicilio') {
                  domicilioValue = true;
                }
              },
            ),
          );
    }
    if (_opcionalAddress == '...') {
      AuthenticationRepository.instance.getOpcionalAddress(uid.toString()).then(
            (String s) => setState(
              () {
                _opcionalAddress = s;

                if (_opcionalAddress != '...') {
                  _opcionalAddressController.text = _opcionalAddress;
                }
              },
            ),
          );
    }
    if (_tarifa == 0) {
      AuthenticationRepository.instance.getTarifa(uid.toString()).then(
            (s) => setState(
              () {
                _tarifa = s;

                if (_tarifa != 0) {
                  tarifaValue = true;
                  _tarifaController.text = _tarifa.toString();
                }
              },
            ),
          );
    }
  }

  void createSchedules() async {
    if (_horarios == null || _horarios!.isEmpty) {
      final defaultSchedule = {
        'Lunes': {
          'habilitado': false,
          'jornadaContinua': false,
          'range1Hour1': null,
          'range1Hour2': null,
          'range2Hour1': null,
          'range2Hour2': null
        },
        'Martes': {
          'habilitado': false,
          'jornadaContinua': false,
          'range1Hour1': null,
          'range1Hour2': null,
          'range2Hour1': null,
          'range2Hour2': null
        },
        'Miercoles': {
          'habilitado': false,
          'jornadaContinua': false,
          'range1Hour1': null,
          'range1Hour2': null,
          'range2Hour1': null,
          'range2Hour2': null
        },
        'Jueves': {
          'habilitado': false,
          'jornadaContinua': false,
          'range1Hour1': null,
          'range1Hour2': null,
          'range2Hour1': null,
          'range2Hour2': null
        },
        'Viernes': {
          'habilitado': false,
          'jornadaContinua': false,
          'range1Hour1': null,
          'range1Hour2': null,
          'range2Hour1': null,
          'range2Hour2': null
        },
        'Sabado': {
          'habilitado': false,
          'jornadaContinua': false,
          'range1Hour1': null,
          'range1Hour2': null,
          'range2Hour1': null,
          'range2Hour2': null
        },
        'Domingo': {
          'habilitado': false,
          'jornadaContinua': false,
          'range1Hour1': null,
          'range1Hour2': null,
          'range2Hour1': null,
          'range2Hour2': null
        }
      };

      try {
        await FirebaseFirestore.instance
            .collection('users')
            .doc(uid)
            .update({'horario': defaultSchedule});

        Navigator.pop(context);
      } catch (e) {
        print(e);
      }
    } else {
      Navigator.pushReplacement(
        context,
        CupertinoPageRoute(
          builder: (BuildContext context) {
            return HorarioScreen(
              horarios: _horarios!,
            );
          },
        ),
      );
    }
  }

  Future<void> updateInfo() async {
    if (_opcionalAddressController.text.isNotEmpty) {
      FirebaseFirestore.instance
          .collection('users')
          .doc(uid)
          .update({'opcional_address': _opcionalAddressController.text});
    }
    if (tarifaValue && _tarifaController.text.isNotEmpty) {
      FirebaseFirestore.instance
          .collection('users')
          .doc(uid)
          .update({'tarifa': int.parse(_tarifaController.text)});
    } else {
      FirebaseFirestore.instance
          .collection('users')
          .doc(uid)
          .update({'tarifa': 0});
    }

    if (domicilioValue && sitioValue) {
      FirebaseFirestore.instance
          .collection('users')
          .doc(uid)
          .update({'ubicacion': 'ambos'});
    } else if (domicilioValue) {
      FirebaseFirestore.instance
          .collection('users')
          .doc(uid)
          .update({'ubicacion': 'domicilio'});
    } else if (sitioValue) {
      FirebaseFirestore.instance
          .collection('users')
          .doc(uid)
          .update({'ubicacion': 'sitio'});
    } else {
      Get.snackbar(
        'Elige como vas a dar tu servicio',
        'Selecciona si tu servicio es a domicilio o en tu consultorio.',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.black.withOpacity(0.2),
        messageText: const Text(
          'Selecciona si tu servicio es a domicilio o en tu consultorio.',
          style: TextStyle(color: Colors.white),
        ),
      );
      return;
    }

    try {
      if (imagen_to_upload == null) {
      } else {
        updateImage(photoTemp);
        //image
      }
    } catch (e) {
      print('Error al actualizar la imagen de perfil $e');
    }

    Get.snackbar(
      'Información actualizada',
      'Su información a sido actualizada con exito.',
      snackPosition: SnackPosition.TOP,
    );

    Navigator.pop(context);
    return;
  }

  void name() {
    _horarios!.forEach((dia, horario) {
      print('Día: $dia');
      print('Habilitado: ${horario.habilitado}');
      print('Jornada Continua: ${horario.jornadaContinua}');
      print('Rango 1 Hora 1: ${horario.range1Hour1}');
      print('Rango 1 Hora 2: ${horario.range1Hour2}');
      print('Rango 2 Hora 1: ${horario.range2Hour1}');
      print('Rango 2 Hora 2: ${horario.range2Hour2}');
      print('-----------------------------------');
    });
  }

  Future<void> updateImage(image) async {
    try {
      await FirebaseFirestore.instance
          .collection('users')
          .doc(uid)
          .update({'banner': image});
    } catch (e) {
      try {
        await FirebaseFirestore.instance
            .collection('users')
            .doc(uid)
            .set({'banner': image});
      } catch (e) {
        print('Error al agregar la imagen de perfil: $e');
      }

      print('Error al actualizar la imagen de perfil: $e');
    }
  }

  Future<bool> uploadImage(File image) async {
    final String namefile = image.path.split('/').last;

    Reference ref = storage
        .ref()
        .child('users')
        .child(uid!)
        .child('profile')
        .child(namefile);

    final UploadTask uploadTask = ref.putFile(image);

    final TaskSnapshot snapshot = await uploadTask.whenComplete(() => true);

    photoTemp = ref.fullPath;

    if (snapshot.state == TaskState.success) {
      return true;
    } else {
      return false;
    }
  }

  Future<void> _showChoiceDialog(BuildContext context) async {
    return showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          content: SingleChildScrollView(
            child: ListBody(
              children: [
                GestureDetector(
                  child: const Text(
                    textAlign: TextAlign.center,
                    "Tomar foto",
                    style: TextStyle(color: Color(0xFF2BA4EC)),
                  ),
                  onTap: () async {
                    final imagen = await getImage(1);
                    setState(() {
                      imagen_to_upload = File(imagen[0]!.path);
                    });
                    Navigator.of(context).pop();
                  },
                ),
                const Divider(color: Colors.black54),
                GestureDetector(
                  child: const Text(
                    textAlign: TextAlign.center,
                    "Abrir Galería",
                    style: TextStyle(color: Color(0xFF2BA4EC)),
                  ),
                  onTap: () async {
                    final imagen = await getImage(2);
                    setState(() {
                      imagen_to_upload = File(imagen[0]!.path);
                    });
                    Navigator.of(context).pop();
                  },
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    String address = _direccion.toString();

    return Scaffold(
      appBar: PopAppbar(
          onPressed: () {
            Navigator.pop(context);
          },
          label: 'Perfil profesional'),
      body: SingleChildScrollView(
        reverse: true,
        child: Column(
          children: [
            GestureDetector(
              onTap: () {
                _showChoiceDialog(context);
              },
              child: Container(
                child: (imagen_to_upload != null)
                    ? LocalPhoto(
                        file: imagen_to_upload!,
                      )
                    : ReferenceBannerPhoto(
                        ref: storage.ref().child(_photo),
                      ),
              ),
            ),
            if (settings?.tarifas == true)
              const Divider(
                color: Colors.white,
                height: 12,
              ),
            if (settings?.tarifas == true)
              customSwitch(
                'Tarifa',
                tarifaValue,
                (value) {
                  tarifaValue = value;
                },
              ),
            tarifaValue
                ? Padding(
                    padding:
                        const EdgeInsets.only(left: 40, right: 40, bottom: 15),
                    child: Column(
                      children: [
                        TextFormField(
                          controller: _tarifaController,
                          keyboardType: TextInputType.number,
                          decoration: const InputDecoration(
                              prefixIcon: Icon(Icons.attach_money),
                              hintText: 'COP'),
                          inputFormatters: [
                            FilteringTextInputFormatter.digitsOnly,
                          ],
                        ),
                      ],
                    )
                        .animate()
                        .moveY(duration: const Duration(milliseconds: 100)),
                  )
                : const SizedBox(),
            if (settings?.domicilios == true)
              const Divider(
                color: Colors.white,
                height: 12,
              ),
            if (settings?.domicilios == true)
              customSwitch(
                'Servicio a domicilio',
                domicilioValue,
                (value) {
                  domicilioValue = value;
                },
              ),
            const Divider(),
            customSwitch(
              'Servicio en sitio',
              sitioValue,
              (value) {
                sitioValue = value;
              },
            ),
            sitioValue
                ? Padding(
                    padding:
                        const EdgeInsets.only(left: 40, right: 40, bottom: 15),
                    child: Column(
                      children: [
                        TextFormField(
                          readOnly: true,
                          onTap: () async {
                            final String? direccion = await Navigator.push(
                              context,
                              CupertinoPageRoute(
                                builder: (BuildContext context) {
                                  return const ProfessionalDireccionScreen();
                                },
                              ),
                            ) as String?;

                            if (direccion != null) {
                              setState(() {
                                _direccion = direccion;
                              });
                            }
                          },
                          decoration: InputDecoration(
                              prefixIcon: const Icon(Icons.near_me),
                              hintStyle: address == ''
                                  ? const TextStyle()
                                  : const TextStyle(color: Colors.black87),
                              hintText: address == '' ? 'Dirección' : address),
                        ),
                        const SizedBox(height: 10),
                        TextFormField(
                          controller: _opcionalAddressController,
                          decoration: const InputDecoration(
                              hintText: 'Oficina / Piso / Conjunto'),
                        ),
                      ],
                    )
                        .animate()
                        .moveY(duration: const Duration(milliseconds: 100)),
                  )
                : const SizedBox(),
            const Divider(),
            const Padding(
              padding: EdgeInsets.symmetric(horizontal: 30),
              child: SizedBox(
                width: double.infinity,
                child: Text(
                  'Horario estandar',
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 15,
                  ),
                ),
              ),
            ),
            GestureDetector(
              onTap: () {
                createSchedules();
              },
              child: Padding(
                padding: const EdgeInsets.symmetric(vertical: 10),
                child: Table(
                  defaultColumnWidth: const IntrinsicColumnWidth(),
                  children: [
                    TableRow(
                      children: [
                        TableCell(
                          child: Container(
                            padding: const EdgeInsets.all(8.0),
                            child: Text('Lunes'),
                          ),
                        ),
                        TableCell(
                          child: Container(
                            padding: const EdgeInsets.all(8.0),
                            child: Text(timeList(_horarios?['Lunes'], context)),
                          ),
                        ),
                      ],
                    ),
                    TableRow(
                      children: [
                        TableCell(
                          child: Container(
                            padding: const EdgeInsets.all(8.0),
                            child: const Text('Martes'),
                          ),
                        ),
                        TableCell(
                          child: Container(
                            padding: const EdgeInsets.all(8.0),
                            child:
                                Text(timeList(_horarios?['Martes'], context)),
                          ),
                        ),
                      ],
                    ),
                    TableRow(
                      children: [
                        TableCell(
                          child: Container(
                            padding: const EdgeInsets.all(8.0),
                            child: const Text('Miercoles'),
                          ),
                        ),
                        TableCell(
                          child: Container(
                            padding: const EdgeInsets.all(8.0),
                            child: Text(
                                timeList(_horarios?['Miercoles'], context)),
                          ),
                        ),
                      ],
                    ),
                    TableRow(
                      children: [
                        TableCell(
                          child: Container(
                            padding: const EdgeInsets.all(8.0),
                            child: const Text('Jueves'),
                          ),
                        ),
                        TableCell(
                          child: Container(
                            padding: const EdgeInsets.all(8.0),
                            child:
                                Text(timeList(_horarios?['Jueves'], context)),
                          ),
                        ),
                      ],
                    ),
                    TableRow(
                      children: [
                        TableCell(
                          child: Container(
                            padding: const EdgeInsets.all(8.0),
                            child: const Text('Viernes'),
                          ),
                        ),
                        TableCell(
                          child: Container(
                            padding: const EdgeInsets.all(8.0),
                            child:
                                Text(timeList(_horarios?['Viernes'], context)),
                          ),
                        ),
                      ],
                    ),
                    TableRow(
                      children: [
                        TableCell(
                          child: Container(
                            padding: const EdgeInsets.all(8.0),
                            child: const Text('Sabado'),
                          ),
                        ),
                        TableCell(
                          child: Container(
                            padding: const EdgeInsets.all(8.0),
                            child:
                                Text(timeList(_horarios?['Sabado'], context)),
                          ),
                        ),
                      ],
                    ),
                    TableRow(
                      children: [
                        TableCell(
                          child: Container(
                            padding: const EdgeInsets.all(8.0),
                            child: const Text('Domingo'),
                          ),
                        ),
                        TableCell(
                          child: Container(
                            padding: const EdgeInsets.all(8.0),
                            child:
                                Text(timeList(_horarios?['Domingo'], context)),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
            PrimaryButtom(
                onPressed: () {
                  updateInfo();
                  // name();
                },
                label: 'Guardar'),
            const SizedBox(
              height: 20,
            )
          ],
        ),
      ),
    );
  }

  customSwitch(String text, bool switchValue, ValueChanged<bool> onChanged) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 30),
      child: SizedBox(
        height: 40,
        child: Row(
          children: [
            Expanded(
                child: Text(
              text,
              style: const TextStyle(
                fontSize: 15,
                color: Colors.black,
              ),
            )),
            Transform.scale(
              scale: 1.2,
              child: Switch(
                value: switchValue,
                onChanged: (bool newValue) {
                  setState(() {
                    onChanged(newValue);
                  });
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  String timeList(Schedule? schedule, BuildContext context) {
    if (schedule == null) {
      return 'N/A';
    }
    if (!schedule.habilitado) {
      return 'N/A';
    }
    if (schedule.jornadaContinua) {
      return '${schedule.range1Hour1?.format(context).toString()} - ${schedule.range2Hour2?.format(context).toString()}';
    } else {
      return '${schedule.range1Hour1?.format(context).toString()} - ${schedule.range1Hour2?.format(context).toString()}; ${schedule.range2Hour1?.format(context).toString()} - ${schedule.range2Hour2?.format(context).toString()}';
    }
  }
}
