import 'dart:convert'; import 'dart:developer'; import 'dart:io'; import 'package:flutter/services.dart'; import 'package:wanisdriver/Screen/OtpVerificationScreen.dart'; import 'package:wanisdriver/utils/colors.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; import 'package:image_picker/image_picker.dart'; import 'package:provider/provider.dart'; import '../Provider/CarypeProvider.dart'; import '../Provider/CityProvider.dart'; import '../Provider/SignUp_provider.dart'; import '../Provider/language_provider.dart'; import '../Provider/sms_provider.dart'; import '../config/AppSnackbar.dart'; import '../config/constants/arabe.dart' as Language; import '../models/CarTypeModel.dart'; import '../models/CityModel.dart'; import '../services/pickSingleImage.dart'; import '../widgets/CustomDateFieldWidget.dart'; import '../widgets/CustomDropdownWidget.dart'; import '../widgets/CustomTextFieldWidget.dart'; import '../widgets/GenderSelectorWidget.dart'; import '../widgets/PhoneInputField.dart'; import '../widgets/SingleImagePickerWidget.dart'; import '../widgets/custom_button.dart'; import '../widgets/custom_text.dart'; import 'SignUpScreenVehicle.dart'; class SignUpScreenDriver extends StatefulWidget { const SignUpScreenDriver({super.key}); @override State createState() => _SignUpScreenDriverState(); } class _SignUpScreenDriverState extends State { final emailController = TextEditingController(); final idCardController = TextEditingController(); final LicenceCardController = TextEditingController(); final FullNameController = TextEditingController(); final VehicleBrandController = TextEditingController(); final VehicleModelController = TextEditingController(); final phoneController = TextEditingController(); final sexeController = TextEditingController(); // Custom brand and model controllers (when "Autre" is selected) final customBrandController = TextEditingController(); final customModelController = TextEditingController(); File? _selectedImage; // Car brands and models data List> carData = []; String? selectedBrand; String? selectedModel; List availableModels = []; bool isOtherBrandSelected = false; Future _pickImage() async { final ImagePicker picker = ImagePicker(); final XFile? pickedFile = await picker.pickImage(source: ImageSource.gallery); if (pickedFile != null) { setState(() { _selectedImage = File(pickedFile.path); }); } } String _phoneNumber = ''; String _countryCode = ''; String completePhoneNumber = ''; String? selectedCity; @override void initState() { super.initState(); _loadCarData(); WidgetsBinding.instance.addPostFrameCallback((_) { Provider.of(context, listen: false).reset(); Provider.of(context, listen: false).getLanguage(); Provider.of(context, listen: false).loadCities(); Provider.of(context, listen: false).loadCarType(); }); } Future _loadCarData() async { final String jsonString = await rootBundle.loadString('assets/data/car_brands.json'); final List jsonData = json.decode(jsonString); setState(() { carData = List>.from(jsonData); }); } void _onBrandSelected(String? brand) { setState(() { selectedBrand = brand; selectedModel = null; isOtherBrandSelected = brand == "Autre"; if (isOtherBrandSelected) { availableModels = []; customBrandController.clear(); customModelController.clear(); } else if (brand != null) { final brandData = carData.firstWhere( (item) => item['brand'] == brand, orElse: () => {'models': []}, ); availableModels = List.from(brandData['models'] ?? []); } else { availableModels = []; } }); } @override Widget build(BuildContext context) { final cityProvider = Provider.of(context); final languageProvider = context.watch(); bool isArabic = languageProvider.currentLangCode == Language.ar; final provider = context.watch(); final smsProvider = context.watch(); final carTypeProvider = Provider.of(context); // Get list of brands List brands = carData.map((item) => item['brand'] as String).toList(); return Scaffold( backgroundColor: Theme.of(context).brightness == Brightness.dark ? AppColors.blackBackgroundColor : AppColors.whiteBackgroundColor, appBar: AppBar( backgroundColor: Theme.of(context).brightness == Brightness.dark ? AppColors.blackBackgroundColor : AppColors.whiteBackgroundColor, elevation: 0, leading: Padding( padding: const EdgeInsets.all(8.0), child: Container( decoration: BoxDecoration( shape: BoxShape.circle, color: Theme.of(context).brightness == Brightness.dark ? Colors.grey.shade800 : Colors.grey.shade200, ), child: IconButton( icon: Icon( Icons.arrow_back, color: Theme.of(context).brightness == Brightness.dark ? AppColors.white : AppColors.black, size: 20, ), onPressed: () => Navigator.pop(context), ), ), ), title: Txt( text: "Create account", style: TextStyle( color: Theme.of(context).brightness == Brightness.dark ? AppColors.white : AppColors.black, fontSize: 18, fontWeight: FontWeight.w600, fontFamily: 'Poppins', ), ), centerTitle: true, ), body: SingleChildScrollView( padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 30), child: Column( children: [ Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 20), decoration: BoxDecoration( color: Theme.of(context).brightness == Brightness.dark ? AppColors.blackBackgroundColor : AppColors.whiteBackgroundColor, borderRadius: BorderRadius.circular(20), boxShadow: [ BoxShadow( color: Theme.of(context).brightness == Brightness.dark ? Colors.white24 : Colors.black12, blurRadius: 10, offset: const Offset(0, 5), ), ], ), child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ //Profile image GestureDetector( onTap: () { _pickImage(); if (_selectedImage != null) { provider.setProfileImage(File(_selectedImage!.path)); } }, child: CircleAvatar( radius: 45, backgroundColor: Colors.grey.shade200, backgroundImage: _selectedImage != null ? FileImage(_selectedImage!) : null, child: _selectedImage == null ? const Icon(Icons.camera_alt, color: Colors.grey) : null, ), ), const SizedBox(height: 30), //Full Name CustomTextFieldWidget( controller: FullNameController, label: 'Your Name', icon: Icons.person, isPassword: false, keybordType: TextInputType.text, isRequired: true, ), const SizedBox(height: 10), GenderSelector( initialValue: 'MALE', onChanged: (value) { sexeController.text = value; }, ), const SizedBox(height: 20), //Phone-number CustomPhoneInputField( isArabic: isArabic, onNumberChange: (phoneNumber) { setState(() { _phoneNumber = phoneNumber.number; _countryCode = phoneNumber.countryCode; phoneController.text = _countryCode + _phoneNumber; }); }, validator: (phoneNumber) { if (phoneNumber == null || phoneNumber.number.isEmpty) { return languageProvider .translate('Please enter a valid phone number'); } return null; }, ), const SizedBox(height: 20), //Email CustomTextFieldWidget( controller: emailController, label: 'Email', icon: Icons.email_outlined, isPassword: false, keybordType: TextInputType.emailAddress, isRequired: true, ), const SizedBox(height: 20), //City drop-down CustomDropdownWidget( label: 'Select City', icon: Icons.location_city, items: cityProvider.cities, hintText: "Select Your City", selectedItem: selectedCity, getItemLabel: (city) => city.city, required: true, onChanged: (value) { provider.setCity(value!); setState(() { selectedCity = value; }); }, ), const SizedBox(height: 20), //ID card number CustomTextFieldWidget( controller: idCardController, label: 'Id card number', icon: Icons.credit_card_outlined, isPassword: false, keybordType: TextInputType.number, isRequired: true, ), const SizedBox(height: 20), //Licence card number CustomTextFieldWidget( controller: LicenceCardController, label: 'Licence Number', icon: Icons.local_taxi_outlined, isPassword: false, keybordType: TextInputType.number, isRequired: true, ), const SizedBox(height: 20), // Vehicle Brand Dropdown CustomDropdownWidget( label: 'Vehicle Brand', icon: Icons.directions_car, items: brands, selectedItem: selectedBrand, required: true, hintText: "Select Brand", getItemLabel: (brand) => brand, onChanged: (value) { _onBrandSelected(value); if (!isOtherBrandSelected) { VehicleBrandController.text = value ?? ''; } }, ), const SizedBox(height: 20), // Show custom brand input if "Autre" is selected if (isOtherBrandSelected) ...[ CustomTextFieldWidget( controller: customBrandController, label: 'Enter Brand Name', hintText: "e.g., Tesla", icon: Icons.edit, isPassword: false, keybordType: TextInputType.text, isRequired: true, ), const SizedBox(height: 20), ], // Vehicle Model Dropdown (only show if brand is selected and not "Autre") if (!isOtherBrandSelected && selectedBrand != null) ...[ CustomDropdownWidget( label: 'Vehicle Model', icon: Icons.directions_car_outlined, items: availableModels, selectedItem: selectedModel, required: true, hintText: "Select Model", getItemLabel: (model) => model, onChanged: (value) { setState(() { selectedModel = value; VehicleModelController.text = value ?? ''; }); }, ), const SizedBox(height: 20), ], // Show custom model input if "Autre" is selected if (isOtherBrandSelected) ...[ CustomTextFieldWidget( controller: customModelController, label: 'Enter Model Name', hintText: "e.g., Model S", icon: Icons.edit, isPassword: false, keybordType: TextInputType.text, isRequired: true, ), const SizedBox(height: 20), ], const SizedBox(height: 20), //Next button CustomButton( borderRadius: 10, height: 50, isloading: smsProvider.loader, onClick: () async { final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$'); if (_selectedImage == null) { AppSnackbar.showError("Error", "Please select a profile image."); return; } if (phoneController.text.trim().isEmpty || int.tryParse(phoneController.text.trim()) == null) { AppSnackbar.showError("Error", "Phone number must be digits only."); return; } if (idCardController.text.trim().isEmpty) { AppSnackbar.showError("Error", "Please enter your id number."); return; } if (idCardController.text.trim().length != 8) { AppSnackbar.showError("Error", "The ID number must contain 8 numbers."); return; } if (sexeController.text.trim().isEmpty) { AppSnackbar.showError("Error", "Please select a gender."); return; } if (LicenceCardController.text.trim().isEmpty) { AppSnackbar.showError("Error", "Please enter your licence number."); return; } if (selectedCity == null || selectedCity!.isEmpty) { AppSnackbar.showError("Error", "Please select your city."); return; } if (FullNameController.text.trim().length < 3) { AppSnackbar.showError("Error", "Full name must be at least 3 characters."); return; } List nameParts = FullNameController.text.trim().split(' '); String firstName = nameParts.first; String lastName = nameParts.length > 1 ? nameParts.sublist(1).join(' ') : ''; if (firstName.length < 2) { AppSnackbar.showError("Error", "First name must be at least 2 characters."); return; } // Vehicle Brand Validation String finalBrand; if (isOtherBrandSelected) { if (customBrandController.text.trim().isEmpty) { AppSnackbar.showError("Error", "Please enter vehicle brand."); return; } if (customBrandController.text.trim().length < 2) { AppSnackbar.showError("Error", "Vehicle brand must be at least 2 characters."); return; } finalBrand = customBrandController.text.trim(); } else { if (selectedBrand == null || selectedBrand!.isEmpty) { AppSnackbar.showError("Error", "Please select vehicle brand."); return; } finalBrand = selectedBrand!; } // Vehicle Model Validation String finalModel; if (isOtherBrandSelected) { if (customModelController.text.trim().isEmpty) { AppSnackbar.showError("Error", "Please enter vehicle model."); return; } if (customModelController.text.trim().isEmpty) { AppSnackbar.showError("Error", "Vehicle model must be at least 2 characters."); return; } finalModel = customModelController.text.trim(); } else { if (selectedModel == null || selectedModel!.isEmpty) { AppSnackbar.showError("Error", "Please select vehicle model."); return; } finalModel = selectedModel!; } if (emailController.text.trim().isEmpty) { AppSnackbar.showError("Error", "Please enter your email address."); return; } if (!emailRegex.hasMatch(emailController.text.trim())) { AppSnackbar.showError("Error", "Please enter a valid email address."); return; } final provider = Provider.of(context, listen: false); final smsProvider = Provider.of(context, listen: false); // All validations passed provider.setDriverInfo( email: emailController.text.trim(), phone: phoneController.text.trim(), firstName: firstName, lastName: lastName, idCard: idCardController.text.trim(), carbrand: finalBrand, carmodel: finalModel, licencecard: LicenceCardController.text.trim(), city: selectedCity!, gender: sexeController.text.trim(), ); provider.setProfileImage(_selectedImage!); bool resultcheck = await smsProvider.checkphoneandemail( phoneController.text.trim(), emailController.text.trim()); if (!resultcheck) return; bool result = await smsProvider.send_sms(phoneController.text.trim()); log('test : $result'); if (!result) return; Navigator.push( context, MaterialPageRoute( builder: (_) => OtpVerificationScreen( phoneNumber: phoneController.text.trim(), )), ); }, title: 'Continue', width: MediaQuery.of(context).size.width, backgroundColor: Theme.of(context).brightness == Brightness.dark ? AppColors.darkPrimaryColor : AppColors.primaryColor, ), ], ), ), const SizedBox(height: 25), ], ), ), ); } }