import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/ppm_provider.dart';
import 'package:test_sa/controllers/providers/api/user_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/device/asset.dart';
import 'package:test_sa/models/lookup.dart';
import 'package:test_sa/models/plan_preventive_visit/plan_preventive_visit_model.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/views/widgets/date_and_time/date_picker.dart';
import 'package:test_sa/views/widgets/item_views/info_header_widget.dart';
import 'package:test_sa/views/widgets/item_views/info_text_widget.dart';
import 'package:test_sa/views/widgets/pentry/calibration_tool_asset_picker.dart';

class PpmCalibrationToolsForm extends StatefulWidget {
  List<PreventiveVisitCalibrations>? models;

  PpmCalibrationToolsForm({Key? key, this.models = const <PreventiveVisitCalibrations>[]}) : super(key: key);

  @override
  State<PpmCalibrationToolsForm> createState() => _PpmCalibrationToolsFormState();
}

class _PpmCalibrationToolsFormState extends State<PpmCalibrationToolsForm> {
  @override
  Widget build(BuildContext context) {
    final userProvider = Provider.of<UserProvider>(context);
    final ppmProvider = Provider.of<PpmProvider>(context, listen: false);
    int totalTabs = ppmProvider.totalTabs;
    int currentIndex = totalTabs == 4 ? 2 : 1;
    return ListView.separated(
      itemCount: widget.models!.length + 1,
      padding: const EdgeInsets.only(left: 16, right: 16, top: 8, bottom: 16),
      separatorBuilder: (cxt, index) => 16.height,
      itemBuilder: (context, index) {
        if (index == widget.models!.length) {
          return Visibility(
            visible: !ppmProvider.isReadOnly,
            child: AppFilledButton(
              label: "Add More Calibration Tools".addTranslation,
              maxWidth: true,
              textColor: AppColor.headingTextColor(context),
              buttonColor: AppColor.addItemButtonColor(context),
              icon: Icon(Icons.add_circle, color: AppColor.blueStatus(context)),
              showIcon: true,
              onPressed: () async {
                if (widget.models?.isNotEmpty ?? false) {
                  if (widget.models!.last.asset?.id == null) {
                    await Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.assetNumber}");
                    return;
                  }
                  if (widget.models!.last.calibrationDateOfTesters == null) {
                    await Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.date}");
                    return;
                  }
                }
                widget.models!.add(PreventiveVisitCalibrations(id: 0));
                setState(() {});
              },
            ),
          );
        }
        PreventiveVisitCalibrations model = widget.models![index];
        return Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: AppColor.background(context),
            borderRadius: BorderRadius.circular(20),
            boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.03), blurRadius: 14)],
          ),
          child: IgnorePointer(
            ignoring: ppmProvider.isReadOnly,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    InfoHeader16Widget((index == 0 ? "$currentIndex /$totalTabs . Calibration Tools" : "")),
                    // (index == 0 ? "$currentIndex /$totalTabs . Calibration Tools" : "").heading5(context).custom(color: AppColor.textStyleColor(context)),
                    "trash".toSvgAsset(height: 20, width: 15).onPress(() {
                      widget.models!.remove(model);
                      setState(() {});
                    }),
                  ],
                ),
                16.height,
                CalibrationToolAssetPicker(
                  initialValue: model.asset?.id == null ? null : Lookup(id: model.asset?.id?.toInt(), name: model.asset?.assetNumber ?? ""),
                  hospitalId: userProvider.user!.clientId,
                  onPick: (asset) {
                    model.asset = Asset(id: asset.id, assetNumber: asset.assetNumber, assetSerialNo: asset.assetSerialNo);
                    setState(() {});
                  },
                ),
                12.height,
                if (model.asset?.assetNumber != null) InfoTextWidget(label: 'Asset Number'.addTranslation, value: model.asset?.assetNumber?.cleanupWhitespace.capitalizeFirstOfEach ?? '-'),
                // Text("Asset Number: ${model.asset?.assetNumber?.cleanupWhitespace.capitalizeFirstOfEach}", style: AppTextStyles.bodyText2.copyWith(color: AppColor.neutral120)),
                //  if (model.assetName != null) Text("Asset Name: ${model.assetName?.cleanupWhitespace.capitalizeFirstOfEach}", style: AppTextStyles.bodyText2.copyWith(color: AppColor.neutral120)),
                if (model.asset?.assetSerialNo != null) InfoTextWidget(label: 'Asset Serial No'.addTranslation, value: model.asset?.assetSerialNo?.cleanupWhitespace.capitalizeFirstOfEach ?? '-'),
                // Text("Asset Serial No: ${model.asset?.assetSerialNo?.cleanupWhitespace.capitalizeFirstOfEach}", style: AppTextStyles.bodyText2.copyWith(color: AppColor.neutral120)),
                12.height,
                ADatePicker(
                  label: context.translation.calibrationDate,
                  date: DateTime.tryParse(model.calibrationDateOfTesters ?? ""),
                  from: DateTime.now().subtract(const Duration(days: 10 * 365)),
                  backgroundColor: AppColor.fieldBgColor(context),
                  withBorder: false,
                  hideShadow: true,
                  onDatePicker: (date) {
                    model.calibrationDateOfTesters = date.toIso8601String();
                    setState(() {});
                  },
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
