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/modules/cm_module/views/components/action_button/footer_action_button.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/multiple_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 'package:test_sa/views/widgets/equipment/asset_status_buttons.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';

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;
  List<Site> _selectedSites = [];
  List<Lookup> _selectedDepartments = [];
  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;
      _commissioningStatus = filter.assetStatus;
      final departmentProvider = Provider.of<DepartmentProvider>(context, listen: false);
      final siteProvider = Provider.of<SiteProvider>(context, listen: false);
      if (departmentProvider.items.isEmpty ?? true) await departmentProvider.getData();
      if (siteProvider.items.isEmpty ?? true) await siteProvider.getData();

      // Initialize selected departments from filter
      if (filter.departments != null && filter.departments!.isNotEmpty) {
        _selectedDepartments = [];
        for (var deptName in filter.departments!) {
          final match = departmentProvider.items.firstWhere(
            (dept) => dept.name == deptName,
            orElse: () => Lookup(),
          );
          if (match.id != null) {
            _selectedDepartments.add(match);
          }
        }
      }

      // Initialize selected sites from filter
      if (filter.sites != null && filter.sites!.isNotEmpty) {
        _selectedSites = [];
        for (var siteName in filter.sites!) {
          final match = siteProvider.items.firstWhere(
            (site) => site.name == siteName,
            orElse: () => Site(),
          );
          if (match.id != null) {
            _selectedSites.add(match);
          }
        }
      }

      loading = false;
      setState(() {});
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: DefaultAppBar(
        title: context.translation.filter,
        showBackButtonAsCancel: true,
        actions: [
          if (loading == false && _showResetButton())
            TextButton(
              onPressed: () {
                setState(() {
                  startDate = null;
                  endDate = null;
                  _selectedDepartments = [];
                  _selectedSites = [];
                  _commissioningStatus = null;
                });
              },
              style: TextButton.styleFrom(padding: EdgeInsets.zero, tapTargetSize: MaterialTapTargetSize.shrinkWrap),
              child: Text(
                'Clear Filters',
                style: AppTextStyles.bodyText2.copyWith(color: AppColor.red30),
              ),
            ).paddingOnly(start: 16, end: 16)
        ],
      ),
      body: Column(
        children: [
          ListView(
            padding: const EdgeInsets.all(16),
            children: [
              AssetStatusButtons(
                initialValue: _commissioningStatus,
                onSelect: (value) {
                  if (value != null) {
                    _commissioningStatus = value;
                  }
                },
              ),
              16.height,
              MultipleItemDropDownMenu<Lookup, DepartmentProvider>(
                context: context,
                title: context.translation.byDepartment,
                initialValue: _selectedDepartments,
                showAsBottomSheet: true,
                // backgroundColor: context.isDark ? AppColor.neutral60 : Colors.white,
                // backgroundColor: AppColor.fieldBgColor(context),
                showShadow: true,
                height: 56.toScreenHeight,
                showCancel: true,
                onSelect: (value) {
                  if (value != null) {
                    setState(() {
                      _selectedDepartments = value;
                    });
                  }
                },
              ),
              12.height,
              MultipleItemDropDownMenu<Site, SiteProvider>(
                context: context,
                title: context.translation.bySite,
                initialValue: _selectedSites,
                showAsBottomSheet: true,
                // backgroundColor: AppColor.fieldBgColor(context),
                backgroundColor: context.isDark ? AppColor.neutral60 : Colors.white,
                showShadow: true,
                height: 56.toScreenHeight,
                showCancel: true,
                onSelect: (value) {
                  if (value != null) {
                    setState(() {
                      _selectedSites = value;
                    });
                  }
                },
              ),
              16.height,
              context.translation.pmDateRange.heading5(context).custom(color: AppColor.textStyleColor(context)),
              8.height,
              Row(
                children: [
                  ADatePicker(
                    label: context.translation.from,
                    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,
                ],
              ),
            ],
          ).expanded,
          FooterActionButton.footerContainer(context: context, child: AppFilledButton(onPressed: _search, label: context.translation.applyFilter)),
        ],
      ),
    );
  }

  void _search() async {
    filter.sites = _selectedSites.map((site) => site.name ?? '').where((name) => name.isNotEmpty).toList();
    filter.departments = _selectedDepartments.map((dept) => dept.name ?? '').where((name) => name.isNotEmpty).toList();
    filter.assetStatus = _commissioningStatus;
    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 (_selectedDepartments.isNotEmpty) || (_selectedSites.isNotEmpty) || (_commissioningStatus != null) || (startDate != null) || (endDate != null);
  }
}
