import 'package:business_panel/core/config/app_colors.dart';
import 'package:business_panel/domain/entities/discount_entity.dart';
import 'package:business_panel/gen/assets.gen.dart';
import 'package:business_panel/presentation/home/bloc/home_bloc.dart';
import 'package:business_panel/presentation/pages/add_discount_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/svg.dart';
import 'package:intl/intl.dart' show NumberFormat;
import 'package:slide_countdown/slide_countdown.dart';

class DiscountCard extends StatelessWidget {
  final DiscountEntity discount;

  const DiscountCard({super.key, required this.discount});

  @override
  Widget build(BuildContext context) {
    final remaining =
        discount.endDate != null ? discount.endDate!.difference(DateTime.now()) : const Duration(seconds: -1);

    final int discountPercentage = (discount.price > 0 && discount.price > discount.nPrice)
        ? (((discount.price - discount.nPrice) / discount.price) * 100).toInt()
        : 0;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 8.0),
              child: Text(
                "تخفیف ${discount.type}",
                style: const TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: Colors.black,
                ),
              ),
            ),
            InkWell(
              onTap: () {
                Navigator.of(context)
                    .push(
                      MaterialPageRoute(
                        builder: (_) => AddDiscountPage(discountId: discount.id),
                      ),
                    )
                    .then((value) {
                  if (value == true) {
                    context.read<HomeBloc>().add(FetchDiscounts());
                  }
                });
              },
              borderRadius: BorderRadius.circular(8),
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Row(
                  children: [
                    SvgPicture.asset(
                      Assets.icons.edit,
                      width: 20,
                      color: AppColors.active,
                    ),
                    const SizedBox(width: 5),
                    const Text(
                      "ویرایش",
                      style: TextStyle(color: AppColors.active),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
        const Divider(height: 1),
        const SizedBox(height: 10),
        Card(
          color: Colors.white,
          elevation: 0,
          margin: const EdgeInsets.only(bottom: 16),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(25),
            side: BorderSide(color: Colors.grey.shade300, width: 1),
          ),
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                if (discount.images.isNotEmpty && discount.images.first.isNotEmpty)
                  ClipRRect(
                    borderRadius: BorderRadius.circular(15),
                    child: Image.network(
                      discount.images.first,
                      width: 100,
                      height: 100,
                      fit: BoxFit.cover,
                      errorBuilder: (context, error, stackTrace) => Container(
                        width: 100,
                        height: 100,
                        decoration: BoxDecoration(
                          color: Colors.grey[200],
                          borderRadius: BorderRadius.circular(15),
                        ),
                        child: const Icon(
                          Icons.image_not_supported,
                          color: Colors.grey,
                        ),
                      ),
                    ),
                  )
                else
                  Container(
                    width: 100,
                    height: 100,
                    decoration: BoxDecoration(
                      color: Colors.grey[200],
                      borderRadius: BorderRadius.circular(15),
                    ),
                    child: const Icon(
                      Icons.store,
                      color: Colors.grey,
                      size: 50,
                    ),
                  ),
                const SizedBox(width: 16),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          SvgPicture.asset(
                            Assets.icons.shop,
                            width: 18,
                            color: Colors.grey.shade700,
                          ),
                          const SizedBox(width: 10),
                          Expanded(
                            child: Text(
                              discount.shopName,
                              style: const TextStyle(fontSize: 16),
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 8),
                      Row(
                        children: [
                          SvgPicture.asset(
                            Assets.icons.shoppingCart,
                            width: 18,
                            color: Colors.grey.shade700,
                          ),
                          const SizedBox(width: 10),
                          Expanded(
                            child: Text(
                              discount.name,
                              style: TextStyle(
                                fontSize: 15,
                                color: Colors.grey.shade600,
                              ),
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 12),
                      if (discount.endDate == null)
                        const Text(
                          'تاریخ نامعتبر',
                          style: TextStyle(
                            color: Colors.orange,
                            fontWeight: FontWeight.bold,
                          ),
                        )
                      else if (remaining.isNegative)
                        const Text(
                          'منقضی شده',
                          style: TextStyle(
                            color: AppColors.expiryReserve,
                            fontWeight: FontWeight.bold,
                          ),
                        )
                      else
                        Row(
                          children: [
                            SvgPicture.asset(
                              Assets.icons.timerPause,
                              width: 18,
                              color: Colors.grey.shade700,
                            ),
                            const SizedBox(width: 10),
                            Expanded(child: _buildCountdownTimer(remaining)),
                          ],
                        ),
                      const SizedBox(height: 16),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                "${NumberFormat('#,##0').format(discount.nPrice)} تومان",
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.normal,
                  color: Colors.red,
                ),
              ),
              const SizedBox(width: 8),
              if (discountPercentage > 0)
                Text(
                  '($discountPercentage%)',
                  style: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.normal,
                    color: Colors.red,
                  ),
                ),
              const SizedBox(width: 4),
              Text(
                NumberFormat('#,##0').format(discount.price),
                style: const TextStyle(
                  fontSize: 14,
                  color: Color.fromARGB(255, 124, 124, 124),
                  decoration: TextDecoration.lineThrough,
                ),
              ),
              const SizedBox(width: 4),
              SvgPicture.asset(Assets.icons.cardPos),
            ],
          ),
        ),
        const SizedBox(height: 4),
      ],
    );
  }

  Widget _buildCountdownTimer(Duration remaining) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Directionality(
          textDirection: TextDirection.ltr,
          child: SlideCountdown(
            duration: remaining,
            slideDirection: SlideDirection.up,
            separator: ':',
            style: const TextStyle(
              fontSize: 15,
              fontWeight: FontWeight.bold,
              color: AppColors.countdown,
            ),
            separatorStyle: const TextStyle(
              fontSize: 15,
              color: AppColors.countdown,
            ),
            decoration: const BoxDecoration(color: Colors.transparent),
            shouldShowDays: (d) => d.inDays > 0,
            shouldShowHours: (d) => true,
            shouldShowMinutes: (d) => true,
          ),
        ),
        const SizedBox(height: 4),
        _buildTimerLabels(remaining),
      ],
    );
  }

  Widget _buildTimerLabels(Duration duration) {
    const labelStyle = TextStyle(fontSize: 9, color: AppColors.selectedImg);
    List<Widget> labels = [];
    if (duration.inDays > 0) {
      labels.add(const SizedBox(width: 30, child: Text("روز", style: labelStyle)));
    }
    if (duration.inHours > 0 || duration.inDays > 0) {
      labels.add(const SizedBox(width: 35, child: Text("ساعت", style: labelStyle)));
    }
    labels.add(const SizedBox(width: 35, child: Text("دقیقه", style: labelStyle)));
    labels.add(const SizedBox(width: 35, child: Text("  ثانیه", style: labelStyle)));
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: labels.reversed.toList(),
    );
  }
}