import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:provider/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/module_permissions_model.dart';
import 'package:test_sa/modules/asset_inventory_module/models/session_model.dart';
import 'package:test_sa/modules/asset_inventory_module/pages/asset_inventory_detail_view.dart';
import 'package:test_sa/modules/asset_inventory_module/pages/asset_inventory_scan_assets_view.dart';
import 'package:test_sa/modules/asset_inventory_module/pages/asset_inventory_site_information_page.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/default_app_bar.dart';
import '../provider/asset_inventory_provider.dart';

class AssetInventoryPage extends StatefulWidget {
  final int sessionId;
  final int moduleId;

  const AssetInventoryPage({Key? key, required this.sessionId, required this.moduleId}) : super(key: key);

  @override
  _AssetInventoryPageState createState() {
    return _AssetInventoryPageState();
  }
}

class _AssetInventoryPageState extends State<AssetInventoryPage> {
  late AssetInventoryProvider _assetInventoryProvider;

  @override
  void initState() {
    super.initState();
    _assetInventoryProvider = Provider.of<AssetInventoryProvider>(context, listen: false);

    WidgetsBinding.instance.addPostFrameCallback((_) {
      getInitialData();
    });
  }

  Future<void> getInitialData() async {
    _assetInventoryProvider.reset();
    _assetInventoryProvider.modelPermission = context.userProvider.currentModelPermission(widget.moduleId);
    await _assetInventoryProvider.getSessionById(id: widget.sessionId);
    await _assetInventoryProvider.getAssetsInSession(
      sessionId: widget.sessionId,
    );
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Theme.of(context).scaffoldBackgroundColor,
        appBar: DefaultAppBar(
          title: 'Asset Inventory Session'.addTranslation,
          onBackPress: () {
            Navigator.pop(context);
          },
        ),
        body: Consumer<AssetInventoryProvider>(builder: (context, provider, child) {
          return DefaultTabController(
            length: 2,
            child: provider.isLoading
                ? CircularProgressIndicator(color: AppColor.loadingColor(context)).center
                : Column(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      Container(
                        margin: EdgeInsets.only(left: 16.toScreenWidth, right: 16.toScreenWidth, top: 12.toScreenHeight),
                        decoration: BoxDecoration(
                          color: AppColor.tabBarBackground(context),
                          border: Border.all(color: AppColor.tabBarBorder(context)),
                          borderRadius: BorderRadius.circular(20),
                        ),
                        child: TabBar(
                          padding: EdgeInsets.symmetric(vertical: 4.toScreenHeight, horizontal: 4.toScreenWidth),
                          labelColor: context.isDark ? AppColor.neutral30 : AppColor.black20,
                          unselectedLabelColor: context.isDark ? AppColor.neutral30 : AppColor.black20,
                          unselectedLabelStyle: AppTextStyles.bodyText,
                          labelStyle: AppTextStyles.bodyText,
                          indicatorPadding: EdgeInsets.zero,
                          indicatorSize: TabBarIndicatorSize.tab,
                          dividerColor: Colors.transparent,
                          overlayColor: WidgetStateProperty.all(Colors.transparent),
                          indicator: BoxDecoration(
                              color: AppColor.background(context),
                              borderRadius: BorderRadius.circular(15),
                              boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.03), blurRadius: 5, offset: const Offset(0, 0), spreadRadius: 0)]),
                          onTap: (index) {},
                          tabs: [
                            Tab(text: 'Session Details'.addTranslation, height: 57.toScreenHeight),
                            Tab(
                                text:
                                    '${'Scan Assets'.addTranslation} ${provider.assetInventoryResponse?.totalRows != null && provider.assetInventoryResponse!.totalRows! > 0 ? '(${provider.assetInventoryResponse?.totalRows})' : ''}',
                                height: 57.toScreenHeight),
                          ],
                        ),
                      ),
                      TabBarView(
                        children: [
                          AssetInventoryDetailView(sessionModel: provider.sessionModel ?? SessionModel()),
                          AssetInventoryScanAssetView(sessionId: provider.sessionModel?.id ?? 0),
                        ],
                      ).expanded,
                      if (provider.modelPermission?.canEdit ?? false)
                        FooterActionButton.footerContainer(
                          context: context,
                          child: AppFilledButton(
                            buttonColor: AppColor.primary10,
                            label: 'Scan Assets'.addTranslation,
                            onPressed: () => _scanAsset(provider: provider),
                            // buttonColor: AppColor.primary10,
                          ),
                        )
                    ],
                  ),
          );
        }));
  }

  Future<void> _scanAsset({required AssetInventoryProvider provider}) async {
    provider.siteFilterAssetList.clear();
    Navigator.push(context, MaterialPageRoute(builder: (contxt) => SiteInformationPage(sessionModel: provider.sessionModel ?? SessionModel())));
  }
}
