import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:shimmer/shimmer.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../constants/asset_constants.dart';
import '../../constants/color_constants.dart';
import '../../constants/font_constants.dart';
import '../../controllers/tenant/get_tenant.dart'; // OrderedTenantController
import '../../features/orders/presentation/order_tracking.dart';
import '../../widgets/text_widget.dart';
import 'my_orders.dart'; // OrderDatum

class OrdersByStoreScreen extends StatefulWidget {
  final bool showBackArrow;

  const OrdersByStoreScreen({super.key, required this.showBackArrow});

  @override
  _OrdersByStoreScreenState createState() => _OrdersByStoreScreenState();
}

class _OrdersByStoreScreenState extends State<OrdersByStoreScreen>
    with SingleTickerProviderStateMixin {
  final OrderedTenantController tenantController =
  Get.put(OrderedTenantController());
  final ScrollController _scrollController = ScrollController();
  static const Color primaryColor = Color(0xFF662582);

  int? _expandedIndex; // ✅ track which tile is expanded
  late AnimationController _fabAnimationController;
  late Animation<double> _fabAnimation;

  final List<String> emojis = ['😡', '😕', '😐', '😊', '😍'];


  Color _getStatusColor(String? status) {
    final cleanStatus = status?.trim().toLowerCase() ?? '';
    switch (cleanStatus) {
      case 'created':
        return Colors.blue;
      case 'pending':
        return Colors.orange;
      case 'cancelled':
        return Colors.red;
      case 'completed':
        return Colors.green;
      default:
        return Colors.grey;
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    tenantController
        .refreshOrders(); // ✅ auto refresh every time this screen rebuilds
  }

  @override
  void initState() {
    super.initState();

    // Initialize FAB animation
    _fabAnimationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 300),
    );
    _fabAnimation = CurvedAnimation(
      parent: _fabAnimationController,
      curve: Curves.easeInOut,
    );

    // Load initial orders
    tenantController.loadOrders();

    // Listen for scroll to bottom
    _scrollController.addListener(() {
      // FAB animation based on scroll
      if (_scrollController.offset > 100) {
        _fabAnimationController.forward();
      } else {
        _fabAnimationController.reverse();
      }

      if (_scrollController.position.pixels >=
          _scrollController.position.maxScrollExtent - 200 && // near bottom
          !tenantController.isLoading.value) {
        tenantController.pageNo++; // increment page
        tenantController.loadOrders();
      }
    });
  }

  @override
  void dispose() {
    _scrollController.dispose();
    _fabAnimationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      top: false,
      child: Scaffold(
        backgroundColor: Colors.grey[50],
        body: CustomScrollView(
          controller: _scrollController,
          physics: const BouncingScrollPhysics(), // ✨ Smooth bouncing scroll
          slivers: [
            SliverAppBar(
              backgroundColor: Colors.white,
              surfaceTintColor: Colors.transparent,
              // 🔥 Prevent color overlay when scrolled
              scrolledUnderElevation: 0,

              floating: false,
              pinned: true,

              // 👈 use widget.showBackArrow
              automaticallyImplyLeading: widget.showBackArrow,

              leading: widget.showBackArrow
                  ? IconButton(
                icon: const Icon(Icons.arrow_back, color: Colors.black),
                onPressed: () => Navigator.pop(context),
                splashRadius: 24, // ✨ Better ripple effect
              )
                  : null,

              title: const Text(
                'Orders',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: Colors.black,
                ),
              ),
              // titleSpacing: -5,

              centerTitle: false,
              elevation: 0,
            ),

            const SliverToBoxAdapter(child: SizedBox(height: 8)),
            Obx(() {
              if (tenantController.isLoading.value &&
                  tenantController.orders.isEmpty) {
                // Initial loading
                return SliverFillRemaining(
                  hasScrollBody: false,
                  child: shimmerListView(),
                );
              }

              if (tenantController.orders.isEmpty) {
                final screenSize = MediaQuery.of(context).size;
                return SliverToBoxAdapter(
                  child: emptyOrdersWidget(screenSize),
                );
              }

              return SliverList(
                delegate: SliverChildBuilderDelegate(
                      (context, index) {
                    if (index == tenantController.orders.length) {
                      // Loader at bottom
                      return tenantController.isLoading.value
                          ? const Padding(
                        padding: EdgeInsets.symmetric(vertical: 16),
                        child: Center(child: CircularProgressIndicator()),
                      )
                          : const SizedBox.shrink();
                    }

                    final order = tenantController.orders[index];
                    final tenantName = order.tenantname ?? 'Unknown Tenant';
                    double totalAmount = 0.0;
                    if (order.orderdetails != null &&
                        order.orderdetails!.isNotEmpty) {
                      totalAmount = order.orderdetails!
                          .map((item) => item.productsumprice ?? 0.0)
                          .reduce((a, b) => a + b);
                    }

                    // ✨ Staggered fade-in animation for each item
                    return TweenAnimationBuilder<double>(
                      tween: Tween(begin: 0.0, end: 1.0),
                      duration: Duration(milliseconds: 300 + (index * 50)),
                      curve: Curves.easeOutCubic,
                      builder: (context, value, child) {
                        return Transform.translate(
                          offset: Offset(0, 20 * (1 - value)),
                          child: Opacity(
                            opacity: value,
                            child: child,
                          ),
                        );
                      },
                      child: Builder(builder: (tileContext) {
                        return Container(
                          margin: const EdgeInsets.symmetric(
                              vertical: 4, horizontal: 8),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            border: Border.all(color: Colors.black12, width: 0.45),
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Theme(
                            data: Theme.of(context)
                                .copyWith(dividerColor: Colors.transparent),
                            child: ExpansionTile(
                              key: ValueKey(
                                  '${order.orderid}-${_expandedIndex == index}'),
                              //initiallyExpanded: _expandedIndex == index,
                              initiallyExpanded: _expandedIndex == index,
                              title: ReusableTextWidget(
                                text: tenantName,
                                color: primaryColor,
                                fontWeight: FontWeight.bold,
                                fontSize: 15,
                                fontFamily: FontConstants.fontFamily,
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                              trailing: Container(
                                padding: const EdgeInsets.symmetric(
                                    horizontal: 6, vertical: 2),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(6),
                                ),
                                child: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    // ● Circle dot
                                    Container(
                                      width: 6,
                                      height: 6,
                                      decoration: BoxDecoration(
                                        color: _getStatusColor(order.orderstatus),
                                        shape: BoxShape.circle,
                                      ),
                                    ),
                                    const SizedBox(width: 4),
                                    Text(
                                      (order.orderstatus ?? 'Pending')
                                          .capitalizeFirst!,
                                      style: const TextStyle(
                                        color: Colors.black,
                                        fontSize: 10,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              subtitle: Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  const Icon(Icons.location_on,
                                      size: 13, color: Colors.grey),
                                  const SizedBox(width: 2),
                                  ReusableTextWidget(
                                    text: order.tenantsuburb ?? 'Unknown Location',
                                    color: Colors.grey[700]!,
                                    fontWeight: FontWeight.w400,
                                    fontSize: 10,
                                    fontFamily: FontConstants.fontFamily,
                                  ),
                                ],
                              ),
                              leading: Container(
                                height: 50,
                                width: 50,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(8),
                                  color: Colors.grey[200],
                                ),
                                child: (order.tenantimage != null &&
                                    order.tenantimage!.isNotEmpty)
                                    ? ClipRRect(
                                  borderRadius: BorderRadius.circular(8),
                                  child: Image.network(
                                    order.tenantimage!,
                                    fit: BoxFit.cover,
                                    errorBuilder:
                                        (context, error, stackTrace) {
                                      return Icon(Icons.store,
                                          size: 28,
                                          color: Colors.grey[700]);
                                    },
                                  ),
                                )
                                    : Icon(Icons.store,
                                    size: 28, color: Colors.grey[700]),
                              ),
                              // ✅ this callback runs when the tile is expanded or collapsed
                              onExpansionChanged: (expanded) {
                                setState(() {
                                  _expandedIndex = expanded ? index : null;
                                });

                                if (expanded) {
                                  // ✨ Haptic feedback
                                  HapticFeedback.selectionClick();

                                  // ✨ Smooth scroll to expanded item
                                  Future.delayed(const Duration(milliseconds: 200),
                                          () {
                                        Scrollable.ensureVisible(
                                          tileContext,
                                          duration: const Duration(milliseconds: 500),
                                          curve: Curves.easeInOut,
                                          alignment: 0.1,
                                        );
                                      });
                                }
                              },
                              children: [
                                // ✨ Animated container for smooth expansion
                                AnimatedContainer(
                                  duration: const Duration(milliseconds: 300),
                                  curve: Curves.easeInOut,
                                  child: Padding(
                                    padding: const EdgeInsets.only(top: 0, bottom: 8),
                                    child: Column(
                                      children: [
                                        GestureDetector(
                                          onTap: () {},
                                          child: Container(
                                            height: 180,
                                            width: double.infinity,
                                            margin: const EdgeInsets.symmetric(
                                                vertical: 6, horizontal: 12),
                                            padding: const EdgeInsets.all(12),
                                            decoration: BoxDecoration(
                                              color: Colors.white,
                                              borderRadius:
                                              BorderRadius.circular(9),
                                              border: Border.all(
                                                  color: Colors.black12,
                                                  width: 0.20),
                                              boxShadow: [
                                                BoxShadow(
                                                  color: Colors.black
                                                      .withOpacity(0.04),
                                                  blurRadius: 4,
                                                  offset: const Offset(0, 1),
                                                ),
                                              ],
                                            ),
                                            child: Column(
                                              crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                              children: [
                                                Row(
                                                  mainAxisAlignment:
                                                  MainAxisAlignment
                                                      .spaceBetween,
                                                  children: [
                                                    ReusableTextWidget(
                                                      text:
                                                      "Order ID: ${order.orderid ?? 'Unknown'}",
                                                      color: ColorConstants
                                                          .blackColor
                                                          .withOpacity(0.87),
                                                      fontWeight: FontWeight.w600,
                                                      fontSize: 14,
                                                      fontFamily: FontConstants
                                                          .fontFamily,
                                                    ),
                                                    Container(
                                                      padding:
                                                      const EdgeInsets
                                                          .symmetric(
                                                          horizontal: 8,
                                                          vertical: 4),
                                                      decoration: BoxDecoration(
                                                        color: Colors.purple
                                                            .withOpacity(0.2),
                                                        borderRadius:
                                                        BorderRadius.circular(
                                                            12),
                                                      ),
                                                      child: ReusableTextWidget(
                                                        text:
                                                        "${order.orderdetails?.fold<int>(0, (sum, item) => sum + (item.orderqty ?? 0)) ?? 0}",
                                                        color: primaryColor,
                                                        fontWeight:
                                                        FontWeight.bold,
                                                        fontSize: 12,
                                                        fontFamily: FontConstants
                                                            .fontFamily,
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                                const SizedBox(height: 6),
                                                Row(
                                                  children: [
                                                    ReusableTextWidget(
                                                      text: "Total Amount: ",
                                                      color: ColorConstants
                                                          .blackColor
                                                          .withOpacity(0.65),
                                                      fontWeight: FontWeight.w600,
                                                      fontSize: 12,
                                                      fontFamily: FontConstants
                                                          .fontFamily,
                                                    ),
                                                    ReusableTextWidget(
                                                      text:
                                                      "₹${totalAmount.toStringAsFixed(2)}",
                                                      color: ColorConstants
                                                          .blackColor
                                                          .withOpacity(0.67),
                                                      fontWeight: FontWeight.w600,
                                                      fontSize: 13,
                                                      fontFamily: FontConstants
                                                          .fontFamily,
                                                    ),
                                                  ],
                                                ),
                                                const SizedBox(height: 6),
                                                Row(
                                                  crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                                  mainAxisAlignment:
                                                  MainAxisAlignment.start,
                                                  children: [
                                                    const SizedBox(width: 4),
                                                    ReusableTextWidget(
                                                      text: order.orderdate != null
                                                          ? "${order.orderdate!.day} ${_getMonthName(order.orderdate!.month)} ${order.orderdate!.year}"
                                                          : 'No Date',
                                                      color: ColorConstants
                                                          .blackColor
                                                          .withOpacity(0.65),
                                                      fontWeight: FontWeight.w500,
                                                      fontSize: 12,
                                                      fontFamily: FontConstants
                                                          .fontFamily,
                                                    ),
                                                  ],
                                                ),
                                                const SizedBox(height: 8),
                                                Divider(color: Colors.grey[300]),
                                                const SizedBox(
                                                  height: 5,
                                                ),
                                                Row(
                                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                                  children: [
                                                    // Track Button
                                                    Expanded(
                                                      child: Container(
                                                        height: 44,
                                                        margin: const EdgeInsets.only(right: 10),
                                                        decoration: BoxDecoration(
                                                          borderRadius: BorderRadius.circular(14),
                                                          gradient: const LinearGradient(
                                                            colors: [Color(0xFF662582), Color(0xFF7A2E9C)],
                                                            begin: Alignment.topLeft,
                                                            end: Alignment.bottomRight,
                                                          ),
                                                          boxShadow: [
                                                            BoxShadow(
                                                              color: const Color(0xFF662582).withOpacity(0.3),
                                                              blurRadius: 10,
                                                              offset: const Offset(0, 4),
                                                            ),
                                                          ],
                                                        ),
                                                        child: Material(
                                                          color: Colors.transparent,
                                                          child: InkWell(
                                                            borderRadius: BorderRadius.circular(14),
                                                            onTap: () {
                                                              HapticFeedback.mediumImpact();
                                                              Get.to(() => const DeliveryTrackingPage());
                                                            },
                                                            child: const Center(
                                                              child: Row(
                                                                mainAxisAlignment: MainAxisAlignment.center,
                                                                children: [
                                                                  Icon(Icons.location_on_rounded, color: Colors.white, size: 18),
                                                                  SizedBox(width: 6),
                                                                  Text(
                                                                    'Track',
                                                                    style: TextStyle(
                                                                      fontSize: 14,
                                                                      fontWeight: FontWeight.w600,
                                                                      color: Colors.white,
                                                                      letterSpacing: 0.2,
                                                                    ),
                                                                  ),
                                                                ],
                                                              ),
                                                            ),
                                                          ),
                                                        ),
                                                      ),
                                                    ),

                                                    // View Details Button
                                                    Expanded(
                                                      child: Container(
                                                        height: 44,
                                                        decoration: BoxDecoration(
                                                          borderRadius: BorderRadius.circular(14),
                                                          border: Border.all(color: primaryColor, width: 1.4),
                                                          color: Colors.white,
                                                        ),
                                                        child: Material(
                                                          color: Colors.transparent,
                                                          child: InkWell(
                                                            borderRadius: BorderRadius.circular(14),
                                                            onTap: () {
                                                              HapticFeedback.mediumImpact();
                                                              Navigator.push(
                                                                context,
                                                                PageRouteBuilder(
                                                                  pageBuilder: (context, animation, secondaryAnimation) =>
                                                                      OrderDetailsPage(
                                                                        orderId: order.orderid ?? 'Unknown',
                                                                        storeName: tenantName,
                                                                        storeLocation: order.tenantsuburb ?? 'Unknown',
                                                                        tax: order.totaltaxamount ?? 0,
                                                                        gstno: order.gstno ?? "",
                                                                        fee: order.deliverycharge ?? 0,
                                                                        items: order.orderdetails
                                                                            ?.map((item) => {
                                                                          'name': item.productname ?? 'Unknown',
                                                                          'quantity': item.orderqty ?? 0,
                                                                          'productSumPrice': item.productsumprice ?? 0.0,
                                                                          'price': item.price ?? 0.0,
                                                                          'discountamount': item.price ?? 0.0,
                                                                          'image': item.productimage ?? '',
                                                                        })
                                                                            .toList() ??
                                                                            [],
                                                                      ),
                                                                  transitionsBuilder: (context, animation, secondaryAnimation, child) {
                                                                    return FadeTransition(
                                                                      opacity: animation,
                                                                      child: SlideTransition(
                                                                        position: Tween<Offset>(
                                                                          begin: const Offset(0.05, 0),
                                                                          end: Offset.zero,
                                                                        ).animate(animation),
                                                                        child: child,
                                                                      ),
                                                                    );
                                                                  },
                                                                  transitionDuration: const Duration(milliseconds: 300),
                                                                ),
                                                              );
                                                            },
                                                            child: Center(
                                                              child: Text(
                                                                'View Details',
                                                                style: TextStyle(
                                                                  fontSize: 14,
                                                                  fontWeight: FontWeight.w600,
                                                                  color: primaryColor,
                                                                  letterSpacing: 0.2,
                                                                ),
                                                              ),
                                                            ),
                                                          ),
                                                        ),
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ],
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        );
                      }),
                    );
                  },
                  childCount:
                  tenantController.orders.length + 1, // extra for loader
                ),
              );
            }),
          ],
        ),
        // ✨ Floating Action Button for scroll to top
        floatingActionButton: ScaleTransition(
          scale: _fabAnimation,
          child: FloatingActionButton.small(
            backgroundColor: primaryColor,
            elevation: 4,
            onPressed: () {
              HapticFeedback.mediumImpact();
              _scrollController.animateTo(
                0,
                duration: const Duration(milliseconds: 500),
                curve: Curves.easeInOut,
              );
            },
            child: const Icon(
              Icons.arrow_upward,
              color: Colors.white,
              size: 20,
            ),
          ),
        ),
      ),
    );
  }

  // Helper method to get month name
  String _getMonthName(int month) {
    const months = [
      'Jan',
      'Feb',
      'Mar',
      'Apr',
      'May',
      'Jun',
      'Jul',
      'Aug',
      'Sep',
      'Oct',
      'Nov',
      'Dec'
    ];
    return months[month - 1];
  }

  // Shimmer placeholder for initial loading
  Widget shimmerListView() {
    return Shimmer.fromColors(
      baseColor: Colors.grey.shade300,
      highlightColor: Colors.grey.shade100,
      child: Column(
        children: List.generate(15, (index) {
          return Padding(
            padding: const EdgeInsets.symmetric(vertical: 8.0,horizontal: 8),
            child: Container(
              height: 80,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
              ),
            ),
          );
        }),
      ),
    );
  }
}

Widget emptyOrdersWidget(Size screenSize) {
  // ✨ Animated empty state
  return TweenAnimationBuilder<double>(
    tween: Tween(begin: 0.0, end: 1.0),
    duration: const Duration(milliseconds: 600),
    curve: Curves.easeOutCubic,
    builder: (context, value, child) {
      return Transform.scale(
        scale: 0.8 + (0.2 * value),
        child: Opacity(
          opacity: value,
          child: child,
        ),
      );
    },
    child: Padding(
      padding: EdgeInsets.only(
        left: screenSize.width * 0.08,
        right: screenSize.width * 0.08,
        top: screenSize.height * 0.12,
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(height: screenSize.height * 0.06),
          Image.asset(
            AssetConstants.noOrders,
            height: screenSize.height * 0.25,
            width: screenSize.width * 0.50,
            fit: BoxFit.fill,
          ),
          ReusableTextWidget(
            text: 'No Orders Yet!',
            color: ColorConstants.blackColor,
            fontFamily: FontConstants.fontFamily,
            fontSize: 18,
            fontWeight: FontWeight.w700,
            maxLines: 2,
            textAlign: TextAlign.center,
          ),
          SizedBox(height: screenSize.height * 0.01),
          ReusableTextWidget(
            text: 'Stay tuned, your next order will appear here soon!',
            color: ColorConstants.blackColor,
            fontFamily: FontConstants.fontFamily,
            fontSize: 14,
            fontWeight: FontWeight.normal,
            maxLines: 2,
            textAlign: TextAlign.center,
          ),
        ],
      ),
    ),
  );
}