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/lookup.dart';
import 'package:test_sa/modules/asset_delivery_module/models/asset_delivery_data_model.dart';
import 'package:test_sa/modules/asset_delivery_module/models/cost_center_model.dart';
import 'package:test_sa/modules/asset_delivery_module/models/delivery_line_model.dart';
import 'package:test_sa/modules/asset_delivery_module/models/technical_inspection_form_model.dart';
import 'package:test_sa/modules/asset_delivery_module/pages/technical_inpection/technical_inpection_cost_center_card_view.dart';
import 'package:test_sa/modules/asset_delivery_module/pages/technical_inpection/technical_inspection_parent_asset_list_view.dart';
import 'package:test_sa/modules/asset_delivery_module/provider/asset_delivery_provider.dart';
import 'package:test_sa/modules/asset_delivery_module/provider/power_supply_type_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_lazy_loading.dart';
import 'package:test_sa/new_views/common_widgets/app_text_form_field.dart';
import 'package:test_sa/new_views/common_widgets/single_item_drop_down_menu.dart';
import 'package:test_sa/views/widgets/loaders/no_data_found.dart';
import '../../../../new_views/common_widgets/app_filled_button.dart';
import '../../../../new_views/common_widgets/default_app_bar.dart';

class UpdateTechnicalInspectionLinesView extends StatefulWidget {
  static const String id = "/technical-inspection-form";
  final AssetDeliveryTableModel deliveryTableModel;
  final AssetDeliveryDataModel? requestModel;
  final DeliveryLineModel? deliveryLineModel;

  UpdateTechnicalInspectionLinesView({
    Key? key,
    required this.deliveryTableModel,
    this.requestModel,
    this.deliveryLineModel,
  }) : super(key: key);

  @override
  State<UpdateTechnicalInspectionLinesView> createState() => _UpdateTechnicalInspectionLinesViewState();
}

class _UpdateTechnicalInspectionLinesViewState extends State<UpdateTechnicalInspectionLinesView> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  TechnicalInspectionFormModel model = TechnicalInspectionFormModel();
  AssetDeliveryProvider? assetDeliveryProvider;
  bool isLoading = false;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getInitialData();
    });
    super.initState();
  }

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

  void getInitialData() async {
    assetDeliveryProvider = Provider.of<AssetDeliveryProvider>(context, listen: false);
    isLoading = true;
    setState(() {});
    model = await assetDeliveryProvider!.getTechnicalInspectionData(
      lineId: widget.deliveryLineModel?.id,
      tableId: widget.deliveryTableModel.id,
    );
    isLoading = false;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: DefaultAppBar(
        title: 'Technical Inspection'.addTranslation,
        titleStyle: AppTextStyles.heading3.copyWith(fontWeight: FontWeight.w500, color: context.isDark ? AppColor.neutral30 : AppColor.neutral50),
      ),
      body: Form(
        key: _formKey,
        child: isLoading
            ? CircularProgressIndicator(color: AppColor.loadingColor(context)).center
            : Column(
                children: [
                  SingleChildScrollView(
                      padding: const EdgeInsets.all(16),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              itemDetails(context: context, itemNo: widget.deliveryLineModel?.itemNumber, itemDescription: widget.deliveryLineModel?.itemDescription),
                              12.height,
                              inspectionDetailsForm(),
                            ],
                          ).toShadowContainer(context, borderRadius: 20, padding: 12),
                          20.height,
                          Text(
                            "Cost Centers",
                            style: AppTextStyles.heading6.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.black10),
                          ),
                          16.height,
                          costCenterList(context),
                        ],
                      )).expanded,
                  FooterActionButton.footerContainer(context: context, child: AppFilledButton(buttonColor: AppColor.primary10, label: 'Save'.addTranslation, maxWidth: true, onPressed: _saveTap)),
                ],
              ),
      ),
    );
  }

  Widget costCenterList(BuildContext context) {
    List<CostCenterModel> costCenterList = model.costCenters ?? [];
    return costCenterList.isEmpty
        ? const NoDataFound().center
        : ListView.separated(
            itemCount: costCenterList.length,
            separatorBuilder: (_, __) => 8.height,
            padding: EdgeInsets.zero,
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemBuilder: (listContext, itemIndex) {
              return TechnicalInspectionCostCard(
                costModel: costCenterList[itemIndex],
                editPress: () {
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => TechnicalInspectionParentAssetListView(
                                costCenterId: costCenterList[itemIndex].id,
                                tableItemId: widget.deliveryTableModel.id,
                                lineId: widget.deliveryLineModel?.id,
                              )));
                },
                isViewOnly: false,
              );
            },
          );
  }

  Widget itemDetails({required BuildContext context, String? itemNo, String? itemDescription}) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'Item No'.addTranslation,
          style: AppTextStyles.bodyText.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.black10),
        ),
        8.height,
        Text(
          itemNo ?? '-',
          style: AppTextStyles.bodyText2.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral120),
        ),
        8.height,
        Text(
          'Item Description'.addTranslation,
          style: AppTextStyles.bodyText.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.black10),
        ),
        8.height,
        Text(
          itemDescription ?? '-',
          style: AppTextStyles.bodyText2.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral120),
        ),
      ],
    );
  }

  Widget inspectionDetailsForm() {
    return Column(
      children: [
        SingleItemDropDownMenu<Lookup, PowerSupplyTypeProvider>(
          context: context,
          height: 56.toScreenHeight,
          title: 'Power Supply Type'.addTranslation,
          titleTextColor: AppColor.neutral120,
          showShadow: false,
          validator: (value) {
            if (value == null) return 'Please select power supply type';
            return null;
          },
          backgroundColor: AppColor.fieldBgColor(context),
          showAsBottomSheet: true,
          initialValue: model.powerSupplyType,
          onSelect: (value) {
            if (value != null) {
              model.powerSupplyType = value;
              setState(() {});
            }
          },
        ),
        8.height,
        AppTextFormField(
          labelText: 'Power Reading'.addTranslation,
          backgroundColor: AppColor.fieldBgColor(context),
          initialValue: model.powerReading != null ? model.powerReading.toString() : '',
          textAlign: TextAlign.center,
          labelStyle: AppTextStyles.textFieldLabelStyle,
          textInputType: TextInputType.number,
          showShadow: false,
          validator: (value) {
            if ((value ?? "").isEmpty) return "Mandatory";
            return null;
          },
          onSaved: (value) {
            model.powerReading = int.tryParse(value);
          },
          style: Theme.of(context).textTheme.titleMedium,
        ),
        8.height,
        AppTextFormField(
          labelText: 'Max Current'.addTranslation,
          backgroundColor: AppColor.fieldBgColor(context),
          initialValue: model.maxCurrent != null ? model.maxCurrent.toString() : '',
          textAlign: TextAlign.center,
          labelStyle: AppTextStyles.textFieldLabelStyle,
          textInputType: TextInputType.number,
          showShadow: false,
          validator: (value) {
            if ((value ?? "").isEmpty) return "Mandatory";
            return null;
          },
          onSaved: (value) {
            model.maxCurrent = int.tryParse(value);
          },
          style: Theme.of(context).textTheme.titleMedium,
        ),
        8.height,
        AppTextFormField(
          labelText: 'Voltage'.addTranslation,
          backgroundColor: AppColor.fieldBgColor(context),
          textInputType: TextInputType.number,
          initialValue: model.voltage != null ? model.voltage.toString() : '',
          textAlign: TextAlign.center,
          validator: (value) {
            if ((value ?? "").isEmpty) return "Mandatory";
            return null;
          },
          onSaved: (value) {
            model.voltage = int.tryParse(value);
          },
          labelStyle: AppTextStyles.textFieldLabelStyle,
          showShadow: false,
          style: Theme.of(context).textTheme.titleMedium,
        ),
        8.height,
        AppTextFormField(
          labelText: 'Frequency'.addTranslation,
          backgroundColor: AppColor.fieldBgColor(context),
          initialValue: model.frequency != null ? model.frequency.toString() : '',
          textInputType: TextInputType.number,
          textAlign: TextAlign.center,
          validator: (value) {
            if ((value ?? "").isEmpty) return "Mandatory";
            return null;
          },
          onSaved: (value) {
            model.frequency = int.tryParse(value);
          },
          labelStyle: AppTextStyles.textFieldLabelStyle,
          showShadow: false,
          style: Theme.of(context).textTheme.titleMedium,
        ),
      ],
    );
  }

  void _saveTap() async {
    if (!_formKey.currentState!.validate()) return;
    _formKey.currentState!.save();
    model.tableItemId = widget.deliveryTableModel.id;
    model.lineId = widget.deliveryLineModel?.id;
    showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
    await assetDeliveryProvider?.saveTechnicalInspection(model: model).then((status) async {
      Navigator.pop(context);
      if (status) {
        Navigator.pop(context);
      }
    });
  }
}
