import 'package:bookmywages/consts_widgets/app_assets.dart';
import 'package:bookmywages/consts_widgets/app_colors.dart';
import 'package:bookmywages/consts_widgets/comman_textformfiled.dart';
import 'package:bookmywages/model/vendor_model/vendor_serviceupload_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';
import 'package:get/get_core/src/get_main.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';

import 'package:shared_preferences/shared_preferences.dart';

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

  @override
  ConsumerState<VendorCatgories> createState() => _VendorCatgoriesState();
}

class _VendorCatgoriesState extends ConsumerState<VendorCatgories> {
  String? selectedCategory;
  String? selectedSubCategory;
  String? selectedWorkingHours;
  String? selectedWorkingDuration;
  String? selectedServiceType;
  List<File> selectedImages = [];
  List<String> videoLinks = [];
  TextEditingController videoLinkController = TextEditingController();
  TextEditingController nameController = TextEditingController();
  TextEditingController serviceNameController = TextEditingController();
  TextEditingController serviceAmountController = TextEditingController();
  TextEditingController serviceDetailsController = TextEditingController();
  TextEditingController locationController = TextEditingController();
  TextEditingController descriptionController = TextEditingController();

  // Validation error messages
  String? nameError;
  String? serviceNameError;
  String? categoryError;
  String? subCategoryError;
  String? workingHoursError;
  String? workingDurationError;
  String? serviceTypeError;
  String? serviceAmountError;
  String? serviceDetailsError;
  String? locationError;
  String? imagesError;

  List<dynamic> categories = [];
  List<dynamic> subcategories = [];
  bool isLoading = true;

  @override
  void initState() {
    super.initState();
    _fetchCategories();

    // Add listeners to clear validation errors when typing
    nameController.addListener(() {
      if (nameError != null && nameController.text.isNotEmpty) {
        setState(() => nameError = null);
      }
    });

    serviceNameController.addListener(() {
      if (serviceNameError != null && serviceNameController.text.isNotEmpty) {
        setState(() => serviceNameError = null);
      }
    });

    serviceAmountController.addListener(() {
      if (serviceAmountError != null &&
          serviceAmountController.text.isNotEmpty) {
        setState(() => serviceAmountError = null);
      }
    });

    serviceDetailsController.addListener(() {
      if (serviceDetailsError != null &&
          serviceDetailsController.text.isNotEmpty) {
        setState(() => serviceDetailsError = null);
      }
    });

    locationController.addListener(() {
      if (locationError != null && locationController.text.isNotEmpty) {
        setState(() => locationError = null);
      }
    });

    // Add listener for description controller even though it's optional
    descriptionController.addListener(() {
      if (descriptionController.text.isNotEmpty) {
        // No error for description as it's optional, but added for consistency
      }
    });

    // Add listener for video link controller
    videoLinkController.addListener(() {
      // No error for video links as they're optional, but added for consistency
    });
  }

  @override
  void dispose() {
    nameController.dispose();
    serviceNameController.dispose();
    serviceAmountController.dispose();
    serviceDetailsController.dispose();
    locationController.dispose();
    descriptionController.dispose();
    videoLinkController.dispose();
    super.dispose();
  }

  Future<void> _fetchCategories() async {
    try {
      final categoryData = await ref.read(categoryListProvider.future);
      setState(() {
        categories = categoryData;
        isLoading = false;
      });
    } catch (e) {
      setState(() {
        isLoading = false;
      });
      print('Error fetching categories: $e');
    }
  }

  Future<void> _fetchSubcategories(String categoryId) async {
    setState(() {
      isLoading = true;
      subcategories = [];
      selectedSubCategory =
          null; // Reset selected subcategory when category changes
      subCategoryError = null; // Clear subcategory error when fetching new ones
    });

    try {
      final subcategoryData = await ref.read(
        subcategoryProvider(categoryId).future,
      );
      setState(() {
        subcategories = subcategoryData;
        isLoading = false;
      });
    } catch (e) {
      setState(() {
        isLoading = false;
      });
      print('Error fetching subcategories: $e');
    }
  }

  Future<void> _pickImages() async {
    final picker = ImagePicker();
    final pickedFiles = await picker.pickMultiImage();

    if (pickedFiles.isNotEmpty) {
      List<File> validImages = [];

      for (final pickedFile in pickedFiles) {
        final file = File(pickedFile.path);
        final bytes = await file.length(); // get size in bytes
        final sizeInMB = bytes / (1024 * 1024); // convert to MB

        if (sizeInMB <= 2) {
          validImages.add(file);
        }
      }

      if (validImages.isEmpty) {
        setState(() {
          imagesError = 'Each image must be less than 2MB';
        });
      } else {
        setState(() {
          selectedImages.addAll(validImages);
          imagesError = null;
        });
      }
    }
  }

  void _addVideoLink() {
    if (videoLinkController.text.trim().isNotEmpty) {
      setState(() {
        videoLinks.add(videoLinkController.text.trim());
        videoLinkController.clear();
      });
    }
  }

  void _removeImage(int index) {
    setState(() {
      selectedImages.removeAt(index);
      // Re-validate images if list becomes empty
      if (selectedImages.isEmpty) {
        imagesError = 'Please upload at least one image';
      }
    });
  }

  void _removeVideoLink(int index) {
    setState(() {
      videoLinks.removeAt(index);
    });
  }

  bool _validateForm() {
    bool isValid = true;

    if (nameController.text.isEmpty) {
      setState(() => nameError = 'Please enter your name');
      isValid = false;
    }

    if (serviceNameController.text.isEmpty) {
      setState(() => serviceNameError = 'Please enter service name');
      isValid = false;
    }

    if (selectedCategory == null) {
      setState(() => categoryError = 'Please select a category');
      isValid = false;
    }

    if (selectedSubCategory == null) {
      setState(() => subCategoryError = 'Please select a sub-category');
      isValid = false;
    }

    if (selectedWorkingHours == null) {
      setState(() => workingHoursError = 'Please select working hours');
      isValid = false;
    }

    if (selectedWorkingDuration == null) {
      setState(() => workingDurationError = 'Please select working duration');
      isValid = false;
    }

    if (selectedServiceType == null) {
      setState(() => serviceTypeError = 'Please select service type');
      isValid = false;
    }

    // if (serviceAmountController.text.isEmpty) {
    //   setState(() => serviceAmountError = 'Please enter service amount');
    //   isValid = false;
    // }

    if (serviceDetailsController.text.isEmpty) {
      setState(() => serviceDetailsError = 'Please enter service details');
      isValid = false;
    }

    if (locationController.text.isEmpty) {
      setState(() => locationError = 'Please enter location');
      isValid = false;
    }

    if (selectedImages.isEmpty) {
      setState(() => imagesError = 'Please upload at least one image');
      isValid = false;
    }

    return isValid;
  }

  List<String> generateWorkingHours() {
    List<String> workingHours = [];
    TimeOfDay startTime = TimeOfDay(hour: 9, minute: 0);
    TimeOfDay endTime = TimeOfDay(hour: 18, minute: 0);

    while (startTime.hour < endTime.hour ||
        (startTime.hour == endTime.hour &&
            startTime.minute <= endTime.minute)) {
      final hour = startTime.hourOfPeriod.toString().padLeft(2, '0');
      final minute = startTime.minute.toString().padLeft(2, '0');
      final period = startTime.period == DayPeriod.am ? 'am' : 'pm';
      workingHours.add('$hour:$minute $period');

      int newMinute = startTime.minute + 30;
      int newHour = startTime.hour;
      if (newMinute >= 60) {
        newMinute -= 60;
        newHour += 1;
      }
      startTime = TimeOfDay(hour: newHour, minute: newMinute);
    }

    return workingHours;
  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    final keyboardOpen = MediaQuery.of(context).viewInsets.bottom > 0;

    return GestureDetector(
      onTap: () => FocusScope.of(context).unfocus(),
      child: Scaffold(
        backgroundColor: AppColors.secondprimary,
        resizeToAvoidBottomInset: false,
        body: SingleChildScrollView(
          padding: EdgeInsets.only(bottom: keyboardOpen ? 20 : 0),
          child: Column(
            children: [
              Image.asset(
                AppAssets.login,
                width: screenSize.width,
                height: screenSize.height * 0.45,
                fit: BoxFit.cover,
              ),
              Transform.translate(
                offset: const Offset(0, -100),
                child: Padding(
                  padding: EdgeInsets.symmetric(
                    horizontal: screenSize.width * 0.05,
                  ),
                  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 Text(
                            "Service Upload",
                            style: TextStyle(
                              fontSize: 25,
                              fontFamily: "Gilroy-ExtraBold",
                              fontWeight: FontWeight.w800,
                              height: 1.0,
                              letterSpacing: 0.64,
                            ),
                          ),
                          const SizedBox(height: 25),
                          CommonTextFormField(
                            controller: nameController,
                            hintText: 'Enter your name',
                            errorText: nameError,
                            prefixIcon: const Icon(
                              Icons.person,
                              color: AppColors.hittext,
                            ),
                          ),
                          const SizedBox(height: 20),
                          CommonTextFormField(
                            controller: serviceNameController,
                            hintText: 'Service name',
                            errorText: serviceNameError,
                            prefixIcon: const Icon(
                              Icons.build,
                              color: AppColors.hittext,
                            ),
                          ),
                          const SizedBox(height: 20),
                          DropdownButtonFormField<String>(
                            decoration: _buildDropdownDecoration(
                              'Select Categories',
                              Icons.category,
                              errorText: categoryError,
                            ),
                            value: selectedCategory,
                            items: _buildCategoryItems(),
                            onChanged: (value) {
                              setState(() {
                                selectedCategory = value;
                                selectedSubCategory = null;
                                categoryError = null;
                              });
                              if (value != null) _fetchSubcategories(value);
                            },
                            isExpanded: true,
                          ),
                          const SizedBox(height: 20),
                          DropdownButtonFormField<String>(
                            decoration: _buildDropdownDecoration(
                              'Select Sub-categories',
                              Icons.list,
                              errorText: subCategoryError,
                            ),
                            value: selectedSubCategory,
                            items: _buildSubcategoryItems(),
                            onChanged: subcategories.isNotEmpty
                                ? (value) {
                                    setState(() {
                                      selectedSubCategory = value;
                                      subCategoryError = null;
                                    });
                                  }
                                : null,
                            isExpanded: true,
                          ),
                          const SizedBox(height: 20),
                          DropdownButtonFormField<String>(
                            decoration: _buildDropdownDecoration(
                              'Select Working Hours',
                              Icons.access_time,
                              errorText: workingHoursError,
                            ),
                            value: selectedWorkingHours,
                            items: generateWorkingHours()
                                .map(
                                  (e) => DropdownMenuItem<String>(
                                    value: e,
                                    child: Text(e),
                                  ),
                                )
                                .toList(),
                            onChanged: (value) {
                              setState(() {
                                selectedWorkingHours = value;
                                workingHoursError = null;
                              });
                            },
                            isExpanded: true,
                            menuMaxHeight: 300,
                          ),
                          const SizedBox(height: 20),
                          DropdownButtonFormField<String>(
                            decoration: _buildDropdownDecoration(
                              'Select Working Duration',
                              Icons.timelapse,
                              errorText: workingDurationError,
                            ),
                            value: selectedWorkingDuration,
                            items:
                                [
                                      '01:00 hours',
                                      '02:00 hours',
                                      '03:00 hours',
                                      '04:00 hours',
                                      '05:00 hours',
                                      '06:00 hours',
                                    ]
                                    .map(
                                      (e) => DropdownMenuItem<String>(
                                        value: e,
                                        child: Text(e),
                                      ),
                                    )
                                    .toList(),
                            onChanged: (value) {
                              setState(() {
                                selectedWorkingDuration = value;
                                workingDurationError = null;
                              });
                            },
                            isExpanded: true,
                          ),
                          const SizedBox(height: 20),
                          DropdownButtonFormField<String>(
                            decoration: _buildDropdownDecoration(
                              'Service Free or Paid',
                              Icons.money,
                              errorText: serviceTypeError,
                            ),
                            value: selectedServiceType,
                            items: ['Free Service', 'Paid Service']
                                .map(
                                  (e) => DropdownMenuItem<String>(
                                    value: e,
                                    child: Text(e),
                                  ),
                                )
                                .toList(),
                            onChanged: (value) {
                              setState(() {
                                selectedServiceType = value;
                                serviceTypeError = null;
                                // Clear the amount when switching to free service
                                if (value == 'Free Service') {
                                  serviceAmountController.clear();
                                  serviceAmountError = null;
                                }
                              });
                            },
                            isExpanded: true,
                          ),
                          const SizedBox(height: 20),
                          // Conditionally show the service amount field
                          if (selectedServiceType == 'Paid Service') ...[
                            CommonTextFormField(
                              controller: serviceAmountController,
                              hintText: 'Service Amount',
                              errorText: serviceAmountError,
                              prefixIcon: const Icon(
                                Icons.currency_rupee,
                                color: AppColors.hittext,
                              ),
                              keyboardType: TextInputType.number,
                            ),
                            const SizedBox(height: 20),
                          ],
                          CommonTextFormField(
                            controller: serviceDetailsController,
                            hintText: 'Service Details',
                            errorText: serviceDetailsError,
                            prefixIcon: const Icon(
                              Icons.description,
                              color: AppColors.hittext,
                            ),
                          ),
                          const SizedBox(height: 20),
                          CommonTextFormField(
                            controller: locationController,
                            hintText: 'Location',
                            errorText: locationError,
                            prefixIcon: const Icon(
                              Icons.location_on,
                              color: AppColors.hittext,
                            ),
                          ),
                          const SizedBox(height: 20),
                          CommonTextFormField(
                            controller: descriptionController,
                            hintText: 'Description (Optional)',
                            prefixIcon: Padding(
                              padding: const EdgeInsets.only(bottom: 48),
                              child: Icon(
                                Icons.description,
                                color: AppColors.hittext,
                              ),
                            ),
                            maxLines: 5,
                            minLines: 3,
                            keyboardType: TextInputType.multiline,
                          ),
                          const SizedBox(height: 20),
                          // Image Upload Section
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              GestureDetector(
                                onTap: _pickImages,
                                child: Container(
                                  width: 349,
                                  height: 56.12,
                                  decoration: BoxDecoration(
                                    color: Colors.white,
                                    borderRadius: BorderRadius.circular(15.78),
                                    border: Border.all(
                                      color: const Color(0xFFBDBCBC),
                                      width: 0.88,
                                    ),
                                  ),
                                  child: const Center(
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      children: [
                                        Icon(
                                          Icons.image,
                                          color: AppColors.hittext,
                                        ),
                                        SizedBox(width: 10),
                                        Text(
                                          'Upload Images',
                                          style: TextStyle(
                                            color: AppColors.hittext,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ),
                              if (imagesError != null)
                                Padding(
                                  padding: const EdgeInsets.only(
                                    left: 16,
                                    top: 8,
                                  ),
                                  child: Text(
                                    imagesError!,
                                    style: TextStyle(
                                      color: Colors.red[700],
                                      fontSize: 12,
                                    ),
                                  ),
                                ),
                            ],
                          ),

                          // Display selected images
                          if (selectedImages.isNotEmpty) ...[
                            const SizedBox(height: 10),
                            SizedBox(
                              height: 100,
                              child: ListView.builder(
                                scrollDirection: Axis.horizontal,
                                itemCount: selectedImages.length,
                                itemBuilder: (context, index) {
                                  return Padding(
                                    padding: const EdgeInsets.only(right: 10),
                                    child: Stack(
                                      children: [
                                        Container(
                                          width: 90,
                                          height: 90,
                                          decoration: BoxDecoration(
                                            borderRadius: BorderRadius.circular(
                                              16,
                                            ),
                                            image: DecorationImage(
                                              image: FileImage(
                                                selectedImages[index],
                                              ),
                                              fit: BoxFit.cover,
                                            ),
                                          ),
                                        ),
                                        Positioned(
                                          top: 0,
                                          right: 0,
                                          child: GestureDetector(
                                            onTap: () => _removeImage(index),
                                            child: AnimatedContainer(
                                              duration: const Duration(
                                                milliseconds: 200,
                                              ),
                                              curve: Curves.easeInOut,
                                              width: 20,
                                              height: 18,
                                              decoration: BoxDecoration(
                                                color: Colors.red.withOpacity(
                                                  0.8,
                                                ),
                                                shape: BoxShape.circle,
                                              ),
                                              child: const Center(
                                                child: Icon(
                                                  Icons.close,
                                                  color: Colors.white,
                                                  size: 13,
                                                ),
                                              ),
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  );
                                },
                              ),
                            ),
                          ],
                          const SizedBox(height: 20),
                          // Video Links Section
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                children: [
                                  Expanded(
                                    child: CommonTextFormField(
                                      controller: videoLinkController,
                                      hintText:
                                          'Add YouTube video link (Optional)',
                                      prefixIcon: const Icon(
                                        Icons.video_library,
                                        color: AppColors.hittext,
                                      ),
                                    ),
                                  ),
                                  IconButton(
                                    icon: const Icon(
                                      Icons.add,
                                      color: AppColors.primary,
                                    ),
                                    onPressed: _addVideoLink,
                                  ),
                                ],
                              ),
                              const SizedBox(height: 4),
                              const Text(
                                'Optional - Add videos of your service',
                                style: TextStyle(
                                  fontSize: 12,
                                  color: Colors.grey,
                                ),
                              ),
                            ],
                          ),
                          // Display added video links
                          if (videoLinks.isNotEmpty) ...[
                            const SizedBox(height: 10),
                            Column(
                              children: videoLinks.map((link) {
                                return ListTile(
                                  leading: const Icon(
                                    Icons.video_library,
                                    color: AppColors.primary,
                                  ),
                                  title: Text(
                                    link,
                                    maxLines: 1,
                                    style: const TextStyle(fontSize: 13),
                                  ),
                                  trailing: IconButton(
                                    icon: const Icon(
                                      Icons.close,
                                      size: 23,
                                      color: Colors.red,
                                    ),
                                    onPressed: () => _removeVideoLink(
                                      videoLinks.indexOf(link),
                                    ),
                                  ),
                                );
                              }).toList(),
                            ),
                          ],
                          const SizedBox(height: 30),
                          SizedBox(
                            width: double.infinity,
                            child: ElevatedButton(
                              style: ElevatedButton.styleFrom(
                                backgroundColor: AppColors.primary,
                                padding: const EdgeInsets.symmetric(
                                  vertical: 16,
                                ),
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(10),
                                ),
                              ),
                              onPressed: () async {
                                if (_validateForm()) {
                                  // Show loading indicator
                                  showDialog(
                                    context: context,
                                    barrierDismissible: false,
                                    builder: (context) => const Center(
                                      child: CircularProgressIndicator(
                                        color: AppColors.primary,
                                      ),
                                    ),
                                  );

                                  try {
                                    // Get user ID from shared preferences or other storage
                                    final prefs =
                                        await SharedPreferences.getInstance();
                                    final dataid = prefs.getString('vendor_id');

                                    // Create the model
                                    final model = VendorServiceUploadModel(
                                      id: dataid.toString(),
                                      vendorName: nameController.text,
                                      serviceName: serviceNameController.text,
                                      serviceType:
                                          selectedServiceType == 'Free Service'
                                          ? '0'
                                          : '1',
                                      category: selectedCategory!,
                                      subcategory: selectedSubCategory!,
                                      workingHours: selectedWorkingHours!,
                                      workingDuration: selectedWorkingDuration!,
                                      amount:
                                          double.tryParse(
                                            serviceAmountController.text,
                                          ) ??
                                          0.0,
                                      location: locationController.text,
                                      description: descriptionController.text,
                                      details: serviceDetailsController.text,
                                      images:
                                          [], // We'll pass actual images separately
                                      videos: videoLinks,
                                    );

                                    // Call the API using Riverpod with both model and images
                                    final result = await ref.read(
                                      vendorserviceFutureProvider((
                                        model,
                                        selectedImages,
                                      )).future,
                                    );

                                    // Close loading dialog
                                    Navigator.of(
                                      context,
                                      rootNavigator: true,
                                    ).pop();

                                    // Check if the result indicates success
                                    if (result != null &&
                                        (result['success'] == true ||
                                            result.containsKey('data') &&
                                                result['success'] != false)) {
                                      // Show success message
                                      Fluttertoast.showToast(
                                        msg:
                                            result['message'] ??
                                            "Service uploaded successfully",
                                        backgroundColor: Colors.green,
                                        textColor: Colors.white,
                                        toastLength: Toast.LENGTH_SHORT,
                                        gravity: ToastGravity.BOTTOM,
                                      );

                                      // Clear the form only after successful upload
                                      _clearForm();

                                      // Navigate back if needed
                                      if (Navigator.canPop(context)) {
                                        Navigator.pop(context);
                                      }
                                    } else {
                                      // Handle API failure response
                                      String errorMessage =
                                          result?['error'] ??
                                          result?['message'] ??
                                          "Upload failed. Please try again.";

                                      Fluttertoast.showToast(
                                        msg: errorMessage,
                                        backgroundColor: Colors.red,
                                        textColor: Colors.white,
                                        toastLength: Toast.LENGTH_LONG,
                                        gravity: ToastGravity.BOTTOM,
                                      );

                                      if (errorMessage ==
                                          'Supscription not found') {
                                        Get.toNamed(
                                          RouterConts.vendorpackage,
                                          arguments: 1,
                                        );
                                      }
                                    }
                                  } catch (e) {
                                    // Close loading dialog safely
                                    Navigator.of(
                                      context,
                                      rootNavigator: true,
                                    ).pop();

                                    // Show error message
                                    Fluttertoast.showToast(
                                      msg: "Error: ${e.toString()}",
                                      backgroundColor: Colors.red,
                                      textColor: Colors.white,
                                      toastLength: Toast.LENGTH_LONG,
                                      gravity: ToastGravity.BOTTOM,
                                    );

                                    // Don't clear form or navigate on error
                                  }
                                }
                              },
                              child: const Text(
                                'Submit',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                          ),
                          SizedBox(height: 30),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  List<DropdownMenuItem<String>> _buildCategoryItems() {
    if (categories.isEmpty) {
      return [
        const DropdownMenuItem<String>(
          value: null,
          child: Text('No categories available'),
        ),
      ];
    }
    return categories.map<DropdownMenuItem<String>>((cat) {
      try {
        final id = cat.id?.toString() ?? '';
        final name = cat.name?.toString() ?? 'Unknown';
        return DropdownMenuItem<String>(value: id, child: Text(name));
      } catch (e) {
        print('Error: $e');
        return const DropdownMenuItem<String>(
          value: null,
          child: Text('Error'),
        );
      }
    }).toList();
  }

  List<DropdownMenuItem<String>> _buildSubcategoryItems() {
    if (subcategories.isEmpty) {
      return [
        DropdownMenuItem<String>(
          value: null,
          child: Text(
            selectedCategory == null
                ? 'Select a category first'
                : isLoading
                ? 'Loading subcategories...'
                : 'No subcategories available',
          ),
        ),
      ];
    }
    return subcategories.map<DropdownMenuItem<String>>((sub) {
      try {
        final id = sub.id?.toString() ?? '';
        final name = sub.name?.toString() ?? 'Unknown';
        return DropdownMenuItem<String>(value: id, child: Text(name));
      } catch (e) {
        print('Error: $e');
        return const DropdownMenuItem<String>(
          value: null,
          child: Text('Error'),
        );
      }
    }).toList();
  }

  InputDecoration _buildDropdownDecoration(
    String hintText,
    IconData icon, {
    String? errorText,
  }) {
    return InputDecoration(
      filled: true,
      fillColor: Colors.white,
      prefixIcon: Icon(icon, color: AppColors.hittext),
      hintText: hintText,
      hintStyle: const TextStyle(color: AppColors.hittext),
      errorText: errorText,
      errorStyle: TextStyle(color: Colors.red[700], fontSize: 12),
      contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 18),
      border: OutlineInputBorder(
        borderRadius: BorderRadius.circular(15.78),
        borderSide: const BorderSide(color: Color(0xFFBDBCBC), width: 0.88),
      ),
      enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(15.78),
        borderSide: const BorderSide(color: Color(0xFFBDBCBC), width: 0.88),
      ),
      errorBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(15.78),
        borderSide: BorderSide(color: Colors.red[700]!, width: 0.88),
      ),
      focusedErrorBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(15.78),
        borderSide: BorderSide(color: Colors.red[700]!, width: 0.88),
      ),
    );
  }

  void _clearForm() {
    setState(() {
      // Clear text controllers
      nameController.clear();
      serviceNameController.clear();
      serviceAmountController.clear();
      locationController.clear();
      descriptionController.clear();
      serviceDetailsController.clear();

      // Reset dropdown selections
      selectedServiceType = null;
      selectedCategory = null;
      selectedSubCategory = null;
      selectedWorkingHours = null;
      selectedWorkingDuration = null;

      // Clear images and videos
      selectedImages.clear();
      videoLinks.clear();

      // Clear any error states if you have them
      imagesError = null;
      // Add other error variables if you have them
    });
  }
}
