import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:prosapp_web_app/models/pro_state.dart';
import 'package:prosapp_web_app/models/usuario.dart';
import 'package:prosapp_web_app/services/api_service.dart';
import 'package:prosapp_web_app/services/notifications_service.dart';

class ProfileFormProvider extends ChangeNotifier {
  Usuario? user;
  GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final _api = ApiService.instance;

  void copyUserWith({
    String? id,
    String? email,
    String? phone,
    String? name,
    String? nickname,
    String? city,
    String? picture,
    String? birthday,
    String? gender,
    ProState? proState,
    String? token,
  }) {
    user = Usuario(
      id: id ?? user!.id,
      email: email ?? user!.email,
      phone: phone ?? user!.phone,
      name: name ?? user!.name,
      nickname: nickname ?? user!.nickname,
      city: city ?? user!.city,
      picture: picture ?? user!.picture,
      birthday: birthday ?? user!.birthday,
      gender: gender ?? user!.gender,
      proState: proState ?? user!.proState,
      token: token ?? user!.token,
    );
    notifyListeners();
  }

  bool _validForm() => formKey.currentState!.validate();

  Future<void> updateUserInfo() async {
    if (!_validForm()) return;
    await _api.patch('/users/me', user!.toDocument());
    NotificationsService.showSnackbar('Información actualizada');
  }

  Future<void> updateUserInfoNoValid() async {
    await _api.patch('/users/me', user!.toDocument());
    NotificationsService.showSnackbar('Información actualizada');
  }

  Future<Usuario> uploadPicture(Uint8List bytes) async {
    final url = await _api.upload(bytes, 'profile_${user!.id}.jpg');
    if (url != null) copyUserWith(picture: url);
    notifyListeners();
    return user!;
  }

  Future<void> signUpWithPhoneNumber(String phoneNumber) async {
    try {
      await _api.post('/auth/phone/link/send', {'phone': phoneNumber});
      NotificationsService.showSnackbar('Código enviado al número $phoneNumber');
    } catch (e) {
      NotificationsService.showSnackbar('Error al enviar código: $e');
    }
  }

  Future<bool> linkPhoneNumberToExistingAccount(String phoneNumber, String code) async {
    try {
      await _api.post('/auth/phone/link/verify', {'phone': phoneNumber, 'code': code});
      copyUserWith(phone: phoneNumber);
      notifyListeners();
      NotificationsService.showSnackbar('Número vinculado exitosamente');
      return true;
    } catch (e) {
      NotificationsService.showSnackbar('Código de verificación inválido');
      return false;
    }
  }
}
