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/date_and_time/time_picker.dart';
import 'package:test_sa/views/widgets/item_views/info_text_widget.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: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              spacing: 8,
              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) {
                      showThemedTimePicker(
                        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,
                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) {
                      showThemedTimePicker(
                        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().defaultStyle(context),
            Consumer<UserProvider>(builder: (context, snapshot, child) {
              return SwipeHistoryList(snapshot.swipeHistory ?? [], snapshot.isLoading).expanded;
            }).expanded,
          ],
        ).paddingOnly(start: 16, end: 16, top: 16),
      ),
    );
  }
}

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: const EdgeInsets.only(bottom: 16, top: 16),
            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: AppColor.textStyleColor(context))),
          ],
        ),
        8.height,
        InfoTextWidget(label: context.translation.swipeTypeName, value: swipeHistory.swipeTypeName?.cleanupWhitespace.capitalizeFirstOfEach),
        InfoTextWidget(label: context.translation.userName, value: swipeHistory.userName, showEmptyValue: true),
        InfoTextWidget(label: context.translation.siteName, value: swipeHistory.siteName, showEmptyValue: true),
        InfoTextWidget(label: context.translation.pointName, value: swipeHistory.pointName, showEmptyValue: true),
      ],
    ).toShadowContainer(context, padding: 16);
  }
}
