import 'package:flutter/material.dart';
import 'package:provider/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/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/models/enums/user_types.dart';
import 'package:test_sa/models/enums/work_order_next_step.dart';
import 'package:test_sa/models/helper_data_models/workorder/work_order_helper_models.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.dart';
import 'package:test_sa/service_request_latest/service_request_detail_provider.dart';
import 'package:test_sa/service_request_latest/views/components/bottom_sheets/service_request_bottomsheet.dart';
import 'package:test_sa/service_request_latest/views/components/history_log_view.dart';
import 'components/service_request_detail_view.dart';

class ServiceRequestDetailMain extends StatefulWidget {
  final int requestId;

  ServiceRequestDetailMain({Key? key, required this.requestId}) : super(key: key);

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

class _ServiceRequestDetailMainState extends State<ServiceRequestDetailMain> {
  late ServiceRequestDetailProvider _requestProvider;

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

  Future<void> getInitialData() async{
    bool isNurse = (Provider.of<UserProvider>(context, listen: false).user?.type) == UsersTypes.normal_user;
    _requestProvider = Provider.of<ServiceRequestDetailProvider>(context,   listen: false);
    await _requestProvider.getWorkOrderById(id: widget.requestId);
    if (isNurse && (_requestProvider.currentWorkOrder?.data?.nextStep?.workOrderNextStepEnum == WorkOrderNextStepEnum.waitingForRequesterToConfirm)) {
      ServiceRequestBottomSheet.nurseVerifyArrivalBottomSheet(context: context);
    }
    _requestProvider.needVisitHelperModel = NeedVisitHelperModel(
        workOrderId: _requestProvider.currentWorkOrder?.data?.requestId,
        visitDate: _requestProvider.currentWorkOrder?.data?.needAVisitDateTime,
        comment: _requestProvider.currentWorkOrder?.data?.needAVisitComment,
      );
  }

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

  Future<void> stopTimer() async {
    ServiceRequestDetailProvider requestDetailProvider = Provider.of<ServiceRequestDetailProvider>(context, listen: false);
    if (requestDetailProvider.timer != null && requestDetailProvider.timer!.isActive) {
      requestDetailProvider.stopTimer();
    }
  }

  @override
  Widget build(BuildContext context) {
    bool isNurse = (Provider.of<UserProvider>(context, listen: false).user?.type) == UsersTypes.normal_user;
    return WillPopScope(
      onWillPop: () async {
        stopTimer();
        return true;
      },
      child: Scaffold(
        backgroundColor: AppColor.neutral100,
        appBar: DefaultAppBar(
          title: context.translation.cmDetails,
          onBackPress: () {
            stopTimer();
            Navigator.pop(context);
          },
          actions: [
            isNurse
                ? IconButton(
                    icon: 'qr'.toSvgAsset(
                      height: 24,
                      width: 24,
                    ),
                    onPressed: () {
                      ServiceRequestBottomSheet.getQRCodeBottomSheet(context: context);
                    },
                  )
                : IconButton(
                    icon: const Icon(Icons.home),
                    onPressed: () {
                      // stopTimer();
                      Navigator.pop(context);
                    },
                  ),
          ],
        ),
        body: DefaultTabController(
          length: 2,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Container(
                margin: EdgeInsets.only(left: 16.toScreenWidth, right: 16.toScreenWidth, top: 12.toScreenHeight),
                decoration: BoxDecoration(color: context.isDark ? AppColor.neutral50 : AppColor.white10, borderRadius: BorderRadius.circular(10)),
                child: TabBar(
                  //controller: _tabController,
                  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,
                  indicator: BoxDecoration(color: context.isDark ? AppColor.neutral60 : AppColor.neutral110, borderRadius: BorderRadius.circular(7)),
                  onTap: (index) {
                    // setState(() {});
                  },
                  tabs: [
                    Tab(text: context.translation.details, height: 57.toScreenHeight),
                    Tab(text: context.translation.historyLogs, height: 57.toScreenHeight),
                  ],
                ),
              ),
              12.height,
               TabBarView(
                children: [
                  ServiceRequestDetailView(),
                  const  HistoryLogView(),
                ],
              ).expanded,
            ],
          ),
        ),
      ),
    );
  }
}
