import 'dart:io';

import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/Notifiers/PendingComplaintsProvider.dart';
import 'package:generp/Utils/app_colors.dart';
import 'package:generp/Utils/commonWidgets.dart';
import 'package:provider/provider.dart';

import '../../Utils/dropdownTheme.dart';

class Updatecomplaints extends StatefulWidget {
  final ComplaintID;
  const Updatecomplaints({super.key, required this.ComplaintID});

  @override
  State<Updatecomplaints> createState() => _UpdatecomplaintsState();
}

class _UpdatecomplaintsState extends State<Updatecomplaints> {
  Dropdowntheme ddtheme = Dropdowntheme();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final provider = Provider.of<Pendingcomplaintsprovider>(
        context,
        listen: false,
      );
      provider.checkDropDownSelected();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<Pendingcomplaintsprovider>(
      builder: (context, provider, child) {
        return WillPopScope(
          onWillPop: () {
            provider.submitLoading = false;
            provider.resetAll();
            return onBackPressed(context);
          },
          child: SafeArea(
            top: false,
            bottom: Platform.isIOS ? false : true,
            child: Scaffold(
              resizeToAvoidBottomInset: true,
              appBar: appbar2(
                context,
                "Update Complaint",
                provider.resetAll,
                SizedBox(width: 0),
              ),
              backgroundColor: AppColors.scaffold_bg_color,
              body: Container(
                padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(20),
                ),
                child: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      SizedBox(height: 15),

                      Padding(
                        padding: const EdgeInsets.only(bottom: 5.0),
                        child: Text(
                          "Complaint Status",
                          style: TextStyle(
                            fontFamily: "JakartaMedium",
                            color: AppColors.semi_black,
                          ),
                        ),
                      ),
                      DropdownButtonHideUnderline(
                        child: Row(
                          children: [
                            Expanded(
                              child: DropdownButton2<String>(
                                isExpanded: true,
                                hint: const Row(
                                  children: [
                                    Expanded(
                                      child: Text(
                                        'Select Complaint Status',
                                        style: TextStyle(fontSize: 14),
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ),
                                  ],
                                ),
                                items:
                                    provider.CompletedStatus.map(
                                      (complaintStatus) =>
                                          DropdownMenuItem<String>(
                                            value: complaintStatus['name'],
                                            child: Text(
                                              complaintStatus['name'] ?? '',
                                              style: const TextStyle(
                                                fontSize: 14,
                                              ),
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                          ),
                                    ).toList(),
                                value: provider.statusID,
                                onChanged: (value) {
                                  if (value != null) {
                                    provider.statusID = value;
                                    provider.statusError = "";
                                    print("statusId:${provider.statusID}");
                                  }
                                },
                                buttonStyleData: ddtheme.buttonStyleData,
                                iconStyleData: ddtheme.iconStyleData,
                                menuItemStyleData: ddtheme.menuItemStyleData,
                                dropdownStyleData: ddtheme.dropdownStyleData,
                              ),
                            ),
                          ],
                        ),
                      ),
                      SizedBox(height: 5),
                      ErrorWidget(context, provider.statusError),
                      Padding(
                        padding: const EdgeInsets.only(bottom: 5.0),
                        child: Text(
                          "FSR Number",
                          style: TextStyle(
                            fontFamily: "JakartaMedium",
                            color: AppColors.semi_black,
                          ),
                        ),
                      ),
                      Container(
                        height: 50,

                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          color: AppColors.text_field_color,
                          borderRadius: BorderRadius.circular(14),
                        ),
                        child: Padding(
                          padding: const EdgeInsets.fromLTRB(10.0, 0.0, 10, 0),
                          child: TextFormField(
                            controller: provider.fsrNumberController,
                            keyboardType: TextInputType.text,
                            onChanged: (value) {
                              provider.fsrError = "";
                            },
                            decoration: InputDecoration(
                              hintText: "Enter FSR Number",
                              hintStyle: TextStyle(
                                fontWeight: FontWeight.w400,
                                color: Color(0xFFB4BEC0),
                                fontSize: 14,
                              ),

                              enabledBorder: InputBorder.none,
                              focusedBorder: InputBorder.none,
                            ),
                          ),
                        ),
                      ),
                      SizedBox(height: 5),
                      ErrorWidget(context, provider.fsrError),

                      Row(
                        children: [
                          Expanded(
                            child: Padding(
                              padding: const EdgeInsets.symmetric(
                                horizontal: 5.0,
                                vertical: 3,
                              ),
                              child: Text(
                                "Select Time",
                                style: TextStyle(
                                  fontFamily: "JakartaMedium",
                                  color: AppColors.semi_black,
                                ),
                              ),
                            ),
                          ),
                          Expanded(
                            child: Padding(
                              padding: const EdgeInsets.symmetric(
                                horizontal: 20.0,
                              ),
                              child: Text(
                                "Running Hours",
                                style: TextStyle(
                                  fontWeight: FontWeight.w400,
                                  color: AppColors.semi_black,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),

                      Row(
                        children: [
                          Expanded(
                            child: Container(
                              decoration: BoxDecoration(
                                color: AppColors.text_field_color,
                                borderRadius: BorderRadius.circular(14),
                              ),
                              child: InkWell(
                                onTap: () {
                                  provider.selectTime(context);
                                },
                                child: Container(
                                  alignment: Alignment.center,
                                  height: 45,
                                  margin: EdgeInsets.only(
                                    left: 15.0,
                                    right: 15.0,
                                  ),
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(15.0),
                                  ),
                                  child: Row(
                                    children: [
                                      Text(
                                        "${provider.selectedTime.hour}:${provider.selectedTime.minute}" ??
                                            "Enter in Time",
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                          fontWeight: FontWeight.w400,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            ),
                          ),
                          SizedBox(width: 10),
                          Expanded(
                            child: Container(
                              height: 50,

                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                color: AppColors.text_field_color,
                                borderRadius: BorderRadius.circular(14),
                              ),
                              child: Padding(
                                padding: const EdgeInsets.fromLTRB(
                                  10.0,
                                  0.0,
                                  10,
                                  0,
                                ),
                                child: TextFormField(
                                  controller: provider.runningHoursController,
                                  keyboardType: TextInputType.text,
                                  onChanged: (value) {
                                    provider.runningHoursError = "";
                                  },
                                  decoration: InputDecoration(
                                    hintText: "Enter Running Hours",
                                    hintStyle: TextStyle(
                                      fontWeight: FontWeight.w400,
                                      color: Color(0xFFB4BEC0),
                                      fontSize: 14,
                                    ),
                                    enabledBorder: InputBorder.none,
                                    focusedBorder: InputBorder.none,
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                      Row(
                        children: [
                          Expanded(child: SizedBox()),
                          SizedBox(width: 10),
                          Expanded(
                            child: ErrorWidget(
                              context,
                              provider.runningHoursError,
                            ),
                          ),
                        ],
                      ),
                      InkResponse(
                        onTap: () {
                          _showAttachmentSheet(context);
                        },
                        child: Container(
                          margin: EdgeInsets.symmetric(vertical: 10),
                          height: 45,
                          width: MediaQuery.of(context).size.width,
                          decoration: BoxDecoration(
                            color: Color(0xFFE6F6FF),
                            borderRadius: BorderRadius.circular(12),
                            border: Border.all(
                              color: AppColors.app_blue,
                              width: 0.5,
                            ),
                          ),
                          child: Center(
                            child: Text(
                              "Scan Document",
                              style: TextStyle(color: AppColors.app_blue),
                            ),
                          ),
                        ),
                      ),
                      if (provider.imagePicked == 1 &&
                          provider.imagePath != null) ...[
                        Padding(
                          padding: const EdgeInsets.symmetric(vertical: 4.0),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                "${provider.imagePath}",
                                style: TextStyle(
                                  color: AppColors.semi_black,
                                  fontSize: 11,
                                  fontWeight: FontWeight.w600,
                                ),
                              ),
                              InkResponse(
                                onTap: () {
                                  provider.imagePicked = 0;
                                  provider.imagePath = null;
                                  provider.imageFilePath = null;
                                },
                                child: SvgPicture.asset(
                                  "assets/svg/ic_close.svg",
                                  width: 15,
                                  height: 15,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                      Padding(
                        padding: const EdgeInsets.only(bottom: 5.0),
                        child: Text(
                          "Feedback",
                          style: TextStyle(
                            fontFamily: "JakartaMedium",
                            color: AppColors.semi_black,
                          ),
                        ),
                      ),
                      Container(
                        height: 150,

                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          color: AppColors.text_field_color,
                          borderRadius: BorderRadius.circular(14),
                        ),
                        child: Padding(
                          padding: const EdgeInsets.fromLTRB(10.0, 0.0, 10, 0),
                          child: TextFormField(
                            controller: provider.feedbackController,
                            maxLines: 60,
                            keyboardType: TextInputType.text,
                            decoration: InputDecoration(
                              hintText: "Enter Feedback",
                              hintStyle: TextStyle(
                                fontWeight: FontWeight.w400,
                                color: Color(0xFFB4BEC0),
                                fontSize: 14,
                              ),
                              enabledBorder: InputBorder.none,
                              focusedBorder: InputBorder.none,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              floatingActionButtonLocation:
                  FloatingActionButtonLocation.centerFloat,
              floatingActionButton: InkResponse(
                onTap:
                    provider.submitLoading
                        ? null
                        : () {
                          provider.submitLoading = true;
                          provider.UpdateComplaintAPIFunction(
                            context,
                            widget.ComplaintID,
                            provider.feedbackController.text,
                            provider.fsrNumberController.text,
                            provider.runningHoursController.text,
                            provider.statusID,
                          );
                        },
                child: Container(
                  alignment: Alignment.center,
                  height: 45,
                  margin: EdgeInsets.only(
                    left: 5.0,
                    right: 5.0,
                    top: 5.0,
                    bottom: 5.0,
                  ),
                  decoration: BoxDecoration(
                    color: AppColors.app_blue, //1487C9
                    borderRadius: BorderRadius.circular(15.0),
                  ),
                  child: Center(
                    child:
                        provider.submitLoading
                            ? CircularProgressIndicator.adaptive(
                              valueColor: AlwaysStoppedAnimation<Color>(
                                AppColors.white,
                              ),
                            )
                            : Text(
                              "Submit",
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                fontSize: 15,
                                fontFamily: "JakartaMedium",
                                color: Colors.white,
                              ),
                            ),
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  Widget ErrorWidget(context, text) {
    if (text != null) {
      return Text(text!, style: TextStyle(color: Colors.red, fontSize: 12));
    } else {
      return SizedBox(height: 10);
    }
  }

  Future<void> _showAttachmentSheet(BuildContext context) {
    return showModalBottomSheet(
      useSafeArea: true,
      isDismissible: true,
      isScrollControlled: true,
      showDragHandle: true,
      backgroundColor: Colors.white,
      enableDrag: true,
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return SafeArea(
              child: Consumer<Pendingcomplaintsprovider>(
                builder: (context, provider, child) {
                  return Padding(
                    padding: EdgeInsets.only(
                      bottom:
                          MediaQuery.of(
                            context,
                          ).viewInsets.bottom, // This handles keyboard
                    ),
                    child: Container(
                      margin: EdgeInsets.only(
                        bottom: 15,
                        left: 15,
                        right: 15,
                        top: 10,
                      ),

                      child: SingleChildScrollView(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Align(
                              alignment: Alignment.center,
                              child: Text(
                                "Select Source",
                                style: TextStyle(
                                  color: AppColors.app_blue,
                                  fontSize: 16,
                                ),
                              ),
                            ),
                            SizedBox(height: 15),
                            InkWell(
                              onTap: () {
                                Navigator.of(context).pop(false);
                                provider.imgFromGallery();
                              },
                              child: SizedBox(
                                height: 35,
                                child: Text("Select photo from gallery"),
                              ),
                            ),
                            SizedBox(height: 10),
                            InkWell(
                              onTap: () {
                                Navigator.of(context).pop(false);
                                provider.imgFromCamera();
                              },
                              child: SizedBox(
                                height: 35,
                                child: Text("Capture photo from camera"),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }
}
