import 'package:bookmywages/consts_widgets/app_assets.dart';
import 'package:bookmywages/consts_widgets/app_colors.dart';
import 'package:bookmywages/consts_widgets/comman_button.dart';
import 'package:bookmywages/consts_widgets/comman_textformfiled.dart';
import 'package:bookmywages/model/vendor_model/vendorregister_model.dart';
import 'package:bookmywages/routers/consts_router.dart';
import 'package:bookmywages/viewmodel/api_controller.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';

class VendorRegisterPage extends ConsumerStatefulWidget {
  const VendorRegisterPage({super.key});

  @override
  ConsumerState<VendorRegisterPage> createState() => _VendorRegisterPageState();
}

class _VendorRegisterPageState extends ConsumerState<VendorRegisterPage> {
  final _nameController = TextEditingController();
  final _numberController = TextEditingController();
  final _emailController = TextEditingController();
  final _locationController = TextEditingController();
  final _pincodeController = TextEditingController();
  final _aadharController = TextEditingController();
  final _panController = TextEditingController();
  final _licenseController = TextEditingController();
  final _passportController = TextEditingController();

  String? _nameError;
  String? _numberError;
  String? _emailError;

  void _validateName(String value) {
    setState(() => _nameError = value.isEmpty ? 'Name is required' : null);
  }

  void _validateNumber(String value) {
    setState(() {
      if (value.isEmpty) {
        _numberError = 'Phone number is required';
      } else if (!RegExp(r'^[0-9]{10}$').hasMatch(value)) {
        _numberError = 'Enter a valid 10-digit phone number';
      } else {
        _numberError = null;
      }
    });
  }

  void _validateEmail(String value) {
    setState(() {
      if (value.isEmpty) {
        _emailError = 'Email is required';
      } else if (!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(value)) {
        _emailError = 'Enter a valid email';
      } else {
        _emailError = null;
      }
    });
  }

  @override
  void dispose() {
    _nameController.dispose();
    _numberController.dispose();
    _emailController.dispose();
    _locationController.dispose();
    _pincodeController.dispose();
    _aadharController.dispose();
    _panController.dispose();
    _licenseController.dispose();
    _passportController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    final double horizontalPadding = screenSize.width * 0.05;
    final double imageHeight = screenSize.height * 0.45;

    return Scaffold(
      backgroundColor: AppColors.secondprimary,
      resizeToAvoidBottomInset: true,
      body: SingleChildScrollView(
        child: Column(
          children: [
            Image.asset(
              AppAssets.login,
              width: screenSize.width,
              height: imageHeight,
              fit: BoxFit.cover,
            ),
            Transform.translate(
              offset: const Offset(0, -100),
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: horizontalPadding),
                child: Container(
                  width: double.infinity,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(32.73),
                    border: Border.all(
                      width: 1.09,
                      color: const Color(0xFFA39898),
                    ),
                    boxShadow: const [
                      BoxShadow(
                        offset: Offset(0, -4),
                        blurRadius: 12.3,
                        color: Color(0x66E0E0E0),
                      ),
                      BoxShadow(
                        offset: Offset(0, 4),
                        blurRadius: 4,
                        color: Color(0x66000000),
                      ),
                    ],
                    color: Colors.white,
                  ),
                  child: Padding(
                    padding: EdgeInsets.all(screenSize.width * 0.05),
                    child: Column(
                      children: [
                        const SizedBox(height: 20),
                        const Text(
                          "Vendor Registration",
                          style: TextStyle(
                            fontSize: 25,
                            fontFamily: "Gilroy-ExtraBold",
                            fontWeight: FontWeight.w800,
                            height: 1.0,
                            letterSpacing: 0.64,
                          ),
                        ),
                        SizedBox(height: screenSize.height * 0.03),

                        CommonTextFormField(
                          controller: _nameController,
                          hintText: 'Enter your name',
                          prefixIcon: const Icon(
                            Icons.person,
                            color: AppColors.hittext,
                          ),
                          errorText: _nameError,
                          onChanged: _validateName,
                        ),
                        SizedBox(height: screenSize.height * 0.03),

                        CommonTextFormField(
                          controller: _numberController,
                          hintText: 'Enter your number',
                          prefixIcon: const Icon(
                            Icons.phone_android,
                            color: AppColors.hittext,
                          ),
                          errorText: _numberError,
                          onChanged: _validateNumber,
                        ),
                        SizedBox(height: screenSize.height * 0.03),

                        CommonTextFormField(
                          controller: _emailController,
                          hintText: 'Enter your E-mail Id',
                          prefixIcon: const Icon(
                            Icons.email,
                            color: AppColors.hittext,
                          ),
                          errorText: _emailError,
                          onChanged: _validateEmail,
                        ),
                        SizedBox(height: screenSize.height * 0.03),

                        CommonTextFormField(
                          controller: _locationController,
                          hintText: 'Location',
                          prefixIcon: const Icon(
                            Icons.location_on,
                            color: AppColors.hittext,
                          ),
                        ),
                        SizedBox(height: screenSize.height * 0.03),

                        CommonTextFormField(
                          controller: _pincodeController,
                          hintText: 'Pin code',
                          prefixIcon: const Icon(
                            Icons.pin_drop,
                            color: AppColors.hittext,
                          ),
                        ),
                        SizedBox(height: screenSize.height * 0.03),

                        CommonTextFormField(
                          controller: _aadharController,
                          hintText: 'Aadhar card number',
                          prefixIcon: const Icon(
                            Icons.badge,
                            color: AppColors.hittext,
                          ),
                        ),
                        SizedBox(height: screenSize.height * 0.03),

                        CommonTextFormField(
                          controller: _panController,
                          hintText: 'Pan card number',
                          prefixIcon: const Icon(
                            Icons.fact_check,
                            color: AppColors.hittext,
                          ),
                        ),
                        SizedBox(height: screenSize.height * 0.03),

                        CommonTextFormField(
                          controller: _licenseController,
                          hintText: 'Driving License number',
                          prefixIcon: const Icon(
                            Icons.directions_car,
                            color: AppColors.hittext,
                          ),
                        ),
                        SizedBox(height: screenSize.height * 0.03),

                        CommonTextFormField(
                          controller: _passportController,
                          hintText: 'Passport number',
                          prefixIcon: const Icon(
                            Icons.flight,
                            color: AppColors.hittext,
                          ),
                        ),
                        SizedBox(height: screenSize.height * 0.04),

                        CommanButton(
                          text: 'Submit',
                          textStyle: const TextStyle(
                            fontFamily: 'Gilroy-Black',
                            fontWeight: FontWeight.w800,
                            fontSize: 20,
                            height: 1.0,
                            color: AppColors.secondprimary,
                          ),
                          onPressed: () async {
                            _validateName(_nameController.text);
                            _validateNumber(_numberController.text);
                            _validateEmail(_emailController.text);

                            if (_nameError == null &&
                                _numberError == null &&
                                _emailError == null) {
                              final model = VendorRegisterModel(
                                name: _nameController.text.trim(),
                                number: _numberController.text.trim(),
                                email: _emailController.text.trim(),
                                location: _locationController.text.trim(),
                                pincode: _pincodeController.text.trim(),
                                aadharCard: _aadharController.text.trim(),
                                panCard: _panController.text.trim(),
                                drivingLicense: _licenseController.text.trim(),
                                passport: _passportController.text.trim(),
                              );

                              try {
                                final response = await ref.read(
                                  vendorRegisterFutureProvider(model).future,
                                );
                                print('API Response: $response');

                                _showVerificationDialog(context);
                              } catch (e) {
                                print("Registration Error: $e");
                                Fluttertoast.showToast(
                                  msg: "Error: $e",
                                  toastLength: Toast.LENGTH_SHORT,
                                  gravity: ToastGravity.BOTTOM,
                                );
                              }
                            }
                          },
                          isPrimary: true,
                          backgroundColor: AppColors.primary,
                          textColor: AppColors.secondprimary,
                          width: 230,
                        ),
                        const SizedBox(height: 30),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _showVerificationDialog(BuildContext context) {
    showDialog(
      context: context,
      barrierDismissible: false, // Prevent closing by tapping outside
      builder: (BuildContext context) {
        return Dialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(30),
            side: const BorderSide(color: Colors.white, width: 1),
          ),
          elevation: 10,
          backgroundColor: Colors.white,
          child: Container(
            width: 365,
            height: 305,
            padding: const EdgeInsets.all(20),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Text(
                  'Verification',
                  style: TextStyle(
                    fontFamily: 'Gilroy-Bold',
                    fontWeight: FontWeight.w700,
                    fontSize: 32,
                    height: 1.0,
                    letterSpacing: 0.32,
                  ),
                ),
                const SizedBox(height: 20),
                const Text(
                  'Still your account will not verify by Admin, please wait with us.',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontFamily: 'Gilroy-Bold',
                    fontWeight: FontWeight.w700,
                    fontSize: 20.23,
                    height: 1.74,
                    letterSpacing: 0.2023,
                  ),
                ),
                const SizedBox(height: 30),
                ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFF0066FF),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(29.36),
                    ),
                    padding: const EdgeInsets.symmetric(
                      horizontal: 50,
                      vertical: 15,
                    ),
                  ),
                  onPressed: () {
                    Navigator.of(context).pop(); // Close dialog
                    Get.toNamed(RouterConts.homescreen);
                  },
                  child: const Text(
                    'OK',
                    style: TextStyle(
                      fontFamily: 'Gilroy-Black',
                      fontWeight: FontWeight.w400,
                      fontSize: 20.29,
                      height: 1.0,
                      letterSpacing: 0.4058,
                      color: Colors.white,
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
