import 'package:hmg_patient_app/core/model/labs/patient_lab_orders.dart';
import 'package:hmg_patient_app/core/viewModels/medical/labs_view_model.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/models/header_model.dart';
import 'package:hmg_patient_app/pages/base/base_view.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:hmg_patient_app/uitl/utils.dart';
import 'package:hmg_patient_app/widgets/data_display/medical/LabResult/newUI/LabItem.dart';
import 'package:hmg_patient_app/widgets/new_design/doctor_header.dart';
import 'package:hmg_patient_app/widgets/others/network_base_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:provider/provider.dart';

class LaboratoryResultWidget extends StatefulWidget {
  final GestureTapCallback? onTap;
  final String? billNo;
  final String? details;
  final String? orderNo;
  final String? projectName;
  final PatientLabOrders? patientLabOrder;
  final bool showConfirmMessageDialog;
  final LabsViewModel labmodel;

  const LaboratoryResultWidget({Key? key, this.onTap, this.billNo, this.details, this.orderNo, this.projectName, this.patientLabOrder, this.showConfirmMessageDialog = true,required this.labmodel}) : super(key: key);

  @override
  _LaboratoryResultWidgetState createState() => _LaboratoryResultWidgetState();
}

class _LaboratoryResultWidgetState extends State<LaboratoryResultWidget> {
  bool _isShowMore = true;
  late ProjectViewModel projectViewModel;
  late String? labSpecialResult;
  bool isTabletScreen = false;
  LabsViewModel? model;

  @override
  void initState() {
    super.initState();
    this.model = widget.labmodel;

    labSpecialResult = widget.details ?? "No Data Available";
  }


  @override
  void didChangeDependencies() {
    super.didChangeDependencies();

    var oldStateTablateScreenState = isTabletScreen;
    isTabletScreen =   isTablet(context);
    if(isTabletScreen != oldStateTablateScreenState);
    {
      model?.recalculatePercentage(isTabletScreen);
    }

  }

  bool isTablet(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final shortestSide = size.shortestSide;
    return shortestSide >= 550;
  }

  @override
  Widget build(BuildContext context) {
    isTabletScreen = isTablet(context);
    projectViewModel = Provider.of(context);
    return BaseView<LabsViewModel>(
      onModelReady: (_) {
        print("the length of in on model Ready ${model?.patientLabSpecialResult.length}");
        WidgetsBinding.instance.addPostFrameCallback((_) {
          model?.getPatientLabResult(isVidaPlus: Utils.isVidaPlusProject(projectViewModel, int.parse(widget.patientLabOrder!.projectID!)), patientLabOrder: widget.patientLabOrder!,  isTablet: isTabletScreen);
        });
        labSpecialResult = widget.details ?? "No Data Available";
      },
      builder: (_, __, w) => NetworkBaseView(
        baseViewModel: widget.labmodel,
        child: Column(
          mainAxisSize: MainAxisSize.max,
          children: [
            _buildDoctorHeader(),
            SizedBox(height: 10),
            if (this.model?.labResultLists.isNotEmpty == true)
              Padding(
                padding: const EdgeInsets.all(21.0),
                child: _buildLabResultsList(model!),
              ),

            // Expanded(
            //   child: _buildLabResultsList(model),
            // ),
            _buildSpecialResultsToggle(),
            SizedBox(height: 16),
          ],
        ),
      ),
    );
  }

  Widget _buildDoctorHeader() {
    return DoctorHeader(
      headerModel: HeaderModel(
        widget.patientLabOrder!.doctorName!,
        widget.patientLabOrder!.doctorID ?? 0,
        widget.patientLabOrder!.doctorImageURL!,
        widget.patientLabOrder!.speciality ?? [""],
        widget.billNo!,
        widget.patientLabOrder!.projectName ?? "",
        widget.patientLabOrder!.orderDate!,
        "",
        widget.patientLabOrder!.nationalityFlagURL ?? "",
        widget.patientLabOrder!.doctorRate!,
        widget.patientLabOrder!.actualDoctorRate!,
        widget.patientLabOrder!.noOfPatientsRate!,
        projectViewModel.user.emailAddress!,
      ),
      onTap: widget.onTap!,
      // buttonColor: Color(0xFF09AA28),
      buttonTitle: TranslationBase.of(context).download,
      buttonIcon: "assets/images/svg/download_1.svg",
      showConfirmMessageDialog: widget.showConfirmMessageDialog,
      isDownload: true,
    );
  }

  Widget _buildLabResultsList(LabsViewModel model) {
    return ListView.separated(
      shrinkWrap: true,
      itemCount: model.labResultLists.length,
      physics: NeverScrollableScrollPhysics(),
      separatorBuilder: (_, __) => SizedBox(
        height: 26,
      ),
      itemBuilder: (context, index) {
        var data = model.labResultLists[index];
        return LabItem(key: ValueKey(data.filterName), item: data, patientLabOrders: widget.patientLabOrder);
      },
    );
  }

  Widget _buildSpecialResultsToggle() {
    return InkWell(
      onTap: () {
        setState(() {
          _isShowMore = !_isShowMore;
        });
      },
      child: Container(
        padding: EdgeInsets.only(left: 17, top: 14, right: 13, bottom: 10),
        margin: EdgeInsets.only(left: 21, right: 21, top: 12),
        decoration: BoxDecoration(
          shape: BoxShape.rectangle,
          color: Colors.white,
          borderRadius: BorderRadius.all(
            Radius.circular(10.0),
          ),
          boxShadow: [
            BoxShadow(
              color: Color(0xff000000).withOpacity(.05),
              blurRadius: 27,
              offset: Offset(0, -3),
            ),
          ],
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Row(
              children: <Widget>[
                Expanded(
                  child: Text(
                    TranslationBase.of(context).specialResult,
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                      color: Color(0xff2E303A),
                      letterSpacing: -0.64,
                      height: 25 / 16,
                    ),
                  ),
                ),
                Icon(
                  _isShowMore ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
                  color: Color(0xff575757),
                  size: 22,
                ),
              ],
            ),
            if (_isShowMore)
              Container(
                width: double.infinity,
                child: Html(
                  data: labSpecialResult ?? TranslationBase.of(context).noDataAvailable,
                ),
              ),
          ],
        ),
      ),
    );
  }
}
