import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/all_requests_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/models/new_models/building.dart';
import 'package:test_sa/models/new_models/department.dart';
import 'package:test_sa/models/new_models/floor.dart';
import 'package:test_sa/models/new_models/room_model.dart';
import 'package:test_sa/models/new_models/site.dart';
import 'package:test_sa/modules/asset_inventory_module/models/asset_inventory_model.dart';
import 'package:test_sa/modules/asset_inventory_module/models/session_model.dart';
import 'package:test_sa/modules/asset_inventory_module/pages/asset_detail_card_view.dart';
import 'package:test_sa/modules/asset_inventory_module/pages/asset_inventory_form_view.dart';
import 'package:test_sa/modules/asset_inventory_module/provider/asset_inventory_provider.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/app_lazy_loading.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.dart';
import 'package:test_sa/new_views/common_widgets/single_item_drop_down_menu.dart';
import 'package:test_sa/providers/loading_list_notifier.dart';
import 'package:test_sa/views/widgets/loaders/lazy_loading.dart';

class SiteInformationPage extends StatefulWidget {
  SessionModel sessionModel;

  SiteInformationPage({Key? key, required this.sessionModel}) : super(key: key);

  @override
  State<SiteInformationPage> createState() => _SiteInformationPageState();
}

class _SiteInformationPageState extends State<SiteInformationPage> {
  AssetInventoryModel assetInventoryModel = AssetInventoryModel();
  bool showMarkAsComplete = false;
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      final provider = Provider.of<AssetInventoryProvider>(context, listen: false);
      if (_scrollController.position.pixels >= _scrollController.position.maxScrollExtent && !provider.isNextPageLoading && provider.nextPage) {
        getAssetFilteredList(loadMore: true);
      }
    });
  }

  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: DefaultAppBar(
        title: 'Inventory Session Request'.addTranslation,
        titleStyle: AppTextStyles.heading3.copyWith(fontWeight: FontWeight.w500, color: context.isDark ? AppColor.neutral30 : AppColor.neutral50),
      ),
      body: Column(
        children: [
          ListView(
            controller: _scrollController,
            padding: const EdgeInsets.only(left: 16, right: 16, top: 16),
            children: [
              siteInfoCard(context, widget.sessionModel),
              12.height,
              assetDetailList(),
              8.height,
            ],
          ).expanded,
          FooterActionButton.footerContainer(
            context: context,
            child: Column(
              children: [
                AppFilledButton(
                  buttonColor: AppColor.primary10,
                  label: 'Add Asset'.addTranslation,
                  onPressed: () => _addAsset(),
                  // buttonColor: AppColor.primary10,
                ),
                if (showMarkAsComplete) ...[
                  12.height,
                  AppFilledButton(
                    buttonColor: AppColor.green70,
                    label: 'Mark as completed'.addTranslation,
                    onPressed: () => _markAsCompleted(),
                    // buttonColor: AppColor.primary10,
                  )
                ]
              ],
            ),
          ),
        ],
      ),
    );
  }

  void _addAsset() async {
    if (await validateRequest()) {
      assetInventoryModel.sessionId = widget.sessionModel.id;
      Navigator.push(
          context,
          MaterialPageRoute(
              builder: (contxt) => AssetInventoryFormView(
                    assetInventoryModel: assetInventoryModel,
                    sessionTypeValue: widget.sessionModel.sessionTypeValue,
                  )));
    }
  }

  void _markAsCompleted() async {
    if (await validateRequest()) {
      assetInventoryModel.sessionId = widget.sessionModel.id;
      AssetInventoryProvider provider = Provider.of<AssetInventoryProvider>(context, listen: false);
      Map<String, dynamic> payload = {
        "sessionId": widget.sessionModel.id,
        "siteId": assetInventoryModel.site?.id,
        "buildingId": assetInventoryModel.building?.id,
        "floorId": assetInventoryModel.floor?.id,
        "departmentId": assetInventoryModel.department?.id,
        "roomId": assetInventoryModel.room?.id,
      };
      showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
      await provider.markAsComplete(payload: payload).then((success) {
        Navigator.pop(context);
        if (success) {
          ///TODO need to confirm need to call this or not ..
          // AllRequestsProvider allRequestsProvider = Provider.of<AllRequestsProvider>(context, listen: false);
          // allRequestsProvider.reset();
          // allRequestsProvider.getAllRequests(context, typeTransaction: 8);
          ///Need to call push and remove until...
          Navigator.pop(context);
          Navigator.pop(context);
        }
      });
    }
  }

  Widget assetDetailList() {
    return Consumer<AssetInventoryProvider>(
      builder: (context, provider, _) {
        if (provider.isLoading) {
          return SizedBox(
            height: 300.toScreenHeight,
            child: CircularProgressIndicator(color: AppColor.loadingColor(context)).center,
          );
        }

        final assets = provider.siteFilterAssetList;
        return ListView.separated(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          // Keep non-scrollable, parent handles scroll
          itemCount: assets.length,
          itemBuilder: (context, index) {
            return AssetDetailCardView(
              canDelete: (provider.modelPermission?.canEdit ?? false),
              assetInventoryModel: assets[index],
              onDeletePress: () async {
                await provider.deleteAssetISession(id: assets[index].id ?? 0).then((success) async {
                  if (success) {
                    await getAssetFilteredList();
                    await provider.getAssetsInSession(sessionId: widget.sessionModel.id ?? 0);
                  }
                });
              },
            );
          },
          separatorBuilder: (context, index) => 12.height,
        );
      },
    );
  }

  Widget siteInfoCard(BuildContext context, SessionModel sessionModel) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SingleItemDropDownMenu<Site, NullableLoadingProvider>(
          context: context,
          title: context.translation.site,
          initialValue: assetInventoryModel.site,
          showShadow: false,
          staticData: sessionModel.assetInventorySites,
          backgroundColor: AppColor.fieldBgColor(context),
          showAsBottomSheet: true,
          onSelect: (value) {
            assetInventoryModel.site = value;
            assetInventoryModel.building = null;
            assetInventoryModel.floor = null;
            assetInventoryModel.department = null;
            setState(() {});
          },
        ),
        12.height,
        SingleItemDropDownMenu<Building, NullableLoadingProvider>(
          context: context,
          title: context.translation.building,
          initialValue: assetInventoryModel.building,
          showShadow: false,
          showAsBottomSheet: true,
          backgroundColor: AppColor.fieldBgColor(context),
          enabled: assetInventoryModel.site?.buildings?.isNotEmpty ?? false,
          staticData: assetInventoryModel.site?.buildings ?? [],
          onSelect: (value) {
            assetInventoryModel.building = value;
            assetInventoryModel.floor = null;
            assetInventoryModel.department = null;
            setState(() {});
          },
        ),
        12.height,
        SingleItemDropDownMenu<Floor, NullableLoadingProvider>(
          context: context,
          title: context.translation.floor,
          showShadow: false,
          showAsBottomSheet: true,
          initialValue: assetInventoryModel.floor,
          backgroundColor: AppColor.fieldBgColor(context),
          enabled: assetInventoryModel.building?.floors?.isNotEmpty ?? false,
          staticData: assetInventoryModel.building?.floors ?? [],
          onSelect: (value) {
            assetInventoryModel.floor = value;
            assetInventoryModel.department = null;
            setState(() {});
          },
        ),
        12.height,
        SingleItemDropDownMenu<Department, NullableLoadingProvider>(
          context: context,
          title: context.translation.department,
          showShadow: false,
          showAsBottomSheet: true,
          initialValue: assetInventoryModel.department,
          backgroundColor: AppColor.fieldBgColor(context),
          enabled: assetInventoryModel.floor?.departments?.isNotEmpty ?? false,
          staticData: assetInventoryModel.floor?.departments ?? [],
          onSelect: (value) {
            assetInventoryModel.department = value;
            assetInventoryModel.room = null;
            showMarkAsComplete = true;
            setState(() {});
            if (assetInventoryModel.department != null && assetInventoryModel.department!.rooms!.isEmpty) {
              getAssetFilteredList();
            }
          },
        ),
        12.height,
        SingleItemDropDownMenu<Rooms, NullableLoadingProvider>(
          context: context,
          title: context.translation.room,
          showShadow: false,
          showAsBottomSheet: true,
          initialValue: assetInventoryModel.room,
          backgroundColor: AppColor.fieldBgColor(context),
          enabled: assetInventoryModel.department?.rooms?.isNotEmpty ?? false,
          staticData: assetInventoryModel.department?.rooms ?? [],
          onSelect: (value) {
            assetInventoryModel.room = value;
            setState(() {});
            if (assetInventoryModel.room != null) {
              getAssetFilteredList();
            }
          },
        ),
      ],
    ).toShadowContainer(context, borderRadius: 20, padding: 12);
  }

  Future<bool> validateRequest() async {
    if (assetInventoryModel.site == null) {
      await Fluttertoast.showToast(msg: "Please Select Site");
      return false;
    }
    if (assetInventoryModel.building == null) {
      await Fluttertoast.showToast(msg: "Please Select Building");
      return false;
    }
    if (assetInventoryModel.floor == null) {
      await Fluttertoast.showToast(msg: "Please Select Floor");
      return false;
    }
    if (assetInventoryModel.department == null) {
      await Fluttertoast.showToast(msg: "Please Select Department");
      return false;
    }
    return true;
  }

  Future<void> getAssetFilteredList({bool loadMore = false}) async {
    AssetInventoryProvider provider = Provider.of<AssetInventoryProvider>(context, listen: false);
    Map<String, dynamic> payload = {
      "sessionId": widget.sessionModel.id,
      "siteId": assetInventoryModel.site?.id,
      "buildingId": assetInventoryModel.building?.id,
      "floorId": assetInventoryModel.floor?.id,
      "departmentId": assetInventoryModel.department?.id,
      "roomId": assetInventoryModel.room?.id,
    };
    await provider.getInventoryDetailsByFilter(payload: payload, loadMore: loadMore);
  }
}
