import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/Notifiers/PendingComplaintsProvider.dart';
import 'package:generp/Utils/commonWidgets.dart';
import 'package:generp/screens/screensExports.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../Utils/app_colors.dart';

import '../../Utils/commonServices.dart';
import 'UpdateComplaints.dart';

class Pendingcomplaints extends StatefulWidget {
  const Pendingcomplaints({super.key});

  @override
  State<Pendingcomplaints> createState() => _PendingcomplaintsState();
}

class _PendingcomplaintsState extends State<Pendingcomplaints> {
  Map _source = {ConnectivityResult.mobile: true};
  final MyConnectivity _connectivity = MyConnectivity.instance;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _connectivity.initialise();
    _connectivity.myStream.listen((source) {
      setState(() => _source = source);
    });
    WidgetsBinding.instance.addPostFrameCallback((_) {
      var complaintsprovider = Provider.of<Pendingcomplaintsprovider>(
        context,
        listen: false,
      );
      complaintsprovider.TechnicianPendingComplaints(context);
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _connectivity.disposeStream();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    switch (_source.keys.toList()[0]) {
      case ConnectivityResult.mobile:
        connection = 'Online';
        break;
      case ConnectivityResult.wifi:
        connection = 'Online';
        break;
      case ConnectivityResult.none:
      default:
        connection = 'Offline';
    }
    return (connection == "Online")
        ? Platform.isAndroid
            ? WillPopScope(
              onWillPop: () => onBackPressed(context),
              child: SafeArea(
                top: false,
                bottom: true,
                child: _scaffold1(context),
              ),
            )
            : _scaffold1(context)
        : NoNetwork(context);
  }

  @override
  Widget _scaffold1(BuildContext context) {
    return Consumer<Pendingcomplaintsprovider>(
      builder: (context, provider, child) {
        return WillPopScope(
          onWillPop: () => onBackPressed(context),
          child: SafeArea(
            top: false,
            bottom: Platform.isIOS ? false : true,
            child: Scaffold(
              resizeToAvoidBottomInset: true,
              backgroundColor: AppColors.scaffold_bg_color,
              appBar: appbar2New(
                context,
                "Pending Complaints",
                provider.resetAll,
                InkResponse(
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => Scancomplaintdetails(),
                      ),
                    );
                  },
                  child: SvgPicture.asset("assets/svg/scanner.svg"),
                ),
                0xFFFFFFFF,
              ),
              body:
                  provider.technician_complaint_list.isNotEmpty
                      ? Container(
                        child: ListView.builder(
                          scrollDirection: Axis.vertical,
                          shrinkWrap: true,
                          itemCount: provider.technician_complaint_list.length,
                          padding: EdgeInsets.symmetric(
                            horizontal: 10,
                            vertical: 10,
                          ),

                          itemBuilder: (context, index) {
                            return InkResponse(
                              onTap: () {
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder:
                                        (context) => Visitdetails(
                                          from: "Pending Complaints",
                                          complaintID:
                                              provider
                                                  .technician_complaint_list[index]
                                                  .complaintId,
                                        ),
                                  ),
                                );
                              },
                              child: Container(

                                margin: EdgeInsets.symmetric(vertical: 5),
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(20),
                                ),
                                child: ClipRRect(
                                  borderRadius: BorderRadius.circular(20),
                                  child: Slidable(
                                    startActionPane: ActionPane(
                                      motion: const ScrollMotion(),
                                      key: ValueKey(
                                        provider
                                            .technician_complaint_list[index]
                                            .complaintId,
                                      ),
                                      dragDismissible: false,

                                      // dismissible: DismissiblePane(
                                      //
                                      //   onDismissed: () {},
                                      // closeOnCancel: true,
                                      // resizeDuration: Duration(milliseconds: 300),),
                                      children: [
                                        SlidableAction(
                                          onPressed: (context) async {
                                            var loc =
                                                provider
                                                    .technician_complaint_list[index]
                                                    .loc
                                                    ?.split(",")
                                                    .toString();
                                            var uri = Uri.parse(
                                              "google.navigation:q=${loc![0]},${loc![1]}&mode=d",
                                            );
                                            if (await canLaunch(
                                              uri.toString(),
                                            )) {
                                              await launch(uri.toString());
                                            } else {
                                              throw 'Could not launch ${uri.toString()}';
                                            }
                                          },

                                          backgroundColor: Color(0xFFFFF8E5),
                                          foregroundColor: Color(0xFFFFB600),
                                          icon: Icons.location_history,
                                          label: 'Location',
                                        ),
                                        SlidableAction(
                                          onPressed: (context) async {
                                            Navigator.push(
                                              context,
                                              MaterialPageRoute(
                                                builder:
                                                    (context) => Updatecomplaints(
                                                  ComplaintID: provider
                                                      .technician_complaint_list[index]
                                                      .complaintId,
                                                ),
                                              ),
                                            );
                                          },
                                          backgroundColor: Color(0xFFE6F6FF),
                                          foregroundColor: AppColors.app_blue,
                                          icon: Icons.note_add,
                                          label: 'Update Complaint',
                                        ),
                                      ],
                                    ),
                                    endActionPane: ActionPane(
                                      motion: const ScrollMotion(),
                                      key: ValueKey(
                                        provider
                                            .technician_complaint_list[index]
                                            .complaintId,
                                      ),
                                      dragDismissible: false,

                                      // dismissible: DismissiblePane(
                                      //
                                      //   onDismissed: () {},
                                      // closeOnCancel: true,
                                      // resizeDuration: Duration(milliseconds: 300),),
                                      children: [
                                        SlidableAction(
                                          onPressed: (context) {
                                            Navigator.push(
                                              context,
                                              MaterialPageRoute(
                                                builder:
                                                    (context) => Paymentdetails(
                                                      accountName: "Generator",
                                                      name:
                                                          provider
                                                              .technician_complaint_list[index]
                                                              .companyName,
                                                      genId:
                                                          provider
                                                              .technician_complaint_list[index]
                                                              .genId,
                                                      referenceID:
                                                          provider
                                                              .technician_complaint_list[index]
                                                              .complaintId,
                                                    ),
                                              ),
                                            );
                                          },
                                          backgroundColor: Color(0xFFE7FFE5),
                                          foregroundColor: Color(0xFF0D9C00),
                                          icon: Icons.add,
                                          label: 'Payment Details',
                                        ),
                                      ],
                                    ),
                                    child: Container(
                                      margin: EdgeInsets.symmetric(vertical: 5),
                                      padding: EdgeInsets.symmetric(
                                        horizontal: 10,
                                        vertical: 0,
                                      ),
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          Row(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.center,
                                            mainAxisAlignment:
                                                MainAxisAlignment.center,
                                            children: [
                                              Expanded(
                                                flex: 1,
                                                child: Container(
                                                  padding: EdgeInsets.symmetric(
                                                    horizontal: 10,
                                                    vertical: 10,
                                                  ),
                                                  decoration: BoxDecoration(
                                                    color: Color(0xFFE6F6FF),
                                                    shape: BoxShape.circle,
                                                  ),
                                                  child: SvgPicture.asset(
                                                    width: 30,
                                                    height: 30,
                                                    "assets/svg/se_block_head.svg",
                                                  ),
                                                ),
                                              ),
                                              SizedBox(width: 5),

                                              Expanded(
                                                flex: 4,
                                                child: Column(
                                                  crossAxisAlignment:
                                                      CrossAxisAlignment.start,
                                                  children: [
                                                    Text(
                                                      "${provider.technician_complaint_list[index].contactName}",
                                                      maxLines: 1,
                                                      overflow:
                                                          TextOverflow.ellipsis,
                                                      style: TextStyle(
                                                        fontFamily:
                                                            "JakartaMedium",
                                                      ),
                                                    ),
                                                    Text(
                                                      "${provider.technician_complaint_list[index].companyName}",
                                                      maxLines: 1,
                                                      overflow:
                                                          TextOverflow.ellipsis,
                                                      style: TextStyle(
                                                        color: Color(
                                                          0xFF818181,
                                                        ),
                                                        fontSize: 14,
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                              Spacer(),
                                              Expanded(
                                                flex: 1,
                                                child: InkResponse(
                                                  onTap: () {
                                                    launch(
                                                      'tel://${provider.technician_complaint_list[index].mobileNo}',
                                                    );
                                                  },
                                                  child: SvgPicture.asset(
                                                    "assets/svg/se_call_customer.svg",
                                                    color: Color(0xFF0D9C00),
                                                    height: 20,
                                                    width: 20,
                                                  ),
                                                ),
                                              ),
                                              Expanded(
                                                flex: 1,
                                                child: InkResponse(
                                                  onTap: () {
                                                    _showOptionsSheet(
                                                      context,
                                                      provider
                                                          .technician_complaint_list[index]
                                                          .companyName,

                                                      provider
                                                          .technician_complaint_list[index]
                                                          .genId,
                                                      provider
                                                          .technician_complaint_list[index]
                                                          .complaintId,
                                                    );
                                                  },
                                                  child: SvgPicture.asset(
                                                    "assets/svg/ic_more.svg",
                                                    height: 30,
                                                  ),
                                                ),
                                              ),
                                            ],
                                          ),

                                          // Divider(
                                          //   thickness: 0.5,
                                          //   color: Color(0xFFD7D7D7),
                                          // ),
                                          // ...List.generate(4, (j) {
                                          //   final textheads = [
                                          //     "Complaint ID",
                                          //     "Product Name",
                                          //
                                          //     "Engine Number",
                                          //     "Address",
                                          //   ];
                                          //   final textSubheads = [
                                          //     provider
                                          //         .technician_complaint_list[index]
                                          //         .complaintId,
                                          //     provider
                                          //         .technician_complaint_list[index]
                                          //         .productName,
                                          //     provider
                                          //         .technician_complaint_list[index]
                                          //         .engineNo,
                                          //     provider
                                          //         .technician_complaint_list[index]
                                          //         .address,
                                          //   ];
                                          //   return Container(
                                          //     padding: EdgeInsets.symmetric(
                                          //       vertical: 3,
                                          //     ),
                                          //     child: Row(
                                          //       crossAxisAlignment:
                                          //           CrossAxisAlignment.start,
                                          //       children: [
                                          //         Expanded(
                                          //           flex: 1,
                                          //           child: Text(
                                          //             textheads[j].toString(),
                                          //             style: TextStyle(
                                          //               fontFamily: "JakartaMedium",
                                          //             ),
                                          //           ),
                                          //         ),
                                          //         Expanded(
                                          //           flex: 2,
                                          //           child: Text(
                                          //             textSubheads[j].toString(),
                                          //             style: TextStyle(
                                          //               color: Color(0xFF818181),
                                          //             ),
                                          //           ),
                                          //         ),
                                          //       ],
                                          //     ),
                                          //   );
                                          // }),
                                        ],
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            );
                          },
                        ),
                      )
                      : Emptywidget(context),
            ),
          ),
        );
      },
    );
  }

  @override
  Widget _scaffold(BuildContext context) {
    return Consumer<Pendingcomplaintsprovider>(
      builder: (context, provider, child) {
        return WillPopScope(
          onWillPop: () => onBackPressed(context),
          child: SafeArea(
            top: false,
            bottom: Platform.isIOS ? false : true,
            child: Scaffold(
              resizeToAvoidBottomInset: true,
              backgroundColor: AppColors.scaffold_bg_color,
              appBar: appbar2(
                context,
                "Pending Complaints",
                provider.resetAll,
                InkResponse(
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => Scancomplaintdetails(),
                      ),
                    );
                  },
                  child: SvgPicture.asset("assets/svg/scanner.svg"),
                ),
              ),
              body:
                  provider.technician_complaint_list.isNotEmpty
                      ? Container(
                        child: ListView.builder(
                          scrollDirection: Axis.vertical,
                          shrinkWrap: true,
                          itemCount: provider.technician_complaint_list.length,
                          padding: EdgeInsets.symmetric(
                            horizontal: 10,
                            vertical: 10,
                          ),

                          itemBuilder: (context, index) {
                            return Container(
                              padding: EdgeInsets.symmetric(
                                horizontal: 10,
                                vertical: 10,
                              ),
                              margin: EdgeInsets.symmetric(vertical: 5),
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(20),
                              ),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Row(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Expanded(
                                        flex: 1,
                                        child: SvgPicture.asset(
                                          "assets/svg/se_block_head.svg",
                                        ),
                                      ),
                                      SizedBox(width: 5),

                                      Expanded(
                                        flex: 4,
                                        child: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Text(
                                              "${provider.technician_complaint_list[index].contactName}",
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              style: TextStyle(
                                                fontFamily: "JakartaMedium",
                                              ),
                                            ),
                                            Text(
                                              "${provider.technician_complaint_list[index].companyName}",
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              style: TextStyle(
                                                color: Color(0xFF818181),
                                                fontSize: 14,
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                      Spacer(),
                                      Expanded(
                                        flex: 1,
                                        child: InkResponse(
                                          onTap: () {
                                            launch(
                                              'tel://${provider.technician_complaint_list[index].mobileNo}',
                                            );
                                          },
                                          child: SvgPicture.asset(
                                            "assets/svg/se_call_customer.svg",
                                            color: Color(0xFF0D9C00),
                                            height: 20,
                                            width: 20,
                                          ),
                                        ),
                                      ),
                                      Expanded(
                                        flex: 1,
                                        child: InkResponse(
                                          onTap: () {
                                            _showOptionsSheet(
                                              context,
                                              provider
                                                  .technician_complaint_list[index]
                                                  .companyName,

                                              provider
                                                  .technician_complaint_list[index]
                                                  .genId,
                                              provider
                                                  .technician_complaint_list[index]
                                                  .complaintId,
                                            );
                                          },
                                          child: SvgPicture.asset(
                                            "assets/svg/ic_more.svg",
                                            height: 30,
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                  Divider(
                                    thickness: 0.5,
                                    color: Color(0xFFD7D7D7),
                                  ),
                                  ...List.generate(4, (j) {
                                    final textheads = [
                                      "Complaint ID",
                                      "Product Name",

                                      "Engine Number",
                                      "Address",
                                    ];
                                    final textSubheads = [
                                      provider
                                          .technician_complaint_list[index]
                                          .complaintId,
                                      provider
                                          .technician_complaint_list[index]
                                          .productName,
                                      provider
                                          .technician_complaint_list[index]
                                          .engineNo,
                                      provider
                                          .technician_complaint_list[index]
                                          .address,
                                    ];
                                    return Container(
                                      padding: EdgeInsets.symmetric(
                                        vertical: 3,
                                      ),
                                      child: Row(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          Expanded(
                                            flex: 1,
                                            child: Text(
                                              textheads[j].toString(),
                                              style: TextStyle(
                                                fontFamily: "JakartaMedium",
                                              ),
                                            ),
                                          ),
                                          Expanded(
                                            flex: 2,
                                            child: Text(
                                              textSubheads[j].toString(),
                                              style: TextStyle(
                                                color: Color(0xFF818181),
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                    );
                                  }),
                                  InkResponse(
                                    onTap: () {
                                      Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                          builder:
                                              (context) => Visitdetails(
                                                from: "Pending Complaints",
                                                complaintID:
                                                    provider
                                                        .technician_complaint_list[index]
                                                        .complaintId,
                                              ),
                                        ),
                                      );
                                    },
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.start,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.center,
                                      children: [
                                        Text(
                                          "View Details",
                                          style: TextStyle(
                                            color: AppColors.app_blue,
                                            fontFamily: "JakartaMedium",
                                          ),
                                        ),
                                        SizedBox(width: 5),
                                        SvgPicture.asset(
                                          "assets/svg/next_button.svg",
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            );
                          },
                        ),
                      )
                      : Emptywidget(context),
            ),
          ),
        );
      },
    );
  }

  Future<void> _showOptionsSheet(
    BuildContext context,
    companyName,
    genId,
    complaintId,
  ) {
    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 Container(
                    margin: EdgeInsets.only(
                      bottom: 15,
                      left: 15,
                      right: 15,
                      top: 10,
                    ),
                    padding: EdgeInsets.only(
                      bottom: MediaQuery.of(context).viewInsets.bottom,
                    ),
                    child: SingleChildScrollView(
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          SizedBox(height: 15),

                          ...List.generate(3, (index) {
                            final assetnames = [
                              "se_locate_customer",
                              "se_update_complaint",
                              "se_payment_details",
                            ];
                            final Headingnames = [
                              "Location",
                              "Update Complaint",
                              "Payment Details",
                            ];
                            return ListTile(
                              onTap: () async {
                                switch (index) {
                                  case 0:
                                    {
                                      var loc =
                                          provider
                                              .technician_complaint_list[index]
                                              .loc
                                              ?.split(",")
                                              .toString();
                                      var uri = Uri.parse(
                                        "google.navigation:q=${loc![0]},${loc![1]}&mode=d",
                                      );
                                      if (await canLaunch(uri.toString())) {
                                        await launch(uri.toString());
                                      } else {
                                        throw 'Could not launch ${uri.toString()}';
                                      }
                                    }
                                    break;
                                  case 1:
                                    Navigator.pop(context);
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder:
                                            (context) => Updatecomplaints(
                                              ComplaintID: complaintId,
                                            ),
                                      ),
                                    );
                                    break;
                                  case 2:
                                    Navigator.pop(context);
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder:
                                            (context) => Paymentdetails(
                                              accountName: "Generator",
                                              name: companyName,
                                              genId: genId,
                                              referenceID: complaintId,
                                            ),
                                      ),
                                    );
                                    break;
                                }
                              },
                              leading: SvgPicture.asset(
                                "assets/svg/${assetnames[index]}.svg",
                              ),
                              title: Text(
                                Headingnames[index],
                                style: TextStyle(fontFamily: "JakartaMedium"),
                              ),
                              trailing: SvgPicture.asset(
                                "assets/svg/arrow_right_new.svg",
                              ),
                            );
                          }),
                        ],
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }
}
