import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hamlemuhcrm/core/constants/color_constants.dart';
import 'package:hamlemuhcrm/core/constants/url_services_constant.dart';
import 'package:hamlemuhcrm/core/extensions/responsive_extension.dart';
import 'package:hamlemuhcrm/core/extensions/string_extension.dart';
import 'package:hamlemuhcrm/features/auth/login/cubit/login_cubit.dart';
import 'package:hamlemuhcrm/features/calendar/constants/meet_constants.dart';
import 'package:hamlemuhcrm/features/calendar/cubit/suggestion_cubit.dart';
import 'package:hamlemuhcrm/features/calendar/view/approval_list_agenda_suggestion_view.dart';
import 'package:hamlemuhcrm/features/calendar/view/moderator_list_agenda_suggestion_view.dart';

import '../../../core/constants/app_constants.dart';
import '../model/calendar_model.dart';

final class MeetCardItem extends StatelessWidget {
  final CalendarModel toplantiListesi;
  final void Function()? onMeetUpdate;
  const MeetCardItem(
      {super.key, required this.toplantiListesi, this.onMeetUpdate});

  @override
  Widget build(BuildContext context) {
    String birincifoto = '';
    String ikincifoto = '';
    bool adminMi;
    List<String> resimListesi =
        toplantiListesi.toplantiUserImages!.split(',').toList();
    if (resimListesi.length > 1) {
      birincifoto = resimListesi[0].toString();
      ikincifoto = resimListesi[1].toString();
    } else if (resimListesi.isEmpty) {
      birincifoto = 'buresimyok.jpg';
      ikincifoto = 'buresimyok.jpg';
    }

    bool isAdminOrModerator(CalendarModel toplantiList) {
      int toplantiOlusturan =
          int.tryParse(toplantiList.toplantiUserId ?? '') ?? -1;
      int toplantiYonetici =
          int.tryParse(toplantiList.toplantiYoneticiId ?? '') ?? -1;
      int loginId = int.tryParse(context.read<LoginCubit>().id) ?? -1;
      bool adminMi =
          (toplantiOlusturan == loginId || toplantiYonetici == loginId);
      debugPrint('toplanti : ${toplantiList.toplantiId} + admin mi : $adminMi');
      return adminMi;
    }

    adminMi = isAdminOrModerator(toplantiListesi);
    return Container(
      height: context.dynamicHeight(0.12),
      width: context.dynamicWidth(1),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
              color: Colors.grey.shade200,
              offset: const Offset(1, 1),
              blurRadius: 2),
        ],
        borderRadius: const BorderRadius.only(
          bottomLeft: Radius.circular(10),
          bottomRight: Radius.circular(8),
          topLeft: Radius.circular(8),
          topRight: Radius.circular(8),
        ),
      ),
      alignment: Alignment.center,
      child: Row(
        children: [
          _cornerContainer(context),
          _emptyWidthSpace(context),
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                Row(
                  children: [
                    _circleAvatarsView(context, birincifoto, ikincifoto),
                    _emptyWidthSpace(context),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(toplantiAdiKucult(
                            toplantiListesi.toplantiBaslik ?? '')),
                        const SizedBox(height: 5),
                        Row(
                          children: [
                            Icon(
                              Icons.timelapse,
                              color: ColorsConstants.instance.iconColor,
                            ),
                            const SizedBox(width: 8),
                            Text(
                              ''.toTrTypeNoHour(
                                  toplantiListesi.toplantiTarihi ?? ''),
                              style: Theme.of(context).textTheme.bodySmall,
                            )
                          ],
                        )
                      ],
                    ),
                  ],
                ),
                Padding(
                  padding: const EdgeInsets.only(right: 15.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      _navigateSugButton(context, toplantiListesi, adminMi),
                      _navigateButtonEmptySpace(context),
                      adminMi
                          ? _navigateMeetUpdateButton(context, onMeetUpdate)
                          : const SizedBox.shrink(),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  String toplantiAdiKucult(String gelenToplanti) => gelenToplanti.length > 30
      ? '${gelenToplanti.substring(0, 29)}..'
      : gelenToplanti;
}

Widget _emptyWidthSpace(BuildContext context) {
  return SizedBox(
    width: context.dynamicWidth(0.03),
  );
}

Widget _cornerContainer(BuildContext context) {
  Color renk = Color((Random().nextDouble() * 0xFFFFFF).toInt()).withOpacity(1);
  return Container(
    height: context.dynamicHeight(0.13),
    width: ApplicationConstants.instance.kEdgeStartContainerWidthMax,
    decoration: BoxDecoration(
        color: renk,
        borderRadius: const BorderRadius.only(
            bottomLeft: Radius.circular(20), topLeft: Radius.circular(20))),
  );
}

Widget _navigateButtonTheme(Widget child) => Container(
    decoration: ShapeDecoration(
      color: const Color(0xFFD6D2D1),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5)),
    ),
    child: child);

Widget _navigateButtonEmptySpace(BuildContext context) =>
    SizedBox(width: context.dynamicWidth(0.05));
Widget _navigateSugButton(
        BuildContext context, CalendarModel calendarModel, bool adminMi) =>
    InkWell(
      onTap: () {
        _isCheckProcess(context, calendarModel, adminMi);
      },
      child: _navigateButtonTheme(
        Center(
          heightFactor: 1.5,
          widthFactor: 1.2,
          child: FittedBox(
            child: Text(
                adminMi
                    ? MeetConstants.instance.confirmSuggestionNavigateButtonTxt
                    : MeetConstants.instance.addSuggestionNavigateButtonTxt,
                style: Theme.of(context)
                    .textTheme
                    .bodySmall
                    ?.copyWith(fontWeight: FontWeight.w600)),
          ),
        ),
      ),
    );

void _isCheckProcess(
    BuildContext context, CalendarModel calendarModel, bool value) {
  // onaylanan gundem onerileri için 1, bekleyen gündem istekleri için 0
  if (value) {
    context
        .read<SuggestionCubit>()
        .fetchWaitingSuggestions(context.read<LoginCubit>().token,
            context.read<LoginCubit>().id, calendarModel.toplantiId ?? '0')
        .whenComplete(() => Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => ModeratorListAgendaSuggestionView(
                    toplantiAd: calendarModel.toplantiBaslik ?? '',
                    toplantiID: calendarModel.toplantiId ?? '0'))));
  } else {
    context.read<SuggestionCubit>().fetchWaitingSuggestions(
        context.read<LoginCubit>().token,
        context.read<LoginCubit>().id,
        gundemDurumu: "0",
        calendarModel.toplantiId ?? '0');

    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => ApprovalListAgendaSuggestionView(
                toplantiAd: calendarModel.toplantiBaslik ?? '',
                toplantiID: calendarModel.toplantiId ?? '0')));
  }
}

Widget _navigateMeetUpdateButton(
        BuildContext context, void Function()? onPressed) =>
    InkWell(
      onTap: onPressed,
      child: _navigateButtonTheme(
        Center(
          heightFactor: 1.5,
          widthFactor: 1.5,
          child: FittedBox(
            child: Text(MeetConstants.instance.updateMeetNavigateButtonTxt,
                style: Theme.of(context)
                    .textTheme
                    .bodySmall
                    ?.copyWith(fontWeight: FontWeight.w600)),
          ),
        ),
      ),
    );

Widget _circleAvatarsView(
    BuildContext context, String birinciResim, String ikinciResim) {
  return SizedBox(
    width: context.dynamicWidth(0.2),
    child: Stack(
      alignment: Alignment.centerLeft,
      children: [
        CircleAvatar(
          radius: 20,
          child: CachedNetworkImage(
            height: context.dynamicHeight(0.08),
            fit: BoxFit.fill,
            imageUrl: _imageCheck(birinciResim),
            placeholder: (context, url) => CircleAvatar(
              radius: 30,
              backgroundColor: Colors.grey.shade200,
            ),
            imageBuilder: (context, imageProvider) {
              return CircleAvatar(
                radius: 32,
                backgroundColor: Colors.grey,
                child: CircleAvatar(
                  radius: 30,
                  backgroundImage: imageProvider,
                ),
              );
            },
          ),
        ),
        Positioned(
          left: 15,
          child: CircleAvatar(
            radius: 22,
            backgroundColor: Colors.white,
            child: CachedNetworkImage(
              height: context.dynamicHeight(0.08),
              fit: BoxFit.fill,
              imageUrl: _imageCheck(ikinciResim),
              placeholder: (context, url) => CircleAvatar(
                radius: 30,
                backgroundColor: Colors.grey.shade200,
              ),
              imageBuilder: (context, imageProvider) {
                return CircleAvatar(
                  radius: 32,
                  backgroundColor: Colors.grey,
                  child: CircleAvatar(
                    radius: 30,
                    backgroundImage: imageProvider,
                  ),
                );
              },
            ),
          ),
        ),
      ],
    ),
  );
}

String _imageCheck(String? kullaniciImage) {
  if (kullaniciImage != null && kullaniciImage != "") {
    return '${URLAPIService.instance.fileBaseURL}/upload-user/$kullaniciImage}';
  }

  return URLAPIService.instance.defaultPhotoUrl;
}
