import 'package:hmg_patient_app/config/shared_pref_kay.dart';
import 'package:hmg_patient_app/core/model/ImagesInfo.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/models/FamilyFiles/PatientERVirtualHistoryResponse.dart';
import 'package:hmg_patient_app/pages/livecare/widgets/LiveCarePendingRequest.dart';
import 'package:hmg_patient_app/pages/livecare/widgets/clinic_list.dart';
import 'package:hmg_patient_app/pages/livecare/widgets/livecare_logs.dart';
import 'package:hmg_patient_app/services/livecare_services/livecare_provider.dart';
import 'package:hmg_patient_app/uitl/app_shared_preferences.dart';
import 'package:hmg_patient_app/uitl/app_toast.dart';
import 'package:hmg_patient_app/uitl/gif_loader_dialog_utils.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:hmg_patient_app/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class LiveCareHome extends StatefulWidget {
  static bool showFooterButton = true;
  static bool isLiveCareTypeSelected = false;
  final bool isPharmacyLiveCare;
  final String pharmacyLiveCareQRCode;

  const LiveCareHome({Key? key, this.isPharmacyLiveCare = false, this.pharmacyLiveCareQRCode = ""}) : super(key: key);

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

class _LiveCareHomeState extends State<LiveCareHome> with SingleTickerProviderStateMixin {
  late TabController _tabController;

  bool isDataLoaded = false;
  bool hasLiveCareRequest = false;
  List<ImagesInfo> imagesInfo =[];

  late List<ErRequestHistoryList> erRequestHistoryList;

  late ErRequestHistoryList pendingERRequestHistoryList;

  late ProjectViewModel projectViewModel;
  AppSharedPreferences sharedPref = AppSharedPreferences();

  @override
  void initState() {
    _tabController = new TabController(length: 2, vsync: this);
    erRequestHistoryList =[];
    LiveCareHome.isLiveCareTypeSelected = false;
    pendingERRequestHistoryList = new ErRequestHistoryList();
    imagesInfo.add(ImagesInfo(
        imageEn: 'https://hmgwebservices.com/Images/MobileApp/imges-info/er-consultation_en/en/0.png', imageAr: 'https://hmgwebservices.com/Images/MobileApp/imges-info/er-consultation_ar/ar/0.png'));
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!isDataLoaded && projectViewModel.isLogin) getLiveCareHistory();
    });

    super.initState();
  }

  @override
  void dispose() {
    LiveCareHome.isLiveCareTypeSelected = false;
    sharedPref.remove(LIVECARE_CLINIC_DATA);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    return AppScaffold(
      appBarTitle: TranslationBase.of(context).livecare,
      isShowAppBar: true,
      showNewAppBarTitle: true,
      showNewAppBar: true,
      imagesInfo: imagesInfo,
      description: TranslationBase.of(context).erConsultation,
      body: Container(
        child: Column(children: [
          TabBar(
            controller: _tabController,
            indicatorWeight: 3.0,
            indicatorSize: TabBarIndicatorSize.tab,
            labelColor: Color(0xff2B353E),
            unselectedLabelColor: Color(0xff575757),
            labelPadding: EdgeInsets.only(top: 0, bottom: 0, left: 20, right: 20),
            labelStyle: TextStyle(
              fontFamily: projectViewModel.isArabic ? 'Cairo' : 'Poppins',
              fontSize: 16,
              fontWeight: FontWeight.w600,
              letterSpacing: -0.48,
            ),
            unselectedLabelStyle: TextStyle(
              fontFamily: projectViewModel.isArabic ? 'Cairo' : 'Poppins',
              fontSize: 16,
              fontWeight: FontWeight.w600,
              letterSpacing: -0.48,
            ),
            tabs: [
              Tab(
                child: Text(
                  TranslationBase.of(context).consultation,
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 14,
                    letterSpacing: -0.36,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
              Tab(
                child: Text(
                  TranslationBase.of(context).logs,
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 14,
                    letterSpacing: -0.36,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            ],
          ),
          Expanded(
            child: TabBarView(
              physics: NeverScrollableScrollPhysics(),
              children: [
                isDataLoaded && !hasLiveCareRequest
                    ? ClinicList(
                        getLiveCareHistory: getLiveCareHistory,
                        isPharmacyLiveCare: widget.isPharmacyLiveCare,
                        pharmacyLiveCareQRCode: widget.pharmacyLiveCareQRCode,
                      )
                    : isDataLoaded
                        ? LiveCarePendingRequest(getLiveCareHistory: getLiveCareHistory, pendingERRequestHistoryList: pendingERRequestHistoryList)
                        : Container(),
                isDataLoaded
                    ? LiveCareLogs(
                        erRequestHistoryList: erRequestHistoryList,
                      )
                    : Container(),
              ],
              controller: _tabController,
            ),
          ),
        ]),
      ),
    );
  }

  void getLiveCareHistory() {
    GifLoaderDialogUtils.showMyDialog(context);
    setState(() {
      isDataLoaded = false;
      hasLiveCareRequest = false;
    });
    LiveCareService service = new LiveCareService();
    PatientERVirtualHistoryResponse patientERVirtualHistoryResponse = new PatientERVirtualHistoryResponse();
    service.getLivecareHistory(context).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      setState(() {
        if (res['ErRequestHistoryList'].length != 0) {
          patientERVirtualHistoryResponse = PatientERVirtualHistoryResponse.fromJson(res as Map<String, dynamic>);
          erRequestHistoryList = patientERVirtualHistoryResponse.erRequestHistoryList!;

          if (patientERVirtualHistoryResponse.erRequestHistoryList![0].callStatus! < 4) {
            pendingERRequestHistoryList = patientERVirtualHistoryResponse.erRequestHistoryList![0];
            hasLiveCareRequest = true;
          } else {
            hasLiveCareRequest = false;
          }
        }
        isDataLoaded = true;
      });
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err, localContext: context);
      print(err);
    });
  }
}
