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/extensions/responsive_extension.dart';
import 'package:hamlemuhcrm/core/route/page_route.dart';
import 'package:hamlemuhcrm/features/auth/login/cubit/login_cubit.dart';
import 'package:percent_indicator/percent_indicator.dart';

import '../../../core/constants/url_services_constant.dart';
import '../model/projeler.dart';
import '../view/projects_partial/project_detail_page.dart';
import '../view/projects_partial/project_update_page.dart';

final class ProjectCard extends StatefulWidget {
  final Projeler model;
  final void Function()? onTap;

  const ProjectCard({super.key, required this.model, required this.onTap});

  @override
  State<ProjectCard> createState() => _ProjectCardState();
}

class _ProjectCardState extends State<ProjectCard> {
  String? birinciResim;
  String? ikinciResim;
  bool isFinish = false;
  late final Color renk;

  Color _settingCard() {
    List<String> resimListesi =
        widget.model.projeSorumluImages!.split(',').toList();
    for (var k in resimListesi) {
      if (k.isEmpty) {
        k = 'buresimyok.jpg';
      }
    }

    if (resimListesi.isNotEmpty && resimListesi.length > 1) {
      birinciResim = resimListesi[0].toString();
      ikinciResim = resimListesi[1].toString();
    } else if (resimListesi.isEmpty) {
      birinciResim = 'buresimyok.jpg';
      ikinciResim = 'buresimyok.jpg';
    }

    Color random =
        Color((Random().nextDouble() * 0xFFFFFF).toInt()).withOpacity(1);
    return random;
  }

  @override
  void initState() {
    isFinish = false;
    renk = _settingCard();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      setState(() {
        isFinish = true;
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return isFinish
        ? LayoutBuilder(
            builder: (context, constraints) => Container(
              height: context.dynamicHeight(0.080),
              margin: const EdgeInsets.symmetric(horizontal: 15, vertical: 8),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(5),
                  color: Colors.white,
                  boxShadow: [
                    BoxShadow(
                        color: Colors.grey.withOpacity(0.5),
                        blurRadius: 4,
                        offset: const Offset(1, 1))
                  ]),
              child: Row(
                children: [
                  InkWell(
                    onTap: widget.onTap,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            const SizedBox(width: 8),
                            Icon(
                              Icons.task_alt_outlined,
                              color: renk,
                              size: context.dynamicWidth(0.042),
                            ),
                            SizedBox(width: context.dynamicWidth(0.025)),
                            Text(
                              widget.model.projeAd!.length > 27
                                  ? "${widget.model.projeAd!.substring(0, 26)}..."
                                  : widget.model.projeAd!,
                              style: const TextStyle(fontSize: 12),
                            ),
                          ],
                        ),
                        LinearPercentIndicator(
                          width: context.dynamicWidth(0.5),
                          lineHeight: 7,
                          percent: 0.4,
                          barRadius: const Radius.circular(15),
                          progressColor: renk,
                          backgroundColor: Colors.grey.shade200,
                        ),
                      ],
                    ),
                  ),
                  const Spacer(),
                  _circleAvatarsListView(
                      context,
                      birinciResim ?? 'buresimyok.jpg',
                      ikinciResim ?? 'buresimyok.jpg',
                      URLAPIService.instance.defaultPhotoUrl),
                  IconButton(
                    onPressed: () {
                      // Kullanıcı projeyi ekleyen kişi ise update page yönlendir değil ise detayları gösterme sayfasına yönlendir
                      if (widget.model.projeVerenUserId ==
                          context.read<LoginCubit>().id) {
                        return _navigateToUpdateProject(context, widget.model);
                      }
                      _navigateToDetailProject(context, widget.model);
                    },
                    icon: const Icon(
                      Icons.more_vert,
                      color: Colors.grey,
                    ),
                  ),
                ],
              ),
            ),
          )
        : const SizedBox.shrink();
  }
}

void _navigateToUpdateProject(BuildContext context, Projeler model) {
  Navigator.push(
      context, CustomPageRoute(child: ProjectUpdatePage(projeler: model)));
}

void _navigateToDetailProject(BuildContext context, Projeler model) {
  Navigator.push(
      context, CustomPageRoute(child: ProjectDetailPage(projeler: model)));
}

Widget _circleAvatarsListView(BuildContext context, String birinciResim,
    String ikinciResim, String notFoundImage) {
  return SizedBox(
    width: context.dynamicWidth(0.18),
    child: Stack(
      alignment: Alignment.centerLeft,
      children: [
        CircleAvatar(
          radius: 22,
          backgroundColor: Colors.grey.shade400,
          child: CachedNetworkImage(
            imageUrl: _imageCheck(birinciResim),
            imageBuilder: (context, imageProvider) => Container(
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                image: DecorationImage(image: imageProvider, fit: BoxFit.cover),
              ),
            ),
            errorWidget: (context, url, error) => Icon(
              Icons.image_not_supported_outlined,
              color: ColorsConstants.instance.containerBorderGreyColor,
            ),
          ),
        ),
        Positioned(
          left: 15,
          child: CircleAvatar(
            radius: 22,
            backgroundColor: Colors.white,
            child: CachedNetworkImage(
              imageUrl: _imageCheck(ikinciResim),
              imageBuilder: (context, imageProvider) => Container(
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  image:
                      DecorationImage(image: imageProvider, fit: BoxFit.cover),
                ),
              ),
              errorWidget: (context, url, error) => Icon(
                Icons.image_not_supported_outlined,
                color: ColorsConstants.instance.containerBorderGreyColor,
              ),
            ),
          ),
        ),
      ],
    ),
  );
}

String _imageCheck(String? imagePath) {
  if (imagePath == null) return URLAPIService.instance.defaultPhotoUrl;

  if (imagePath.isNotEmpty) {
    return '${URLAPIService.instance.fileBaseURL}/upload-user/$imagePath';
  }

  return URLAPIService.instance.defaultPhotoUrl;
}
