import 'package:car_provider_app/api/api_client.dart';
import 'package:car_provider_app/api/client/user_api_client.dart';
import 'package:car_provider_app/api/shared_prefrence.dart';
import 'package:car_provider_app/classes/app_state.dart';
import 'package:car_provider_app/classes/colors.dart';
import 'package:car_provider_app/classes/consts.dart';
import 'package:car_provider_app/classes/utils.dart';
import 'package:car_provider_app/config/routes.dart';
import 'package:car_provider_app/models/m_response.dart';
import 'package:car_provider_app/models/user/image_response.dart';
import 'package:car_provider_app/theme/colors.dart';
import 'package:car_provider_app/utils/navigator.dart';
import 'package:car_provider_app/utils/utils.dart';
import 'package:car_provider_app/widgets/app_bar.dart';
import 'package:car_provider_app/widgets/button/show_fill_button.dart';
import 'package:car_provider_app/extensions/int_extensions.dart';
import 'package:car_provider_app/extensions/string_extensions.dart';
import 'package:car_provider_app/extensions/widget_extensions.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:http/http.dart';
import 'package:image_picker/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:io';

import '../../generated/locale_keys.g.dart';
import '../../utils/location/Location.dart';

class DashboardPage extends StatefulWidget {
  @override
  State<DashboardPage> createState() => _DashboardPageState();
}

enum ImageSourceType { gallery, camera }

class _DashboardPageState extends State<DashboardPage> {
  String userName = "";

  // void _handleURLButtonPress(BuildContext context, var type) {
  //   Navigator.push(context,
  //       MaterialPageRoute(builder: (context) => ImageFromGalleryEx(type)));
  // }

  File? imagePicked;
  String image64 = "";
  final _picker = ImagePicker();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    fetchUsernameAndLocation();
  }

  fetchUsernameAndLocation() async {
    userName = await SharedPrefManager.getPhoneOrEmail();
    Location.getCurrentLocation(
      (LatLng? latlng) {
        AppState().currentLocation = latlng ?? new LatLng(0, 0);
      },
    );

    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBar(
        context,
        title: LocaleKeys.logo_brand.tr(),
        isRemoveBackButton: true,
      ),
      drawer: showDrawer(context),
      body: Container(
        child: Container(
          child: Center(
            child: LocaleKeys.dashboard_main.tr().toText24(),
          ),
        ),
      ),
    );
  }

  Widget showDrawer(BuildContext context) {
    return Drawer(
      child: Container(
        child: Column(
          children: [
            Stack(children: [
              Container(
                width: double.infinity,
                height: 200,
                color: MyColors.darkPrimaryColor.withOpacity(0.01),
                child: Image.network(ApiConsts.baseUrlServices + AppState().getUser.data!.userInfo!.userImageUrl.toString()),
              ),
              Positioned(
                top: 10,
                right: 10,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Column(
                      children: [
                        Container(
                          width: 40,
                          height: 40,
                          decoration: BoxDecoration(
                            color: Colors.grey[200],
                            borderRadius: BorderRadius.circular(30),
                          ),
                          child: Icon(
                            Icons.edit,
                            color: MyColors.darkPrimaryColor,
                          ).onPress(() {
                            _openImagePicker();
                            //  _handleURLButtonPress(context, ImageSourceType.camera);
                          }),
                        ),
                        12.height,
                        Container(
                          width: 40,
                          height: 40,
                          decoration: BoxDecoration(
                            color: Colors.grey[200],
                            borderRadius: BorderRadius.circular(30),
                          ),
                          child: Icon(
                            Icons.delete,
                            color: Colors.red,
                          ).onPress(() async {
                            Utils.showLoading(context);
                            ImageResponse response = await UserApiClent().UpdateUserImage("");
                            if (response.messageStatus == 1) {
                              Utils.showToast("Image is Deleted");
                              setState(() {
                                AppState().getUser.data!.userInfo!.userImageUrl = response.data;
                              });
                            }
                            Utils.hideLoading(context);
                          }),
                        ),
                      ],
                    ),
                  ],
                ),
              )
            ]),
            Container(
              width: double.infinity,
              color: MyColors.darkPrimaryColor.withOpacity(0.1),
              padding: EdgeInsets.all(20),
              child: Row(
                children: [
                  Expanded(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        userName.toText20(isBold: true),
                        AppState().getUser.data!.userInfo!.roleName!.toText10(),
                      ],
                    ),
                  ),
                  ShowFillButton(
                    title: LocaleKeys.edit.tr(),
                    fontSize: 12,
                    maxHeight: 35,
                    maxWidth: 70,
                    onPressed: () {
                      navigateWithName(context, AppRoutes.editAccoundPage);
                    },
                  ),
                ],
              ),
            ),
            ListTile(
              leading: SvgPicture.asset("assets/images/ic_notification.svg", color: MyColors.darkPrimaryColor),
              title: LocaleKeys.notifications.tr().toText12(),
            ),
            ListTile(
              leading: SvgPicture.asset("assets/images/ic_settings.svg", color: MyColors.darkPrimaryColor),
              title: LocaleKeys.general.tr().toText12(),
            ),
            ListTile(
              leading: SvgPicture.asset("assets/images/ic_notes.svg", color: MyColors.darkPrimaryColor),
              title: LocaleKeys.defineLicences.tr().toText12(),
              onTap: () {
                navigateWithName(context, AppRoutes.defineLicense);
              },
            ),
            ListTile(
              leading: SvgPicture.asset("assets/images/ic_car.svg", color: MyColors.darkPrimaryColor),
              title: LocaleKeys.dealershipSettings.tr().toText12(),
              onTap: () {
                navigateWithName(context, AppRoutes.dealershipSetting);
              },
            ),
            ListTile(
              leading: Image.asset(
                "assets/images/ic_world.png",
                width: 20,
                height: 20,
                color: MyColors.darkPrimaryColor,
              ),
              title: LocaleKeys.english.tr().toText12(),
              onTap: () {
                if (EasyLocalization.of(context)?.currentLocale?.countryCode == "SA")
                  context.setLocale(const Locale("en", "US"));
                else
                  context.setLocale(const Locale('ar', 'SA'));
              },
            ),
            // ListTile(
            //   leading: SvgPicture.asset("assets/images/ic_lock.svg"),
            //   title: "Change Password".toText12(),
            //   onTap: (){
            //     navigateWithName(context, AppRoutes.changePassword);
            //   },
            // ),
            // ListTile(
            //   leading: SvgPicture.asset("assets/images/ic_mobile.svg"),
            //   title: "Change Mobile".toText12(),
            //   onTap: () {
            //     navigateWithName(context, AppRoutes.changeMobilePage);
            //   },
            // ),
            // ListTile(
            //   leading: Icon(Icons.email_outlined, color: Colors.blue,),
            //   title: "Change Email".toText12(),
            //   onTap: () {
            //     navigateWithName(context, AppRoutes.changeEmailPage);
            //   },
            // ),
            ListTile(
              leading: SvgPicture.asset("assets/images/ic_logout.svg", color: MyColors.darkPrimaryColor),
              title: LocaleKeys.signOut.tr().toText12(),
              onTap: () async {
                final pref = await SharedPreferences.getInstance();
                await pref.clear();
                pop(context);
                navigateReplaceWithName(context, AppRoutes.registerSelection);
              },
            ),
          ],
        ),
      ),
    );
  }

  // Implementing the image picker
  // Future<void> _openImagePicker() async {
  //   final XFile? pickedImage =
  //   await _picker.pickImage(source: ImageSource.gallery);
  //   if (pickedImage != null) {
  //     setState(() {
  //       //  _image = File(pickedImage.path);
  //     });
  //   }
  // }

  void _openImagePicker() {
    showDialog<ImageSource>(
      context: context,
      builder: (context) => AlertDialog(content: Text("Choose image source"), actions: [
        TextButton(child: Text("Camera"), onPressed: () => cameraImage()),
        TextButton(child: Text("Gallery"), onPressed: () => gallaryImage()),
      ]),
      //     .then((ImageSource source) async {
      //   if (source != null) {
      //     final pickedFile = await ImagePicker().getImage(source: source);
      //     setState(() => imagePicked = File(pickedFile.path));
      //   }
      // }
    );
  }

  void gallaryImage() async {
    final picker = ImagePicker();
    final pickedImage = await picker.pickImage(
      source: ImageSource.gallery,
    );
    final pickedImageFile = File(pickedImage!.path);
    int sizeInBytes = pickedImageFile.lengthSync();
    // double sizeInMb = sizeInBytes / (1024 * 1024);
    if (sizeInBytes > 1000) {
      Utils.showToast("File is larger then 1KB");
    } else {
      image64 = convertFileToBase64(pickedImageFile);

      Utils.showLoading(context);
      ImageResponse response = await UserApiClent().UpdateUserImage(image64);
      Utils.hideLoading(context);
      Navigator.pop(context);
      if (response.messageStatus == 1) {
        Utils.showToast("Image is uploaded");
        AppState().getUser.data!.userInfo!.userImageUrl = response.data;
      } else {
        Utils.showToast(response.message ?? "");
      }

      setState(() {
        imagePicked = pickedImageFile;
      });
    }
  }

  void cameraImage() async {
    final picker = ImagePicker();
    final pickedImage = await picker.pickImage(
      source: ImageSource.camera,
    );
    final pickedImageFile = File(pickedImage!.path);
    int sizeInBytes = pickedImageFile.lengthSync();
    // double sizeInMb = sizeInBytes / (1024 * 1024);
    if (sizeInBytes > 1000) {
      Utils.showToast("File is larger then 1KB");
    } else {
      image64 = convertFileToBase64(pickedImageFile);

      Utils.showLoading(context);
      ImageResponse response = await UserApiClent().UpdateUserImage(image64);
      Utils.hideLoading(context);
      Navigator.pop(context);
      if (response.messageStatus == 1) {
        Utils.showToast("Image is uploaded");
        AppState().getUser.data!.userInfo!.userImageUrl = response.data;
      } else {
        Utils.showToast(response.message ?? "");
      }

      setState(() {
        imagePicked = pickedImageFile;
      });
    }
  }
}
