import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/devices_provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/models/lookup.dart';
import 'package:test_sa/models/new_models/site.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/single_item_drop_down_menu.dart';
import 'package:test_sa/providers/department_provider.dart';
import 'package:test_sa/providers/gas_request_providers/site_provider.dart';
import 'package:test_sa/views/widgets/date_and_time/date_picker.dart';

import '../../../models/device/asset_search.dart';
import '../../../new_views/common_widgets/app_lazy_loading.dart';
import '../../../new_views/common_widgets/default_app_bar.dart';
import '../../widgets/equipment/commissioning_status_buttons.dart';

class DeviceFilterScreen extends StatefulWidget {
  static const String id = "asset_filter_screen";
  final DeviceSearch? data;

  const DeviceFilterScreen({Key? key, this.data}) : super(key: key);

  @override
  State<DeviceFilterScreen> createState() => _DeviceFilterScreenState();
}

class _DeviceFilterScreenState extends State<DeviceFilterScreen> {
  late DeviceSearch filter;
  Lookup? _commissioningStatus;
  Site? _site;
  Lookup? _department;
  String? startDate, endDate;
  bool loading = false;

  @override
  void initState() {
    filter = widget.data ?? DeviceSearch();
    WidgetsFlutterBinding.ensureInitialized().addPostFrameCallback((timeStamp) async {
      loading = true;
      setState(() {});
      startDate = filter.supplyDateFrom;
      endDate = filter.supplyDateTo;
      final departmentProvider = Provider.of<DepartmentProvider>(context, listen: false);
      final siteProvider = Provider.of<SiteProvider>(context, listen: false);
      if (departmentProvider.items.isEmpty ?? true) await departmentProvider.getDate();
      if (siteProvider.items.isEmpty ?? true) await siteProvider.getDate();
      _department = departmentProvider.items.where((element) => element.name == filter.department).firstOrNull;
      _site = siteProvider.items.where((element) => element.name == filter.site).firstOrNull;
      loading = false;
      setState(() {});
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: DefaultAppBar(
        title: context.translation.filter,
        actions: [
          if (loading == false && _showResetButton())
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text(
                  context.translation.reset,
                  style: AppTextStyles.bodyText2.copyWith(color: AppColor.primary50),
                ).paddingAll(8).onPress(() {
                  setState(() {
                    startDate = null;
                    endDate = null;
                    _department = null;
                    _site = null;
                  });
                }),
              ],
            )
        ],
      ),
      body: Column(
        children: [
          SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                /// todo : TBD
                CommissioningStatusButtons(
                  initialValue: _commissioningStatus,
                  onSelect: (value) {
                    if (value != null) {
                      _commissioningStatus = value;
                    }
                  },
                ),
                16.height,
                SingleItemDropDownMenu<Lookup, DepartmentProvider>(
                  context: context,
                  title: context.translation.byDepartment,
                  initialValue: _department,
                  loading: loading == false ? null : loading,
                  onSelect: (value) {
                    setState(() {
                      _department = value;
                    });
                  },
                ).paddingOnly(start: 16, end: 16),
                8.height,
                SingleItemDropDownMenu<Site, SiteProvider>(
                  context: context,
                  title: context.translation.bySite,
                  initialValue: _site,
                  loading: loading == false ? null : loading,
                  onSelect: (value) {
                    setState(() {
                      _site = value;
                    });
                  },
                ).paddingOnly(start: 16, end: 16),
                16.height,
                context.translation.pmDateRange.heading5(context).paddingOnly(start: 16, end: 16),
                8.height,
                Row(
                  children: [
                    ADatePicker(
                      label: context.translation.to,
                      from: DateTime(2000),
                      date: DateTime.tryParse(startDate ?? ""),
                      onDatePicker: (date) {
                        setState(() {
                          startDate = date.toIso8601String();
                        });
                      },
                    ).expanded,
                    8.width,
                    ADatePicker(
                      label: context.translation.to,
                      from: DateTime(2000),
                      date: DateTime.tryParse(endDate ?? ""),
                      onDatePicker: (date) {
                        setState(() {
                          endDate = date.toIso8601String();
                        });
                      },
                    ).expanded,
                  ],
                ).paddingOnly(start: 16, end: 16),
              ],
            ),
          ).expanded,
          AppFilledButton(onPressed: _search, label: context.translation.applyFilter).paddingOnly(start: 16, end: 16),
        ],
      ).paddingOnly(top: 16, bottom: 16),
    );
  }

  void _search() async {
    filter.site = _site?.name;
    filter.department = _department?.name;
    filter.supplyDateFrom = startDate;
    filter.supplyDateTo = endDate;
    final deviceProvider = Provider.of<AssetProvider>(context, listen: false);
    deviceProvider.reset();
    showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
    await deviceProvider.getAssets(search: filter);
    Navigator.pop(context);
    Navigator.of(context).pop(filter);
  }

  bool _showResetButton() {
    return (_department != null) || (_site != null) || (startDate != null) || (endDate != null);
  }
}
