import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/app_strings/app_asset.dart';
import 'package:test_sa/controllers/providers/api/service_requests_provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/models/new_models/arrival_verification_type_model.dart';
import 'package:test_sa/models/service_request/service_request.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.dart';
import 'package:test_sa/service_request_latest/request_detail_provider.dart';
import 'package:test_sa/service_request_latest/views/components/verify_otp_view.dart';
import 'package:test_sa/service_request_latest/views/forms/asset_retired/asset_retired.dart';
import 'package:test_sa/service_request_latest/views/forms/asset_retired/verify_asset_detail.dart';
import 'package:test_sa/service_request_latest/views/request_detail_main_view.dart';
import 'package:test_sa/views/widgets/qr/scan_qr.dart';

import 'activities_list_view.dart';

class VerifyArrivalView extends StatefulWidget {
  const VerifyArrivalView({Key? key}) : super(key: key);

  @override
  State<VerifyArrivalView> createState() => _VerifyArrivalViewState();
}

class _VerifyArrivalViewState extends State<VerifyArrivalView> {
  ArrivalVerificationTypeModel? arrivalVerificationTypeModel;

  @override
  void initState() {
    //TODO call this when all data is confirmed
    // getInitialData();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getInitialData();
    });
    super.initState();
  }

  Future<void> getInitialData() async {
    RequestDetailProvider requestDetailProvider = Provider.of<RequestDetailProvider>(context, listen: false);
    arrivalVerificationTypeModel = await requestDetailProvider.getArrivalVerificationType();
    print('data i got is${arrivalVerificationTypeModel?.data?.first?.verificationTypeId}');
  }

  @override
  Widget build(BuildContext context) {
    //TODO replace the list with Api...
    final List<Map<String, dynamic>> items = [
      {'heading': context.translation.scanQr, 'subHeading': context.translation.scanQrDetail, 'icon': AppAsset.scanQrIcon, 'id': 1},
      {'heading': context.translation.askRequester, 'subHeading': context.translation.askRequesterDetail, 'icon': AppAsset.askRequesterIcon, 'id': 2},
      {'heading': context.translation.askOtp, 'subHeading': context.translation.askOtpDetail, 'icon': AppAsset.askOtpIcon, 'id': 3},
      {'heading': context.translation.takeDevicePhoto, 'subHeading': context.translation.takeDevicePhotoDetail, 'icon': AppAsset.takeDevicePhotoIcon, 'id': 4},
    ];
    return Scaffold(
      appBar: DefaultAppBar(title: context.translation.verifyArrival),
      //backgroundColor: const Color(0xfff8f9fb),
      body: Consumer<RequestDetailProvider>(builder: (context, RequestDetailProvider requestDetailProvider, child) {
        return SafeArea(
          child: ListView.builder(
            padding: EdgeInsets.zero,
            itemCount: items.length,
            itemBuilder: (context, index) {
              final item = items[index];
              return customListItem(
                  icon: item['icon']!,
                  heading: item['heading']!,
                  subHeading: item['subHeading']!,
                  context: context,
                  onTap: () {
                    onItemTap(requestDetailProvider: requestDetailProvider, index: index, context: context);
                  });
            },
          ).paddingOnly(start: 16, end: 16, top: 12, bottom: 12),
        );
      }),
    );
  }

  Widget customListItem({
    required BuildContext context,
    required String icon,
    required String heading,
    required String subHeading,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap, // Handles the tap
      child: Card(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(14), // Circular border radius
        ),
        color: Colors.white,
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start, // Align items at the top
          children: [
            // Icon Section
            icon
                .toSvgAsset(
                  width: 32,
                  color: AppColor.neutral120,
                  height: 29,
                )
                .paddingOnly(top: 8),
            14.width,
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    heading,
                    style: AppTextStyles.heading6.copyWith(color: AppColor.neutral50),
                  ),
                  7.height,
                  Text(
                    subHeading,
                    style: AppTextStyles.bodyText2.copyWith(color: AppColor.neutral120),
                  ),
                ],
              ).paddingOnly(end: 50),
            ),
          ],
        ).paddingAll(12),
      ),
    );
  }

  void onItemTap({required int index, required RequestDetailProvider requestDetailProvider, required BuildContext context}) async {
    switch (index) {
      case 0:
        int? status;
        String? result = await Navigator.of(context).push(
          MaterialPageRoute(builder: (_) => const ScanQr()),
        ) as String?;
        if (result != null) {
          try {
            //TODO show loader.
            // showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());

            status = await requestDetailProvider.engineerConfirmArrival(
                workOrderId: requestDetailProvider.currentWorkOrder!.data!.requestId!, verificationTypeId: 1, photoInfo: '', otp: '', assetNo: result);
            if (status == 200) {
              requestDetailProvider.getWorkOrderById(id: requestDetailProvider.currentWorkOrder!.data!.requestId!);
              //Navigator.pop(context);
              requestDetailProvider.startTimer();
              Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => RequestDetailMain(requestId: requestDetailProvider.currentWorkOrder!.data!.requestId!)));
            } else {
              // Navigator.pop(context);
              //show some message.
            }
          } catch (e) {
            // Navigator.pop(context);
            print('error i got is $e');
          }
        }
        break;
      case 1:
        Fluttertoast.showToast(msg: 'Under process...' ?? "", toastLength: Toast.LENGTH_LONG);
        break;
      case 2:
        //TODO add loader.
        // showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());

        requestDetailProvider.sendOtp(workOrderId: requestDetailProvider.currentWorkOrder!.data!.requestId!);
        //Navigator.pop(context);
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (context) => const VerifyOtpView()),
        );
        break;
      case 3:
        File? pickedFile = await onFilePicker();
        if (pickedFile != null) {
          var fileObj = ("${pickedFile.path.split("/").last}|${base64Encode(File(pickedFile.path).readAsBytesSync())}");
          int? status;
          try {
            //TODO add loader
            // showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
            status = await requestDetailProvider.engineerConfirmArrival(workOrderId: requestDetailProvider.currentWorkOrder!.data!.requestId!, verificationTypeId: 4, photoInfo: fileObj, otp: '');

            if (status == 200) {
              requestDetailProvider.getWorkOrderById(id: requestDetailProvider.currentWorkOrder!.data!.requestId!);
              // Navigator.pop(context);
              requestDetailProvider.startTimer();
              Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => RequestDetailMain(requestId: requestDetailProvider.currentWorkOrder!.data!.requestId!)));
            } else {
              //show some message.
              // Navigator.pop(context);
            }
          } catch (e) {
            print('error i got is $e');
            // Navigator.pop(context);
          }
        }

        // Navigator.push(
        //   context,
        //   MaterialPageRoute(builder: (context) => const VerifyAssetDetails()),
        // );
        //push to specific screen...
        // Navigator.push(
        //   context,
        //   MaterialPageRoute(builder: (context) =>  const ScanQrView()),
        // );
        break;
    }
    //   ScanQr
  }

  Future<File?> onFilePicker() async {
    // ImageSource? source = await showModalBottomSheet<ImageSource>(
    //   context: context,
    //   builder: (BuildContext context) {
    //     Widget listCard({required String icon, required String label, required VoidCallback onTap}) {
    //       return GestureDetector(
    //         onTap: onTap,
    //         child: Container(
    //           constraints: BoxConstraints(minWidth: 111.toScreenWidth, minHeight: 111.toScreenHeight),
    //           padding: EdgeInsets.symmetric(horizontal: 12.toScreenWidth, vertical: 12.toScreenHeight),
    //           decoration: BoxDecoration(borderRadius: BorderRadius.circular(12), border: Border.all(width: 1, color: AppColor.white70)),
    //           child: Column(
    //             mainAxisSize: MainAxisSize.min,
    //             crossAxisAlignment: CrossAxisAlignment.start,
    //             children: [
    //               icon.toSvgAsset(),
    //               24.height,
    //               label.bodyText2(context).custom(color: AppColor.black20),
    //             ],
    //           ),
    //         ),
    //       );
    //     }
    //
    //     return Container(
    //       padding: const EdgeInsets.all(16.0),
    //       child: Row(
    //         // mainAxisAlignment: MainAxisAlignment.spaceBetween,
    //         children: <Widget>[
    //           listCard(
    //             icon: 'camera_icon',
    //             label: '${context.translation.open}\n${context.translation.camera}',
    //             onTap: () {
    //               Navigator.of(context).pop(ImageSource.camera);
    //             },
    //           ),
    //           20.width,
    //           listCard(
    //             icon: 'gallery_icon',
    //             label: '${context.translation.open}\n${context.translation.gallery}',
    //             onTap: () {
    //               Navigator.of(context).pop(ImageSource.gallery);
    //             },
    //           ),
    //         ],
    //       ),
    //     );
    //   },
    // );
    // if (source == null) return null;
    File? fileImage;
    final pickedFile = await ImagePicker().pickImage(source: ImageSource.camera, imageQuality: 70, maxWidth: 800, maxHeight: 800);

    if (pickedFile != null) {
      fileImage = File(pickedFile.path);
    }
    return fileImage;
  }
}
