import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/user_provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/string_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.dart';
import 'package:test_sa/views/widgets/date_and_time/date_picker.dart';
import 'package:test_sa/views/widgets/loaders/lazy_loading.dart';
import 'package:test_sa/views/widgets/loaders/no_data_found.dart';


import 'models/swipe_transaction_history.dart';

class SwipeHistoryView extends StatefulWidget {
  static const routeName = '/swipe_list_view';

  const SwipeHistoryView({Key? key}) : super(key: key);

  @override
  State<SwipeHistoryView> createState() => _SwipeHistoryViewState();
}


class _SwipeHistoryViewState extends State<SwipeHistoryView> {
  DateTime dateFrom = DateTime.now();
  DateTime dateTo = DateTime.now();
  UserProvider? _userProvider;
  @override
  void initState() {
    getSwipeHistory();
    super.initState();
  }

  void  getSwipeHistory () {
    _userProvider = Provider.of<UserProvider>(context,listen:false);
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      await  _userProvider!.getSwipeTransactionHistory(userId: _userProvider!.user!.userID!,dateFrom: dateFrom,dateTo: dateTo);
    });
  }
  @override
  Widget build(BuildContext context) {
    return  Scaffold(
      appBar: const DefaultAppBar(title: 'Swipe History',),
      body: Column(
        crossAxisAlignment:CrossAxisAlignment.start,
        children: [

          8.height,
          Row(
            children: [
              ADatePicker(
                label: context.translation.from,
                date: dateFrom,
                from: DateTime(DateTime.now().year - 5, DateTime.now().month, DateTime.now().day),
                formatDateWithTime: true,
                onDatePicker: (selectedDate) {
                  if (selectedDate != null) {
                    showTimePicker(
                      context: context,
                      initialTime: TimeOfDay.now(),
                    ).then((selectedTime) {
                      // Handle the selected date and time here.
                      if (selectedTime != null) {
                        DateTime selectedDateTime = DateTime(
                          selectedDate.year,
                          selectedDate.month,
                          selectedDate.day,
                          selectedTime.hour,
                          selectedTime.minute,
                        );
                        if (selectedDateTime != null) {
                          setState(() {
                            dateFrom = selectedDateTime;
                          });
                        }
                      }
                    });
                  }
                },
              ).expanded,
              8.width,
              ADatePicker(
                label: context.translation.to,
                date: dateTo,
                from: DateTime(DateTime.now().year - 5, DateTime.now().month, DateTime.now().day),
                formatDateWithTime: true,
                onDatePicker: (selectedDate) {
                  if (selectedDate != null) {
                    showTimePicker(
                      context: context,
                      initialTime: TimeOfDay.now(),
                    ).then((selectedTime) {
                      // Handle the selected date and time here.
                      if (selectedTime != null) {
                        DateTime selectedDateTime = DateTime(
                          selectedDate.year,
                          selectedDate.month,
                          selectedDate.day,
                          selectedTime.hour,
                          selectedTime.minute,
                        );
                        if (selectedDateTime != null) {
                          setState(() {
                           dateTo = selectedDateTime;

                          });

                        }
                      }
                    });
                  }
                },
              ).expanded,
            ],
          ),
          12.height,
          AppFilledButton(label: context.translation.search, maxWidth: false, onPressed: getSwipeHistory),
          8.height,
          const Divider(thickness: 2,color:AppColor.white60 ,),

          Consumer<UserProvider>(
            builder: (context, snapshot,child) {
              return SwipeHistoryList(snapshot.swipeHistory ?? [], snapshot.isLoading).expanded;
            }
          ),


        ],
      ).paddingAll(20),
    );
  }
}




class SwipeHistoryList extends StatelessWidget {
  List<SwipeHistory> list;
  bool isLoading;

  SwipeHistoryList(this.list, this.isLoading, {Key ?key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return (list.isEmpty && !isLoading)
        ? NoDataFound(message: context.translation.noDataFound).center
        : ListView.separated(
        padding:  EdgeInsets.only(top: 12.toScreenHeight),
        itemBuilder: (cxt, index) {
          if (isLoading) return const SizedBox().toRequestShimmer(cxt, isLoading);
          return SwipeHistoryCard(list[index]);
        },
        separatorBuilder: (cxt, index) => 12.height,
        itemCount: isLoading ? 6 : list.length);
  }
}
class SwipeHistoryCard extends StatelessWidget {
  final SwipeHistory swipeHistory;
  final bool showShadow;
  const SwipeHistoryCard(this.swipeHistory, {Key? key, this.showShadow = true}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(swipeHistory.swipeTime!.toServiceRequestDetailsFormat, textAlign: TextAlign.end, style: AppTextStyles.tinyFont.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.neutral50)),
          ],
        ),
        8.height,
        '${context.translation.swipeTypeName}: ${swipeHistory.swipeTypeName?.cleanupWhitespace.capitalizeFirstOfEach}'.bodyText(context),
        '${context.translation.userName}:  ${swipeHistory.userName}'.bodyText(context),
        '${context.translation.siteName}: ${swipeHistory.siteName}'.bodyText(context),
        '${context.translation.pointName}: ${swipeHistory.pointName}'.bodyText(context),
        8.height,
      ],
    ).toShadowContainer(context, showShadow: showShadow);
  }
}

