import 'dart:async';
import 'package:flutter_svg/svg.dart';
import 'package:flutter/material.dart';
import 'package:dropdown_button2/dropdown_button2.dart';

class Affiliatedashboard extends StatefulWidget {
  const Affiliatedashboard({super.key});

  @override
  State<Affiliatedashboard> createState() => _AffiliatedashboardState();
}

class _AffiliatedashboardState extends State<Affiliatedashboard>
    with TickerProviderStateMixin {
  late final AnimationController _controller = AnimationController(
    duration: const Duration(milliseconds: 100),
    animationBehavior: AnimationBehavior.normal,
    vsync: this,
  )..repeat(reverse: true);
  late Animation<double> _fadeInFadeOut;
  bool isLoading = true;
  var totalClicks;
  var totalEarned;
  var totalOrders;
  var totalordersShipped;
  var customers_list_filter = "";
  var customer_filter_from_date = "";
  var customer_filter_to_date = "";
  var earnings_filter = "";
  var earnings_filter_from_date = "";
  var earnings_filter_to_date = "";
  final int _currentIndex = 0;

  final List<String> Filteritems = [
    'Today',
    'This Month',
    'Past 7 days',
    'Last Month',
    'Custom',
  ];

  final List<String> Filteritems2 = [
    'Today',
    'This Month',
    'Past 7 days',
    'Last Month',
    'Custom',
  ];
  String? selectedValue;
  String? selectedValue2;
  DateTimeRange? selectedDateRange;

  DateTimeRange? getDateRange(String filter) {
    DateTime now = DateTime.now();
    switch (filter) {
      case 'Today':
        return DateTimeRange(
          start: DateTime(now.year, now.month, now.day),
          end: DateTime(now.year, now.month, now.day),
        );
      case 'Yesterday':
        DateTime yesterday = now.subtract(Duration(days: 1));
        return DateTimeRange(
          start: DateTime(yesterday.year, yesterday.month, yesterday.day),
          end: DateTime(yesterday.year, yesterday.month, yesterday.day),
        );
      case 'This Month':
        return DateTimeRange(
          start: DateTime(now.year, now.month, 1),
          end: DateTime(now.year, now.month + 1, 0),
        );
      case 'Last Month':
        DateTime firstDayLastMonth = DateTime(now.year, now.month - 1, 1);
        DateTime lastDayLastMonth = DateTime(now.year, now.month, 0);
        return DateTimeRange(start: firstDayLastMonth, end: lastDayLastMonth);
      case 'Past 7 days':
        DateTime startOfPast7Days = now.subtract(Duration(days: 6));
        return DateTimeRange(
          start: DateTime(
            startOfPast7Days.year,
            startOfPast7Days.month,
            startOfPast7Days.day,
          ),
          end: DateTime(now.year, now.month, now.day),
        );
      case 'Custom':
        return null; // Handle this separately
      default:
        return null;
    }
  }

  // Function to show custom date range picker
  Future<DateTimeRange?> showCustomDateRangePicker(BuildContext context) async {
    return await showDateRangePicker(
      context: context,
      firstDate: DateTime(2020),
      lastDate: DateTime(2100),
    );
  }

  // Function to format date for display as YYYY-MM-DD
  String formatDate(DateTime date) {
    return "${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}";
  }

  // Example usage for displaying the selected date range
  String getFormattedDateRange() {
    if (selectedDateRange != null) {
      return '${formatDate(selectedDateRange!.start)} - ${formatDate(selectedDateRange!.end)}';
    }
    return 'Select Item';
  }

  @override
  void initState() {
    _fadeInFadeOut = Tween<double>(begin: 0.3, end: 1.5).animate(_controller);

    super.initState();
  }

  void _prepareChartData() {
    chartData =
        []
            .map((earning) {
              // Convert rawDate or date to DateTime
              DateTime? dateTime;
              if (earning.rawDate != null) {
                dateTime = DateTime.tryParse(earning.rawDate!);
              } else if (earning.date != null) {
                dateTime = DateTime.tryParse(earning.date!);
              }

              // Convert creditAmount to double
              double? credit = double.tryParse(earning.creditAmount ?? '0');

              if (dateTime != null && credit != null) {
                return _ChartData(dateTime, credit);
              } else {
                return null;
              }
            })
            .where((data) => data != null) // Remove null values
            .cast<_ChartData>()
            .toList();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _controller.dispose();
    super.dispose();
  }

  List<_ChartData> chartData = [];
  @override
  Widget build(BuildContext context) {
    double screenWidth = MediaQuery.of(context).size.width;
    double screenHeight = MediaQuery.of(context).size.height;
    return Scaffold(
      backgroundColor: Color(0xFFF4F5FA),
      body: SingleChildScrollView(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
          child: Column(
            children: [
              SizedBox(
                width: screenWidth,
                height: screenHeight * 0.28,
                child: GridView.builder(
                  itemCount: 4,
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2,
                    // 4 items in a row for tablet
                    crossAxisSpacing: 10,
                    mainAxisSpacing: 10,
                    childAspectRatio: 80 / 138,
                  ),
                  scrollDirection: Axis.horizontal,
                  shrinkWrap: true,
                  itemBuilder: (context, index) {
                    List<String> labels = [
                      "Total Earnings",
                      "Total Orders",
                      "Pending Remitance Amount",
                      "Total Orders Shipped",
                    ];
                    List<String> labelsTexts = [
                      "$totalEarned",
                      "$totalOrders",
                      "$totalClicks",
                      "$totalordersShipped",
                    ];
                    return Container(
                      padding: EdgeInsets.symmetric(
                        vertical: 5,
                        horizontal: 10,
                      ),
                      decoration: BoxDecoration(
                        color:
                            (index == 0)
                                ? Color(0xFF382560)
                                : Color(0xFFD7E0FF),
                        borderRadius: BorderRadius.circular(14),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          Text(
                            labelsTexts[index],
                            style: TextStyle(
                              color:
                                  (index == 0)
                                      ? Colors.white
                                      : Color(0xFF382560),
                              fontFamily: "Inter",
                              fontWeight: FontWeight.w400,
                              fontSize: 28,
                            ),
                          ),
                          Text(
                            labels[index],
                            style: TextStyle(
                              color:
                                  (index == 0)
                                      ? Colors.white
                                      : Color(0xFF566CB8),
                              fontFamily: "Inter",
                              fontWeight: FontWeight.w400,
                              fontSize: 12,
                            ),
                          ),
                        ],
                      ),
                    );
                  },
                ),
              ),

              if (chartData.length >= 0) ...[
                Container(
                  padding: EdgeInsets.symmetric(vertical: 10),
                  height: screenHeight * 0.5,
                  width: screenWidth,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Column(
                    children: [
                      Container(
                        padding: EdgeInsets.symmetric(
                          vertical: 0,
                          horizontal: 10,
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Container(
                              child: Text(
                                'Earnings Overview',
                                style: TextStyle(
                                  color: Color(0xFF382560),
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold,
                                ),
                                textAlign: TextAlign.center,
                              ),
                            ),
                            DropdownButtonHideUnderline(
                              child: DropdownButton2<String>(
                                isExpanded: true,
                                hint: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    SizedBox(width: 4),
                                    Expanded(
                                      child: Text(
                                        selectedValue2 ?? 'Select Item',
                                        style: TextStyle(
                                          fontSize: 14,
                                          fontWeight: FontWeight.w400,
                                          color: Colors.white,
                                        ),
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ),
                                  ],
                                ),
                                items:
                                    Filteritems2.map(
                                      (String item) => DropdownMenuItem<String>(
                                        value: item,
                                        child: Text(
                                          item,
                                          textAlign: TextAlign.right,
                                          style: const TextStyle(
                                            fontSize: 14,
                                            fontWeight: FontWeight.w400,
                                            color: Colors.white,
                                          ),
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ),
                                    ).toList(),
                                value: selectedValue2,
                                style: TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.w400,
                                  color: Colors.white,
                                ),
                                alignment: Alignment.center,
                                onChanged: (value) async {
                                  if (value == 'Custom') {
                                    selectedDateRange =
                                        await showCustomDateRangePicker(
                                          context,
                                        );
                                  } else {
                                    selectedDateRange = getDateRange(value!);
                                  }

                                  setState(() {
                                    selectedValue2 = value;
                                    // print(selectedDateRange);
                                    // print(selectedValue2);

                                    if (selectedDateRange != null) {
                                      // Extracting the 'from' and 'to' dates directly from DateTimeRange
                                      var fromRange = formatDate(
                                        selectedDateRange!.start,
                                      ); // Format start date
                                      var toRange = formatDate(
                                        selectedDateRange!.end,
                                      ); // Format end date

                                      // print('From range: $fromRange'); // Output: From range: 2024-09-21
                                      // print('To range: $toRange');       // Output: To range: 2024-09-21
                                      earnings_filter = "1";
                                      earnings_filter_from_date = fromRange;
                                      earnings_filter_to_date = toRange;
                                    }
                                  });
                                },
                                buttonStyleData: ButtonStyleData(
                                  height: 40,
                                  width: 160,
                                  padding: const EdgeInsets.only(
                                    left: 14,
                                    right: 14,
                                  ),
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(14),
                                    border: Border.all(color: Colors.black26),
                                    color: Color(0xFF382560),
                                  ),
                                  elevation: 0,
                                ),
                                iconStyleData: IconStyleData(
                                  icon: SvgPicture.asset(
                                    "assets/images/dropdown_burron2.svg",
                                  ),
                                  iconSize: 14,
                                ),
                                dropdownStyleData: DropdownStyleData(
                                  direction: DropdownDirection.right,
                                  maxHeight: 200,
                                  width: 160,
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(14),
                                    color: Color(0xFFDDE1F2),
                                  ),
                                  offset: const Offset(0, 0),
                                  scrollbarTheme: ScrollbarThemeData(
                                    radius: const Radius.circular(40),
                                    thickness: WidgetStateProperty.all(0),
                                    thumbVisibility: WidgetStateProperty.all(
                                      true,
                                    ),
                                  ),
                                ),
                                menuItemStyleData: const MenuItemStyleData(
                                  height: 40,
                                  padding: EdgeInsets.only(left: 14, right: 14),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }
}

class _ChartData {
  _ChartData(this.date, this.creditAmount);
  final DateTime date;
  final double creditAmount;
}
