import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/gas_refill_comments.dart';
import 'package:test_sa/controllers/providers/api/gas_refill_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/widget_extensions.dart';
import 'package:test_sa/views/pages/user/gas_refill/request_gas_refill.dart';
import 'package:test_sa/views/widgets/loaders/app_loading.dart';
import 'package:test_sa/views/widgets/loaders/no_data_found.dart';

import '../../../../extensions/text_extensions.dart';
import '../../../../models/enums/user_types.dart';
import '../../../../models/new_models/gas_refill_model.dart';
import '../../../../new_views/app_style/app_color.dart';
import '../../../../new_views/common_widgets/default_app_bar.dart';
import '../../../widgets/requests/request_status.dart';
import 'gas_refill_comments.dart';

class GasRefillDetailsPage extends StatefulWidget {
  GasRefillModel model;
  String? priority, date;

  GasRefillDetailsPage({Key? key, this.priority, this.date, required this.model}) : super(key: key);

  @override
  State<GasRefillDetailsPage> createState() => _GasRefillDetailsPageState();
}

class _GasRefillDetailsPageState extends State<GasRefillDetailsPage> {
  GasRefillModel _model = GasRefillModel(gazRefillDetails: []);
  late UserProvider _userProvider;
  late GasRefillProvider gasRefillProvider;
  final bool _isLoading = false;

  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  void initState() {
    // _model.fromGasRefillModel(gasRefillModel);
    super.initState();
    Provider.of<GasRefillCommentsProvider>(context, listen: false).reset();
  }

  @override
  Widget build(BuildContext context) {
    _userProvider = Provider.of<UserProvider>(context);
    gasRefillProvider = Provider.of<GasRefillProvider>(context);

    return Scaffold(
      appBar: DefaultAppBar(title: context.translation.gasRefillDetails),
      key: _scaffoldKey,
      body: SafeArea(
        child: FutureBuilder(
          future: gasRefillProvider.getGasRefillObjectById(widget.model.id!),
          builder: (context, snap) {
            if (snap.connectionState == ConnectionState.waiting) {
              return const ALoading();
            } else if (snap.hasData) {
              _model = snap.data as GasRefillModel;
              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SingleChildScrollView(
                    padding: const EdgeInsets.all(16),
                    child: informationCard(_model),
                  ).expanded,
                ],
              );
            }
            return NoDataFound(message: context.translation.noDataFound).center;
          },
        ),
      ),
    );
  }

  Widget informationCard(GasRefillModel gasRefillModel) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    if (widget.priority != null)
                      StatusLabel(
                        label: widget.priority,
                        textColor: AppColor.getRequestStatusTextColorByName(context, widget.priority!),
                        backgroundColor: AppColor.getRequestStatusColorByName(context, widget.priority!),
                      ),
                    8.width,
                    StatusLabel(
                      label: gasRefillModel.status?.name ?? "",
                      textColor: AppColor.getRequestStatusTextColorByName(context, gasRefillModel.status?.name ?? ""),
                      backgroundColor: AppColor.getRequestStatusColorByName(context, gasRefillModel.status?.name ?? ""),
                    ),
                  ],
                ),
                8.height,
                context.translation.gasRefillRequest.heading5(context),
                8.height,

                '${context.translation.gasRequest}: ${gasRefillModel.gazRefillDetails![0].gasType?.name}'.bodyText(context),
                '${context.translation.cylinderType}: ${gasRefillModel.gazRefillDetails![0].cylinderType?.name}'.bodyText(context),
                '${context.translation.cylinderSize}: ${gasRefillModel.gazRefillDetails![0].cylinderSize?.name}'.bodyText(context),
                '${context.translation.site}: ${gasRefillModel.site?.name?.cleanupWhitespace.capitalizeFirstOfEach}'.bodyText(context),
                '${context.translation.department}: ${gasRefillModel.department?.name?.cleanupWhitespace.capitalizeFirstOfEach}'.bodyText(context),
                '${context.translation.requestNo}: ${gasRefillModel.gazRefillNo}'.bodyText(context),
                //TODO need to confirm where to display this new data...
                infoText(label:context.translation.gasRequest ,value:gasRefillModel.extensionNo ),
                infoText(label:context.translation.employeeId ,value:gasRefillModel.employeeId ),
                infoText(label:context.translation.name ,value:gasRefillModel.name ),
                infoText(label:context.translation.createdDate ,value:gasRefillModel.createdDate?.toInitialVisitCardFormat),

                const Divider().defaultStyle(context),
                '${context.translation.requestedQuantity}: ${gasRefillModel.gazRefillDetails![0].requestedQty ?? 0}'.bodyText(context),
                '${context.translation.deliveredQuantity}: ${gasRefillModel.gazRefillDetails![0].deliverdQty ?? 0}'.bodyText(context),
                8.height,
                if (gasRefillModel.comment?.isNotEmpty ?? false) ...[
                  const Divider().defaultStyle(context),
                  gasRefillModel.comment!.bodyText(context),
                  8.height,
                ]
              ],
            ).expanded,
            Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                if (_userProvider.user!.type == UsersTypes.engineer && (gasRefillModel.status?.value ?? 0) != 2)
                  "edit".toSvgAsset(height: 48, width: 48).onPress(
                    () async {
                      _model.fromGasRefillModel(gasRefillModel);
                      // setState(() {});
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => RequestGasRefill(gasRefillModel: gasRefillModel),
                        ),
                      ).then((value) {
                        if (value != null) {
                          _model = value;
                          setState(() {});
                        }
                      });
                    },
                  ),
                if (_userProvider.user!.type == UsersTypes.engineer && (gasRefillModel.status?.value ?? 0) != 2) 8.height,
                Text(
                  (widget.date ?? gasRefillModel.expectedDate)?.toServiceRequestCardFormat ?? "",
                  textAlign: TextAlign.end,
                  style: AppTextStyles.tinyFont.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.neutral50),
                ),
              ],
            ),
          ],
        ).paddingOnly(top: 16, start: 16, end: 16),

        /// TBD
        (_userProvider.user!.type == UsersTypes.normal_user
                ? Container(
                    height: 50,
                    padding: const EdgeInsets.only(left: 16, right: 16),
                    alignment: Alignment.center,
                    width: double.infinity,
                    decoration: ShapeDecoration(
                      color: context.isDark ? AppColor.neutral50 : AppColor.neutral30,
                      shape: const RoundedRectangleBorder(
                        borderRadius: BorderRadius.only(
                          bottomLeft: Radius.circular(14),
                          bottomRight: Radius.circular(14),
                        ),
                      ),
                    ),
                    child: Row(
                      children: [
                        Text(
                          '${context.translation.commentHere}...',
                          style: AppTextStyles.heading6.copyWith(
                            color: (context.isDark ? AppColor.neutral30 : AppColor.neutral50).withOpacity(.6),
                          ),
                        ).expanded,
                        "comment_send".toSvgAsset(width: 24, color: context.isDark ? AppColor.primary50 : AppColor.primary70),
                      ],
                    ),
                  )
                : Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Divider().defaultStyle(context),
                      8.height,
                      Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text(
                            context.translation.viewComments,
                            style: AppTextStyles.bodyText.copyWith(color: AppColor.blueStatus(context)),
                          ),
                          4.width,
                          Icon(
                            Icons.arrow_forward,
                            color: AppColor.blueStatus(context),
                            size: 14,
                          )
                        ],
                      ),
                    ],
                  ).paddingOnly(bottom: 16, start: 16, end: 16))
            .onPress(() {
          showModalBottomSheet(
            context: context,
            useSafeArea: true,
            isScrollControlled: true,
            useRootNavigator: true,
            backgroundColor: Colors.transparent,
            builder: (context) => GasRefillCommentsBottomSheet(requestId: gasRefillModel.id.toString()),
          );
        }),
      ],
    ).toShadowContainer(context, padding: 0);
  }

  Widget infoText({String ?label,String ?value,}){
    if(value==null||value.isEmpty){
      return const  SizedBox();
    }
    else {
      return '$label: $value'.bodyText(context);
    }

  }
}
