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/user_provider.dart';
import 'package:test_sa/controllers/validator/validator.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/enums/user_types.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_text_form_field.dart';
import 'package:test_sa/views/widgets/loaders/lazy_loading.dart';
import 'package:test_sa/views/widgets/loaders/loading_manager.dart';
import 'package:test_sa/views/widgets/loaders/no_data_found.dart';


class GasRefillCommentsBottomSheet extends StatefulWidget {
  final String requestId;

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

  @override
  State<GasRefillCommentsBottomSheet> createState() => _GasRefillCommentsBottomSheetState();
}

class _GasRefillCommentsBottomSheetState extends State<GasRefillCommentsBottomSheet> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  late GasRefillCommentsProvider commentsProvider;
  String? text;

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

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

  @override
  Widget build(BuildContext context) {
    commentsProvider = Provider.of<GasRefillCommentsProvider>(context);
    final userProvider = Provider.of<UserProvider>(context, listen: false);
    return Container(
      height: MediaQuery.of(context).size.height * 0.6,
      clipBehavior: Clip.antiAlias,
      margin: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
      decoration: BoxDecoration(
        color: Theme.of(context).scaffoldBackgroundColor,
        borderRadius: const BorderRadius.only(topRight: Radius.circular(20), topLeft: Radius.circular(20)),
      ),
      padding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth, vertical: 8.toScreenHeight),
      child: Form(
        key: _formKey,
        child: Column(
          children: [
            Container(
              width: 40.toScreenWidth,
              height: 5.toScreenHeight,
              decoration: BoxDecoration(color: AppColor.neutral40, borderRadius: BorderRadius.circular(30)),
            ),
            16.height,
            Align(
              alignment: AlignmentDirectional.centerStart,
              child: context.translation.comments.heading3(context).custom(fontWeight: FontWeight.w600),
            ),
            LoadingManager(
              isLoading: commentsProvider.isLoading,
              isFailedLoading: commentsProvider.comments == null,
              stateCode: commentsProvider.stateCode,
              onRefresh: () async {
                commentsProvider.reset();
                await commentsProvider.getComments(callId: widget.requestId);
              },
              child: commentsProvider.comments.isEmpty
                  ? SizedBox(
                      height: MediaQuery.of(context).size.height * 0.25,
                      child: NoDataFound(message: context.translation.noDataFound),
                    )
                  : LazyLoading(
                      nextPage: commentsProvider.nextPage,
                      onLazyLoad: () async => await commentsProvider.getComments(callId: widget.requestId),
                      child: ListView.separated(
                        itemCount: commentsProvider.comments.length,
                        padding: const EdgeInsets.only(top: 16, bottom: 8),
                        // shrinkWrap: true,
                        // physics: const NeverScrollableScrollPhysics(),
                        separatorBuilder: (cxt, index) => 8.height,
                        itemBuilder: (context, itemIndex) {
                          final model = commentsProvider.comments[itemIndex];
                          return Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              (model.createdBy?.userName ?? "Nurse").heading6(context),
                              // 8.height,
                              (model.comment ?? "").bodyText(context),
                              //8.height,
                              Align(
                                alignment: AlignmentDirectional.bottomEnd,
                                child: Text(DateTime.tryParse(model.createdOn!)!.toIso8601String().toServiceRequestDetailsFormat,
                                    style: AppTextStyles.tinyFont.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.neutral50)),
                              ),
                            ],
                          ).toShadowContainer(context);
                        },
                      ),
                    ),
            ).expanded,
            if (userProvider.user!.type == UsersTypes.normal_user) 8.height,
            if (userProvider.user!.type == UsersTypes.normal_user)
              AppTextFormField(
                labelText: "Type any comment",
                backgroundColor: AppColor.neutral30,
                alignLabelWithHint: true,
                showShadow: false,
                validator: (value) => Validator.hasValue(value) ? null : context.translation.requiredField,
                textInputType: TextInputType.multiline,
                suffixIcon: "comment_send".toSvgAsset().paddingOnly(end: 16).onPress(() {
                  if (_formKey.currentState!.validate()) {
                    _formKey.currentState!.save();
                    // final comment = GasRefillComment(id: 0, gasRefillId: num.tryParse(widget.requestId ?? ""), comment: text);
                    commentsProvider.addComment(context, comment: text!, id: int.parse(widget.requestId));
                  }
                }),
                onSaved: (value) {
                  text = value;
                },
              ),
            16.height,
          ],
        ),
      ),
    );
  }
}
