import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/Notifiers/GeneratorDetailsProvider.dart';
import 'package:generp/screens/genTracker/ComplaintHistory.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../Notifiers/HomeScreenNotifier.dart';
import '../../Utils/app_colors.dart';
import '../../Utils/commonWidgets.dart';
import 'ScanEnterGeneratorIDScreen.dart';

class Generatordetails extends StatefulWidget {
  final activityName;
  final genLocation;
  final generatorId;

  const Generatordetails({
    super.key,
    this.activityName,
    this.genLocation,
    required this.generatorId,
  });

  @override
  State<Generatordetails> createState() => _GeneratordetailsState();
}

class _GeneratordetailsState extends State<Generatordetails> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      var details = Provider.of<Generatordetailsprovider>(
        context,
        listen: false,
      );
      var homeProvider = Provider.of<HomescreenNotifier>(
        context,
        listen: false,
      );
      if (widget.activityName == "NearByGenerators") {
        details.LoadTechniciangeneratorDetailsApifunction(
          homeProvider,
          context,
          "",
          widget.generatorId,
        );
      }
      // else {
      //   details.LoadgeneratorDetailsApifunction(
      //     homeProvider,
      //     context,
      //     "",
      //     widget.generatorId,
      //     "3"
      //   );
      // }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Consumer2<Generatordetailsprovider, HomescreenNotifier>(
      builder: (context, provider, Homeprovider, child) {
        var sendwidget = SizedBox(width: 0);
        return WillPopScope(
          onWillPop: () => onBackPressed(context),
          child: Scaffold(
            resizeToAvoidBottomInset: true,
            appBar: appbar2(
              context,
              "Generator Details",
              provider.resetForm,
              sendwidget,
            ),
            backgroundColor: AppColors.scaffold_bg_color,
            body: SafeArea(
              child: Container(
                child: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 10,
                          vertical: 5,
                        ),
                        child: Text(
                          "Customer Details",
                          style: TextStyle(
                            color: Color(0xFF818181),
                            fontFamily: "JakartaMedium",
                          ),
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.symmetric(
                          horizontal: 10,
                          vertical: 5,
                        ),
                        padding: EdgeInsets.symmetric(
                          horizontal: 15,
                          vertical: 10,
                        ),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(20),
                        ),
                        child: Column(
                          children: [
                            Container(
                              padding: EdgeInsets.symmetric(
                                vertical: 3,
                                horizontal: 0,
                              ),
                              child: Row(
                                children: [
                                  SvgPicture.asset(
                                    "assets/svg/se_block_head.svg",
                                  ),
                                  SizedBox(width: 10),

                                  Expanded(
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          "${provider.aname}",
                                          maxLines: 2,
                                          overflow: TextOverflow.ellipsis,
                                          style: TextStyle(
                                            fontFamily: "JakartaMedium",
                                            fontSize: 14,
                                          ),
                                        ),
                                        Text(
                                          "${provider.cname}",
                                          maxLines: 2,
                                          overflow: TextOverflow.ellipsis,
                                          style: TextStyle(
                                            fontSize: 14,
                                            color: Color(0xFF818181),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: List.generate(4, (j) {
                                final textheads = [
                                  "Mobile Number",
                                  "Contact Person Number",
                                  "Mail ID",
                                  "Location",
                                ];
                                final textSubheads = [
                                  provider.mob1 ?? "-",
                                  provider.mob2 ?? "-",
                                  provider.mail ?? "-",
                                  "View",
                                ];
                                return Container(
                                  padding: EdgeInsets.symmetric(
                                    vertical: 6,
                                    horizontal: 0,
                                  ),
                                  child: Row(
                                    children: [
                                      Expanded(
                                        flex: 1,
                                        child: SizedBox(
                                          child: Text(
                                            textheads[j].toString(),
                                            maxLines: 2,
                                            overflow: TextOverflow.ellipsis,
                                            style: TextStyle(
                                              fontFamily: "JakartaMedium",
                                              fontSize: 14,
                                            ),
                                          ),
                                        ),
                                      ),
                                      SizedBox(width: 5),
                                      if (textSubheads[j] == "View") ...[
                                        Expanded(
                                          flex: 2,
                                          child: Container(
                                            padding: EdgeInsets.only(
                                              right: 10.0,
                                            ),
                                            child: InkWell(
                                              onTap: () async {
                                                if (widget.genLocation !=
                                                    null) {
                                                  provider.genLocationLatLngs =
                                                      widget.genLocation
                                                          ?.split(",")
                                                          .toString();
                                                } else {
                                                  provider.genLocationLatLngs =
                                                      provider.genLocation
                                                          ?.split(",")
                                                          .toString();
                                                }

                                                var uri = Uri.parse(
                                                  "google.navigation:q=${provider.genLocationLatLngs![0]},${provider.genLocationLatLngs![1]}&mode=d",
                                                );
                                                if (Platform.isIOS) {
                                                  uri = Uri.parse(
                                                    "maps://?q=${provider.genLocationLatLngs![0]},${provider.genLocationLatLngs![1]}&z=10&daddr=${provider.genLocationLatLngs![0]},${provider.genLocationLatLngs![1]}&dirflg=d",
                                                  );
                                                }
                                                if (await canLaunch(
                                                  uri.toString(),
                                                )) {
                                                  await launch(uri.toString());
                                                } else {
                                                  throw 'Could not launch ${uri.toString()}';
                                                }
                                              },
                                              child: Text(
                                                textSubheads[j],
                                                maxLines: 2,
                                                overflow: TextOverflow.ellipsis,
                                                style: TextStyle(
                                                  fontSize: 14,
                                                  color: AppColors.app_blue,
                                                  decoration:
                                                      TextDecoration.underline,
                                                  decorationColor:
                                                      AppColors.app_blue,
                                                ),
                                              ),
                                            ),
                                          ),
                                        ),
                                      ] else ...[
                                        Expanded(
                                          flex: 2,
                                          child: InkResponse(
                                            onTap:
                                                textheads[j] != "Mobile Number"
                                                    ? null
                                                    : () async {
                                                      final Uri phoneUri = Uri(
                                                        scheme: 'tel',
                                                        path:
                                                            provider.mob1 == ""
                                                                ? provider.mob2
                                                                : provider.mob1,
                                                      );

                                                      if (await canLaunchUrl(
                                                        phoneUri,
                                                      )) {
                                                        await launchUrl(
                                                          phoneUri,
                                                        );
                                                      } else {
                                                        throw 'Could not launch $phoneUri';
                                                      }
                                                    },
                                            child: SizedBox(
                                              child: Text(
                                                textSubheads[j] == ""
                                                    ? "-"
                                                    : textSubheads[j],
                                                maxLines: 2,
                                                overflow: TextOverflow.ellipsis,
                                                style: TextStyle(
                                                  fontSize: 14,
                                                  color:
                                                      textheads[j] ==
                                                              "Mobile Number"
                                                          ? AppColors.app_blue
                                                          : Color(0xFF818181),
                                                  decorationColor:
                                                      textheads[j] ==
                                                              "Mobile Number"
                                                          ? AppColors.app_blue
                                                          : null,
                                                  decoration:
                                                      textheads[j] ==
                                                              "Mobile Number"
                                                          ? TextDecoration
                                                              .underline
                                                          : null,
                                                ),
                                              ),
                                            ),
                                          ),
                                        ),
                                      ],
                                    ],
                                  ),
                                );
                              }),
                            ),
                          ],
                        ),
                      ),

                      Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 10,
                          vertical: 5,
                        ),
                        child: Text(
                          "Generator Details",
                          style: TextStyle(
                            color: Color(0xFF818181),
                            fontFamily: "JakartaMedium",
                          ),
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.symmetric(
                          horizontal: 10,
                          vertical: 5,
                        ),
                        padding: EdgeInsets.symmetric(
                          horizontal: 15,
                          vertical: 10,
                        ),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(20),
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: List.generate(6, (j) {
                            final textheads = [
                              "Product Name",
                              "Gen Hash ID",
                              "Engine Number",
                              "Engine Model",
                              "Address",
                              "Date Of Supply",
                            ];
                            final textSubheads = [
                              "${provider.spname}",
                              "${provider.genHashID}",
                              "${provider.engineNo}",
                              "${provider.emodel}",
                              "${provider.address}",
                              "${provider.dateOfEngineSale}",
                            ];
                            return Container(
                              padding: EdgeInsets.symmetric(
                                vertical: 6,
                                horizontal: 0,
                              ),
                              child: Row(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Expanded(
                                    flex: 1,
                                    child: Text(
                                      textheads[j].toString(),
                                      style: TextStyle(
                                        fontSize: 14,
                                        fontFamily: "JakartaMedium",
                                      ),
                                    ),
                                  ),
                                  SizedBox(width: 5),
                                  Expanded(
                                    flex: 2,
                                    child: SizedBox(
                                      child: Text(
                                        textSubheads[j] == ""
                                            ? "-"
                                            : textSubheads[j],
                                        maxLines: 2,
                                        overflow: TextOverflow.ellipsis,
                                        style: TextStyle(
                                          fontSize: 14,
                                          color: Color(0xFF818181),
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            );
                          }),
                        ),
                      ),
                      InkWell(
                        onTap: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder:
                                  (context) => TagLocationScreen(
                                    genHashID: provider.genHashID,
                                  ),
                            ),
                          );
                        },
                        child: Container(
                          alignment: Alignment.bottomCenter,
                          height: 45,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(14),
                          ),
                          // width: Med1iaQuery.of(context).size.width,
                          margin: EdgeInsets.symmetric(
                            horizontal: 10,
                            vertical: 5,
                          ),
                          padding: EdgeInsets.symmetric(
                            horizontal: 10,
                            vertical: 10,
                          ),
                          // decoration: BoxDecoration(
                          //   color: AppColors.app_blue,
                          //   borderRadius: BorderRadius.circular(15.0),
                          // ),
                          child: Center(
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                SvgPicture.asset(
                                  "assets/svg/gent_tag_loc.svg",
                                  width: 20,
                                ),
                                SizedBox(width: 10),
                                Text(
                                  "Tag Location",
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                    fontFamily: "JakartaMedium",
                                    fontSize: 15,
                                    decoration: TextDecoration.underline,
                                    decorationColor: AppColors.app_blue,
                                    color: AppColors.app_blue,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                      InkWell(
                        onTap: () {
                          provider.LoadgeneratorDetailsApifunction(
                            Homeprovider,
                            context,
                            "Register Complaint",
                            provider.genHashID,
                            "2",
                          );
                          // Navigator.push(
                          //   context,
                          //   MaterialPageRoute(
                          //     builder:
                          //         (context) => Scanentergeneratoridscreen(
                          //           from: "Register Complaint",
                          //         ),
                          //   ),
                          // );
                        },
                        child: Container(
                          alignment: Alignment.bottomCenter,
                          height: 45,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(14),
                          ),
                          // width: Med1iaQuery.of(context).size.width,
                          margin: EdgeInsets.symmetric(
                            horizontal: 10,
                            vertical: 5,
                          ),
                          padding: EdgeInsets.symmetric(
                            horizontal: 10,
                            vertical: 10,
                          ),
                          // decoration: BoxDecoration(
                          //   color: AppColors.app_blue,
                          //   borderRadius: BorderRadius.circular(15.0),
                          // ),
                          child: Center(
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                SvgPicture.asset(
                                  "assets/svg/gent_reg_comp.svg",
                                  width: 20,
                                ),
                                SizedBox(width: 10),
                                Text(
                                  "Register Complaint",
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                    fontFamily: "JakartaMedium",
                                    fontSize: 15,
                                    decoration: TextDecoration.underline,
                                    decorationColor: AppColors.app_blue,
                                    color: AppColors.app_blue,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                      SizedBox(height: 75),
                    ],
                  ),
                ),
              ),
            ),
            floatingActionButton: Align(
              alignment: Alignment.bottomCenter,
              child: InkWell(
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder:
                          (context) =>
                              Complainthistory(genHashID: provider.genHashID),
                    ),
                  );
                },
                child: Container(
                  alignment: Alignment.bottomCenter,
                  height: 45,
                  width: MediaQuery.of(context).size.width,
                  margin: EdgeInsets.symmetric(horizontal: 10),
                  decoration: BoxDecoration(
                    color: AppColors.app_blue,
                    borderRadius: BorderRadius.circular(15.0),
                  ),
                  child: Center(
                    child: Text(
                      "Complaint History",
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        fontFamily: "JakartaMedium",
                        fontSize: 15,
                        color: Colors.white,
                      ),
                    ),
                  ),
                ),
              ),
            ),
            floatingActionButtonLocation:
                FloatingActionButtonLocation.centerFloat,
          ),
        );
      },
    );
  }
}

class TagLocationScreen extends StatefulWidget {
  final genHashID;

  const TagLocationScreen({super.key, required this.genHashID});

  @override
  State<TagLocationScreen> createState() => _TagLocationScreenState();
}

class _TagLocationScreenState extends State<TagLocationScreen> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {});
  }

  @override
  Widget build(BuildContext context) {
    return Consumer2<Generatordetailsprovider, HomescreenNotifier>(
      builder: (context, provider, Homeprovider, child) {
        var sendwidget = SizedBox(width: 0);
        return WillPopScope(
          onWillPop: () => onBackPressed(context),
          child: Scaffold(
            resizeToAvoidBottomInset: true,
            appBar: appbar2(
              context,
              "Tag Location",
              provider.resetForm,
              sendwidget,
            ),
            backgroundColor: AppColors.white,
            body: SafeArea(
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 10,vertical: 10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    textControllerReadonlyWidget(
                      context,
                      TextEditingController(text: widget.genHashID),
                      "Gen ID",
                      (p0) {},
                    ),
                    SizedBox(height: 10,),
                    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(
                            "Add Proof",
                            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: [
                            Expanded(
                              flex: 4,
                              child: Text(
                                "${provider.imagePath}",
                                overflow: TextOverflow.visible,
                                style: TextStyle(
                                  color: AppColors.semi_black,
                                  fontSize: 11,
                                  fontWeight: FontWeight.w600,
                                ),
                              ),
                            ),
                            SizedBox(width: 10,),
                            Expanded(
                              flex: 1,
                              child: InkResponse(
                                onTap: () {
                                  provider.imagePicked = 0;
                                  provider.imagePath = null;
                                  provider.imageFilePath = null;
                                },
                                child: SvgPicture.asset(
                                  "assets/svg/ic_close.svg",
                                  width: 15,
                                  height: 15,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                    errorWidget(context, provider.imageError)
                  ],
                ),
              ),
            ),
            bottomNavigationBar: InkWell(
              onTap: () {
                provider.TagLocationAPIFunction(
                  Homeprovider,
                  context,
                  provider.genHashID,
                );
              },
              child: Container(
                alignment: Alignment.bottomCenter,
                height: 45,
                width: MediaQuery.of(context).size.width,
                margin: EdgeInsets.symmetric(horizontal: 10,vertical: 10),
                decoration: BoxDecoration(
                  color: AppColors.app_blue,
                  borderRadius: BorderRadius.circular(15.0),
                ),
                child: Center(
                  child: Text(
                    "Tag Location",
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontFamily: "JakartaMedium",
                      fontSize: 15,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  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<Generatordetailsprovider>(
                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.imgFromCamera();
                              },
                              child: Container(
                                height: 35,
                                child: Text("Capture photo from camera"),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }
}
