import 'package:car_customer_app/api/shared_prefrence.dart';
import 'package:car_customer_app/generated/locale_keys.g.dart';
import 'package:car_customer_app/theme/colors.dart';
import 'package:car_customer_app/utils/navigator.dart';
import 'package:car_customer_app/widgets/app_bar.dart';
import 'package:car_customer_app/widgets/show_fill_button.dart';
import 'package:car_customer_app/extensions/int_extensions.dart';
import 'package:car_customer_app/extensions/string_extensions.dart';
import 'package:car_customer_app/extensions/widget_extensions.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:easy_localization/src/public_ext.dart';
import 'package:flutter/material.dart';

import '../../api/client/user_api_client.dart';
import '../../classes/app_state.dart';
import '../../classes/colors.dart';
import '../../classes/consts.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';

import '../../classes/utils.dart';
import '../../config/routes.dart';
import '../../models/user/image_response.dart';
import '../../utils/utils.dart';

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

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();
    fetchUsername();
  }

  fetchUsername() async {
    userName = await SharedPrefManager.getPhoneOrEmail();
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBar(context, title: "Logo/Brand", isRemoveBackButton: true),
      drawer: showDrawer(context),
      body: Container(
        child: Center(
          child: LocaleKeys.dashboard.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: Icon(
                Icons.notifications,
                color: MyColors.darkPrimaryColor,
              ),
              title: LocaleKeys.notifications.tr().toText12(),
            ),
            ListTile(
              leading: Icon(
                Icons.settings,
                color: MyColors.darkPrimaryColor,
              ),
              title: LocaleKeys.general.tr().toText12(),
            ),
            ListTile(
              leading: Icon(
                Icons.person,
                color: MyColors.darkPrimaryColor,
              ),
              title: LocaleKeys.account.tr().toText12(),
            ),
            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: Icon(
                Icons.logout,
                color: MyColors.darkPrimaryColor,
              ),
              title: LocaleKeys.signOut.tr().toText12(),
              onTap: () {
                pop(context);
                navigateReplaceWithName(context, AppRoutes.registerSelection);
              },
            ),
          ],
        ),
      ),
    );
  }

  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(LocaleKeys.fileLarger.tr());
      //("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(LocaleKeys.imageUploaded.tr());
        //("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(LocaleKeys.fileLarger.tr());
      //("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(LocaleKeys.imageUploaded.tr());
        //("Image is uploaded");
        AppState().getUser.data!.userInfo!.userImageUrl = response.data;
      } else {
        Utils.showToast(response.message ?? "");
      }

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