import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:supplier_new/signup/verification_screen.dart';
import 'package:geolocator/geolocator.dart';
import 'package:geocoding/geocoding.dart';
import '../common/settings.dart';

class SignUp extends StatefulWidget {
  var mobileNumber;
  var password;
  SignUp({
    this.mobileNumber,this.password
  });

  @override
  State<SignUp> createState() => _SignUpState();
}

class _SignUpState extends State<SignUp> {
  double? latitude;
  double? longitude;
  final TextEditingController businessNameController = TextEditingController();
  final TextEditingController registrationNumberController = TextEditingController();
  final TextEditingController yearsInBusinessController = TextEditingController();
  final TextEditingController contactNameController = TextEditingController();
  final TextEditingController positionController = TextEditingController();
  final TextEditingController mobileNumberController = TextEditingController();
  final TextEditingController additionalMobileController = TextEditingController();
  final TextEditingController emailController = TextEditingController();
  final TextEditingController addressLine1Controller = TextEditingController();
  final TextEditingController addressLine2Controller = TextEditingController();
  final TextEditingController cityController = TextEditingController();
  final TextEditingController stateController = TextEditingController();
  final TextEditingController zipController = TextEditingController();

  final storage = FlutterSecureStorage(
    aOptions: AndroidOptions(
      resetOnError: true,
      encryptedSharedPreferences: true,
    ),
  );

  Future<void> getLocationFromMap() async {

    bool serviceEnabled;
    LocationPermission permission;

    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      return;
    }

    permission = await Geolocator.checkPermission();

    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
    }

    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);

    /// Save latitude & longitude
    latitude = position.latitude;
    longitude = position.longitude;

    List<Placemark> placemarks =
    await placemarkFromCoordinates(latitude!, longitude!);

    Placemark place = placemarks[0];

    setState(() {

      addressLine1Controller.text =
      "${place.street}, ${place.subLocality}";

      addressLine2Controller.text = place.locality ?? "";

      cityController.text = place.locality ?? "";

      stateController.text = place.administrativeArea ?? "";

      zipController.text = place.postalCode ?? "";

    });

  }
  @override
  void initState() {
    super.initState();
    mobileNumberController.text = widget.mobileNumber ?? '';

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        scrolledUnderElevation: 0,

      ),
      backgroundColor: Colors.white,
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Top image
            Container(
              width: 24,
              height: 24,
              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('images/business.png'),
                  fit: BoxFit.contain, // Optional: can also use BoxFit.cover
                ),
              ),
            ),

            const SizedBox(height: 12),

            Text(
              'Tell us about your water tanker business',
              style: fontTextStyle(12,   Color(0xFF2D2E30),FontWeight.w400),
            ),

            const SizedBox(height: 24),

            Text(
              "BUSINESS REGISTRATION",
              style: fontTextStyle(10,   Color(0xFF2D2E30),FontWeight.w600),
            ),
            const SizedBox(height: 10),

            _buildTextField('Business Name *', 'Enter your Business Name',businessNameController),
            _buildTextField('Registration Number *', 'Business Registration Number',registrationNumberController),
            _buildTextField('Years in Business *', 'Years of operation',yearsInBusinessController),

            const SizedBox(height: 24),
            Text(
              "CONTACT INFORMATION",
              style: fontTextStyle(10,   Color(0xFF2D2E30),FontWeight.w600),
            ),
            const SizedBox(height: 10),

            _buildTextField('Primary Contact Name *', 'Full Name',contactNameController),
            // _buildTextField('Position/Title *', 'Job title',positionController),
            _buildTextField('Mobile Number *', 'Mobile Number',mobileNumberController,readOnly: true),
            _buildTextField('Additional Mobile Number', 'Alternate Number',additionalMobileController),
            _buildTextField('Email Address', 'Email Address',emailController),

            const SizedBox(height: 24),
            Text(
              "BUSINESS ADDRESS",
              style: fontTextStyle(10,   Color(0xFF2D2E30),FontWeight.w600),
            ),
            const SizedBox(height: 10),
            Padding(
                padding: const EdgeInsets.only(left: 90.0),
                child: InkWell(
                  onTap: () {
                    getLocationFromMap();
                  },
                  child: Row(
                    children: [
                      Image.asset(
                        'images/maps.png',
                        width: 20,
                        height: 20,
                        color: primaryColor,
                      ),
                      const SizedBox(width: 8),
                      Text(
                        "Add Location from Maps",
                        style: fontTextStyle(
                            14, const Color(0xFF2D2E30), FontWeight.w500),
                      ),
                    ],
                  ),
                )
            ),
            Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SizedBox(height: 20),

                Text(
                  "Please check the below address for accuracy please change as required by clicking in the box",
                  textAlign: TextAlign.center,
                  style: fontTextStyle(
                      12,
                      Color(0xFF2D2E30),
                      FontWeight.w500),
                ),
              ],
            ),
            const SizedBox(height: 20),
            _buildTextField('Address Line 1 *', '123 Main St',addressLine1Controller),
            _buildTextField('Address Line 2(Optional)', 'Area',addressLine2Controller),
            _buildTextField('City *', 'City',cityController),
            _buildTextField('State/Province *', 'State',stateController),
            _buildTextField('ZIP/Postal Code *', '12345',zipController),

            const SizedBox(height: 10),

            SizedBox(
              width: double.infinity,
              child: ElevatedButton(
                onPressed: () async{
                  if (businessNameController.text != ''&&
                      registrationNumberController.text != ''&&
                  yearsInBusinessController.text != ''&&
                      contactNameController.text != ''&&
                      mobileNumberController.text != ''&&
                      addressLine1Controller.text != ''&&
                      addressLine2Controller.text != ''&&
                      cityController.text != ''&&
                      stateController.text != ''&&
                      zipController.text != ''
                  ) {
                    AppSettings.preLoaderDialog(context);

                    bool isOnline = await AppSettings.internetConnectivity();

                    if(isOnline){
                      SharedPreferences prefs = await SharedPreferences.getInstance();
                      String? fcmToken = prefs.getString('fcmToken');
                      var payload = new Map<String, dynamic>();

                  payload["suppliername"] = contactNameController.text.toString();
                  payload["phone"] = mobileNumberController.text.toString();
                  payload["alternativeContactNumber"] = additionalMobileController.text.toString();
                  payload["password"] = widget.password;
                  payload["emails"] = [
                  {"email": emailController.text.toString()}
                  ];

                  payload["office_address"] = addressLine1Controller.text.toString();
                  payload["city"] = cityController.text.toString();
                  payload["state"] = stateController.text.toString();
                  payload["zip"] = zipController.text.toString();
                  payload["country"] = '';
                  payload["latitude"] = latitude ?? 0;
                  payload["longitude"] = longitude ?? 0;
                  payload["fcmId"] = fcmToken;
                  payload["description"] ='';
                  payload["bussinessname"] = businessNameController.text.toString();
                  payload["registration_number"] = registrationNumberController.text.toString();
                  payload["years_in_business"] = yearsInBusinessController.text.toString();


                      bool signinStatus = await AppSettings.signUp(payload);

                      try{
                        if (signinStatus) {
                          Navigator.of(context,rootNavigator: true).pop();
                         /* String token = AppSettings.accessToken;
                          await storage.write(key: 'authToken', value: token);*/
                          Navigator.push(
                            context,
                            MaterialPageRoute(builder: (context) => VerificationScreen()),
                          );
                          AppSettings.longSuccessToast("Logged in Successfully");

                        } else {
                          Navigator.of(context,rootNavigator: true).pop();
                          AppSettings.longFailedToast("Invalid details");
                        }
                      }
                      catch(exception){
                        Navigator.of(context,rootNavigator: true).pop();
                        print(exception);
                      }
                    }
                    else{
                      Navigator.of(context,rootNavigator: true).pop();
                      AppSettings.longFailedToast("Please Check internet");
                    }
                  }
                  else{

                    AppSettings.longFailedToast("Please enter valid details");
                  }



                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: primaryColor,
                  padding: const EdgeInsets.symmetric(vertical: 16),
                ),

                child: Text(
                  'Submit',
                  style: fontTextStyle(16, Color(0XFFFFFFFF), FontWeight.w600),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTextField(String label, String hint,TextEditingController controller, {bool readOnly = false}) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: fontTextStyle(12,   Color(0xFF2D2E30),FontWeight.w500),
        ),
        const SizedBox(height: 6),
        TextFormField(
          controller: controller,
          readOnly: readOnly,
          textCapitalization: TextCapitalization.sentences,
          style:fontTextStyle(14,Color(0XFF2A2A2A),FontWeight.w400),
          cursorColor: Color(0XFF8270DB),
          decoration: textFormFieldDecorationHintText(Icons.phone,hint),
        ),
        const SizedBox(height: 16),
      ],
    );
  }
}

