import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../core/constants/color_constants.dart';
import '../../../core/constants/url_services_constant.dart';
import '../../../core/extensions/responsive_extension.dart';
import '../../../core/extensions/string_extension.dart';
import '../../auth/login/cubit/login_cubit.dart';
import '../model/group_latest_message.dart';

class LatestMessageBox extends StatelessWidget {
  final GroupLatestMessage model;
  final void Function()? onpressed;

  const LatestMessageBox({
    Key? key,
    required this.model,
    this.onpressed,
  }) : super(key: key);

  // Mesajlar ana sayfada her bir sohbet grubu için gösterilen component

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onpressed,
      child: Material(
        type: MaterialType.button,
        color: Colors.transparent,
        child: Container(
          margin: const EdgeInsets.symmetric(horizontal: 5),
          height: context.dynamicHeight(0.1),
          width: context.dynamicWidth(1),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(5),
              color: (model.kullaniciGonderenKulId !=
                          context.read<LoginCubit>().id &&
                      model.kullaniciMesajGoruldu == "0")
                  ? Colors.grey.shade200
                  : Colors.transparent),
          child: ListTile(
            leading: _avatar(context, model),
            title: Text(model.grupAdi ?? "",
                style: Theme.of(context).textTheme.labelLarge),
            subtitle: Text(
              checkIsFile(model.sonmesaj ?? "", model.sonmesajdosyalar ?? ""),
              style: Theme.of(context)
                  .textTheme
                  .labelMedium
                  ?.copyWith(color: Colors.black54),
            ),
            trailing: isViewIcon(context, model),
          ),
        ),
      ),
    );
  }
}

String checkIsFile(String message, String file) {
  if (message.isEmpty || message == ' ') {
    if (file.contains("hdosyaadurlh")) {
      return ''.extractFileName(file);
    } else {
      return _checkLastMessageTxt(message);
    }
  }
  {
    return _checkLastMessageTxt(message);
  }
}

Widget _avatar(BuildContext context, GroupLatestMessage model) =>
    CachedNetworkImage(
      height: context.dynamicHeight(0.08),
      fit: BoxFit.fill,
      imageUrl: _groupImageCheck(model),
      placeholder: (context, url) => CircleAvatar(
        radius: 32,
        backgroundColor: Colors.grey,
        child: CircleAvatar(
          radius: 30,
          backgroundColor: Colors.grey.shade200,
        ),
      ),
      imageBuilder: (context, imageProvider) {
        return CircleAvatar(
          radius: 32,
          backgroundColor: Colors.grey,
          child: CircleAvatar(
            radius: 30,
            backgroundImage: imageProvider,
          ),
        );
      },
    );

String _checkLastMessageTxt(String lastMessage) {
  if (lastMessage.length < 50) return lastMessage;
  return '${lastMessage.substring(0, 49)}..';
}

String _groupImageCheck(GroupLatestMessage model) {
  if (model.grupKullaniciSayisi != null && model.grupKullaniciSayisi! > 2) {
    return (model.kullaniciImage == null || model.kullaniciImage == "")
        ? URLAPIService.instance.defaultPhotoUrl
        : URLAPIService.instance.defaultPhotoUrl;
  }
  return (model.kullaniciImage == null || model.kullaniciImage == "")
      ? URLAPIService.instance.defaultPhotoUrl
      : '${URLAPIService.instance.photoBaseURL}${model.kullaniciImage}';
}

Widget isViewIcon(BuildContext context, GroupLatestMessage model) {
  // son mesajı atan ben isem ve karşı taraf mesajı gördüyse
  if (model.kullaniciMesajGoruldu == "1" &&
      model.kullaniciGonderenKulId == context.read<LoginCubit>().id) {
    return Icon(
      Icons.done_all,
      color: ColorsConstants.instance.baseTheme,
      size: 15,
    );
    // son mesajı atan ben isem ve karşı taraf mesajı görmediyse
  } else if (model.kullaniciMesajGoruldu == "0" &&
      model.kullaniciGonderenKulId == context.read<LoginCubit>().id) {
    return const Icon(
      Icons.done,
      color: Colors.grey,
      size: 15,
    );
    // son mesajı atan karşı taraf ise ve mesajı görmediysem
  } else if (model.kullaniciGonderenKulId != context.read<LoginCubit>().id &&
      model.kullaniciMesajGoruldu == "0") {
    return Badge(
      backgroundColor: ColorsConstants.instance.baseTheme,
      isLabelVisible: true,
    );
  } else if (model.kullaniciGonderenKulId != context.read<LoginCubit>().id &&
      model.kullaniciMesajGoruldu == "1") {
    // son mesajı atan karşı taraf ise ve mesajı gördüysem
    return Text(
      model.sonmesajtarihi?.formattedHourMinutes ?? "--.--",
      style: Theme.of(context).textTheme.bodySmall,
    );
  }
  // Henüz sohbet başlatılmadıysa bu ikon gösterilsin
  return const Icon(
    Icons.shortcut,
    size: 10,
  );
}
