import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:traderscircuit/Utils/Common/CommonAppbar.dart';
import 'package:traderscircuit/Utils/Common/CustomTextFormField.dart';
import 'package:traderscircuit/Utils/Common/commonBotton.dart';
import 'package:traderscircuit/Utils/base_manager.dart';
import 'package:traderscircuit/Utils/text.dart';
import 'package:traderscircuit/Utils/utils.dart';
import 'package:traderscircuit/resources/routes/route_name.dart';
import 'package:traderscircuit/view/onBoarding/splashScreen1.dart';
import 'package:traderscircuit/view_model/Login/add_details_api.dart';

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

  @override
  State<AddDetails> createState() => _AddDetailsState();
}

class _AddDetailsState extends State<AddDetails> {
  final GlobalKey<FormState> _adddetailsform = GlobalKey<FormState>();
  TextEditingController pincode = TextEditingController();
  TextEditingController fullName = TextEditingController();
  TextEditingController email = TextEditingController();
  TextEditingController phone = TextEditingController();
  TextEditingController city = TextEditingController();
  TextEditingController dobcontroller = TextEditingController();
  Color primaryColor = Colors.transparent.withOpacity(0.2);
  Color secondaryColor = Colors.grey.shade800;

  bool isSwitched = false;

  void _toggleSwitch(bool value) {
    setState(() {
      isSwitched = value;
    });
  }

  DateTime timebackPressed = DateTime.now();

  Future<void> _selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(1900),
        lastDate: DateTime.now(),
        builder: (context, child) {
          return Theme(
              data: Theme.of(context).copyWith(
                colorScheme: ColorScheme.light(
                  surface: Colors.black,
                  onSurface: Colors.white,
                  primary: Color(0xff9A0000),
                  onPrimary: Colors.white,
                ),
                textButtonTheme: TextButtonThemeData(
                  style: TextButton.styleFrom(
                    foregroundColor: Colors.white,
                  ),
                ),
              ),
              child: child!);
        });

    if (picked != null && picked != DateTime.now()) {
      setState(() {
        dobcontroller.text = "${picked.toLocal()}".split(' ')[0];
        final birthDate = DateTime(
          picked.year,
          picked.month,
          picked.day,
        );
      });
    }
  }

  _addDetails() async {
    final isValid = _adddetailsform.currentState?.validate();
    if (isValid!) {
      Utils.loader();
      Map<String, dynamic> updata = {
        "full_name": fullName.text,
        "email_address": email.text,
        "mobile_number": phone.text,
        "date_of_birth": dobcontroller.text,
        "city": city.text,
        "whatsapp_update": isSwitched == false ? 0 : 1,
      };
      final resp = await AddDetailsAPI(updata).adddetailsApi();
      if (resp.status == ResponseStatus.SUCCESS) {
        Get.back();
        Get.toNamed(RouteName.kyc);
      } else if (resp.status == ResponseStatus.PRIVATE) {
        Get.back();
        String? message = resp.data['message'];
        Utils.showToast("$message");
      } else if (resp.status == ResponseStatus.ERROR) {
        Get.back();
        String? message = resp.data['message'];
        Utils.showToast("$message");
      } else {
        Get.back();
        String? message = resp.data['message'];
        Utils.showToast("$message");
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        _onBackButtonPressed(context);
        return true; // Return true to allow the pop action
      },
      child: Scaffold(
        appBar: CommonAppbar(titleTxt: "Add Details"),
        backgroundColor: Colors.black,
        extendBody: true,
        body: Stack(
          children: [
            CommonBlurLeft(),
            CommonBlurRight(),
            Stack(
              children: [
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                  child: Form(
                    key: _adddetailsform,
                    child: ListView(
                      physics: BouncingScrollPhysics(),
                      // mainAxisAlignment: MainAxisAlignment.start,
                      // crossAxisAlignment: CrossAxisAlignment.start,

                      children: [
                        Row(
                          children: [
                            text18W400("Full Name"),
                          ],
                        ),
                        SizedBox(
                          height: 15.h,
                        ),
                        CustomTextFormField(
                          textEditingController: fullName,
                        ),
                        SizedBox(
                          height: 30.h,
                        ),
                        Row(
                          children: [
                            text18W400("Email Address"),
                          ],
                        ),
                        SizedBox(
                          height: 15.h,
                        ),
                        CustomTextFormField(
                          textEditingController: email,
                          texttype: TextInputType.emailAddress,
                        ),
                        SizedBox(
                          height: 30.h,
                        ),
                        Row(
                          children: [
                            text18W400("Phone Number"),
                          ],
                        ),
                        SizedBox(
                          height: 15.h,
                        ),
                        CustomTextFormField(
                          textEditingController: phone,
                          texttype: TextInputType.phone,
                        ),
                        SizedBox(
                          height: 30.h,
                        ),
                        Row(
                          children: [
                            text18W400("Date Of Birth"),
                          ],
                        ),
                        SizedBox(
                          height: 15.h,
                        ),
                        CustomTextFormField(
                          textEditingController: dobcontroller,
                          suffixIcon: Icon(
                            Icons.calendar_month_outlined,
                            color: Colors.white,
                          ),
                          readonly: true,
                          onTap: () {
                            _selectDate(context);
                          },
                        ),
                        SizedBox(
                          height: 30.h,
                        ),
                        Row(
                          children: [
                            text18W400("City"),
                          ],
                        ),
                        SizedBox(
                          height: 15.h,
                        ),
                        CustomTextFormField(
                          textEditingController: city,
                        ),
                        SizedBox(
                          height: 40.h,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                Image.asset(
                                  "assets/images/png/whatsapp.png",
                                  height: 34.h,
                                  width: 34.w,
                                ),
                                SizedBox(
                                  width: 10.w,
                                ),
                                text18W600("Get Updates on WhatsApp"),
                              ],
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: [
                                Switch(
                                  value: isSwitched,
                                  onChanged: _toggleSwitch,
                                  activeTrackColor: Colors.green,
                                  activeColor: Colors.white,
                                  inactiveTrackColor: Colors.white,
                                  inactiveThumbColor: Colors.black,
                                ),
                              ],
                            ),
                          ],
                        ),
                        SizedBox(
                          height: 70.h,
                        ),
                        CommonBtn(
                          text: "Next",
                          onTap: () {
                            _addDetails();
                            // Get.toNamed(RouteName.kyc);
                          },
                        ),
                        SizedBox(
                          height: 10.h,
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Future<bool> _onBackButtonPressed(BuildContext context) async {
    bool? exitApp = await showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            backgroundColor: const Color(0xFFFFF3E4),
            title: const Text('Exit App'),
            content: const Text('Do you really want to close the app?'),
            actions: [
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop(false);
                },
                child: const Text(
                  'No',
                  style: TextStyle(
                    color: Color(0xff1B243D),
                  ),
                ),
              ),
              TextButton(
                onPressed: () {
                  SystemNavigator.pop();
                  Navigator.pop(context);
                },
                child: const Text(
                  'Yes',
                  style: TextStyle(
                    color: Color(0xff1B243D),
                  ),
                ),
              )
            ],
          );
        });
    return exitApp ?? false;
  }
}
