import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';

const double photoSize = 100;
const double iconSize = 55;

class ReferencePhotoWeb extends StatelessWidget {
  Reference? ref;
  double size;
  double sizeIcon;
  double sizeCircle;

  ReferencePhotoWeb({
    super.key,
    required this.ref,
    this.sizeIcon = iconSize,
    this.size = photoSize,
    this.sizeCircle = photoSize,
  });

  Future<Widget> downloadImage() async {
    try {
      if (ref != null) {
        final imageData = await ref!.getData();
        if (imageData != null) {
          return ClipOval(
            child: Image.memory(
              imageData,
              width: size,
              height: size,
              fit: BoxFit.cover,
            ),
          );
        }
      }
      // ignore: empty_catches
    } catch (e) {}

    return DefaultPhotoWeb(
      sizeDefault: sizeCircle,
      iconDefault: sizeIcon,
    );
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<Widget>(
        future: downloadImage(),
        builder: (BuildContext context, AsyncSnapshot<Widget> snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            // mientras la llamada asíncrona está en proceso, muestra un mensaje de carga
            return SizedBox(
              width: size,
              height: size,
              child: const Center(
                child: CircularProgressIndicator(),
              ),
            );
          } else if (snapshot.connectionState == ConnectionState.done &&
              snapshot.hasData) {
            return snapshot.data!;
          } else {
            return DefaultPhotoWeb();
          }
        });
  }
}

class DefaultPhotoWeb extends StatelessWidget {
  double sizeDefault;
  double iconDefault;

  DefaultPhotoWeb({
    super.key,
    this.sizeDefault = photoSize,
    this.iconDefault = iconSize,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      width: sizeDefault,
      height: sizeDefault,
      decoration: BoxDecoration(
        color: const Color(0xFF2BA4EC),
        borderRadius: BorderRadius.circular(50),
      ),
      child: Icon(
        Icons.person,
        color: const Color.fromARGB(255, 255, 255, 255),
        size: iconDefault,
      ),
    ).animate().shake();
  }
}

class LocalPhotoWeb extends StatelessWidget {
  Uint8List? file;
  LocalPhotoWeb({super.key, required this.file});

  @override
  Widget build(BuildContext context) {
    if (file == null) {
      return DefaultPhotoWeb();
    } else {
      return ClipOval(
        child: Image.memory(
          file!,
          width: photoSize,
          height: photoSize,
          fit: BoxFit.cover,
        ),
      );
    }
  }
}
