import 'dart:convert';
import 'dart:io';

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_service_model.dart';
import 'package:bookmywages/model/vendor_model/vendor_serviceupload_model.dart';
import 'package:bookmywages/view/auth/auth_repository.dart';
import 'package:bookmywages/viewmodel/api_controller.dart';
import 'package:bookmywages/viewmodel/consts_api.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';

class VendorServiceupload extends ConsumerStatefulWidget {
  final VendorServiceModel service;
  const VendorServiceupload({super.key, required this.service});

  @override
  ConsumerState<VendorServiceupload> createState() =>
      _VendorServiceuploadState();
}

class _VendorServiceuploadState extends ConsumerState<VendorServiceupload> {
  String? selectedCategory;
  String? selectedSubCategory;
  String? selectedWorkingHours;
  String? selectedWorkingDuration;
  String? selectedServiceType;
  List<File> selectedImages = [];
  List<String> existingImagePaths = []; // To track existing images
  List<String> videoLinks = [];
  TextEditingController videoLinkController = TextEditingController();
  TextEditingController nameController = TextEditingController();
  TextEditingController serviceNameController = TextEditingController();
  TextEditingController serviceAmountController = TextEditingController();
  TextEditingController serviceDetailsController = TextEditingController();
  TextEditingController locationController = TextEditingController();
  TextEditingController descriptionController = TextEditingController();

  final List<String> workingDurationOptions = [
    '01:00 hours',
    '02:00 hours',
    '03:00 hours',
    '04:00 hours',
    '05:00 hours',
    '06:00 hours',
  ];

  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;
  bool isDataLoaded = false;
  bool isSubmitting = false;

  @override
  void initState() {
    super.initState();
    _fetchCategories().then((_) {
      _loadServiceData();
    });

    // Add listeners to clear validation errors when typing
    _setupTextFieldListeners();
  }

  void _setupTextFieldListeners() {
    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);
      }
    });
  }

  // Helper method to safely construct image URLs
  String _getImageUrl(String imagePath) {
    String cleanPath = imagePath
        .replaceAll('[', '')
        .replaceAll(']', '')
        .replaceAll('"', '')
        .replaceAll("'", '')
        .trim();

    if (cleanPath.isEmpty) {
      return '';
    }

    if (cleanPath.startsWith('http')) {
      return cleanPath;
    }

    return 'https://www.demo603.amrithaa.com/bookmywages/admin/public/images/$cleanPath';
  }

  String? _normalizeWorkingDuration(String? duration) {
    if (duration == null || duration.isEmpty) return null;

    // Handle different formats that might come from the database
    String normalizedDuration = duration.toLowerCase().trim();

    // Extract number from the string
    RegExp numberRegex = RegExp(r'(\d+)');
    Match? match = numberRegex.firstMatch(normalizedDuration);

    if (match != null) {
      int hours = int.tryParse(match.group(1)!) ?? 0;
      if (hours >= 1 && hours <= 6) {
        return '${hours.toString().padLeft(2, '0')}:00 hours';
      }
    }

    // If the format already matches, return as is
    if (workingDurationOptions.contains(duration)) {
      return duration;
    }

    return null; // Return null if no match found
  }

  void _loadServiceData() {
    if (isDataLoaded) return;

    // Set the text field values
    nameController.text = widget.service.vendorName;
    serviceNameController.text = widget.service.serviceName;
    serviceAmountController.text = widget.service.amount;
    serviceDetailsController.text = widget.service.details;
    locationController.text = widget.service.location;
    descriptionController.text = widget.service.description;

    // Set dropdown values
    selectedCategory = widget.service.category.toString();
    if (selectedCategory != null) {
      _fetchSubcategories(selectedCategory!).then((_) {
        setState(() {
          selectedSubCategory = widget.service.subcategory.toString();
        });
      });
    }

    selectedWorkingHours = widget.service.workingHours;
    selectedWorkingDuration = _normalizeWorkingDuration(
      widget.service.workingDuration,
    );
    selectedServiceType = widget.service.serviceType == 0
        ? 'Free Service'
        : 'Paid Service';

    // Handle existing images
    _loadExistingImages();

    // Handle existing videos
    _loadExistingVideos();

    setState(() {
      isDataLoaded = true;
    });
  }

  void _loadExistingImages() {
    if (widget.service.images1.isNotEmpty) {
      try {
        setState(() {
          existingImagePaths = List<String>.from(widget.service.images1);
        });
      } catch (e) {
        print('Error loading images: $e');
        setState(() {
          existingImagePaths = [];
        });
      }
    }
  }

  void _loadExistingVideos() {
    try {
      setState(() {
        videoLinks = List<String>.from(widget.service.video!);
      });
    } catch (e) {
      print('Error loading videos: $e');
      setState(() {
        videoLinks = [];
      });
    }
  }

  @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 = [];
      if (!isDataLoaded) {
        selectedSubCategory = null;
      }
      subCategoryError = null;
    });

    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) {
      setState(() {
        selectedImages.addAll(pickedFiles.map((file) => File(file.path)));
        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);
      if (selectedImages.isEmpty && existingImagePaths.isEmpty) {
        imagesError = 'Please upload at least one image';
      }
    });
  }

  void _removeExistingImage(int index) {
    setState(() {
      existingImagePaths.removeAt(index);
      if (existingImagePaths.isEmpty && 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 && existingImagePaths.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(
                            "Edit Service",
                            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: workingDurationOptions
                                .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
                          _buildImageUploadSection(),
                          const SizedBox(height: 20),
                          // Video Links Section
                          _buildVideoLinksSection(),
                          const SizedBox(height: 30),
                          _buildSubmitButton(),
                          SizedBox(height: 30),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildImageUploadSection() {
    return 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 existing images
        if (existingImagePaths.isNotEmpty) ...[
          const SizedBox(height: 10),
          _buildExistingImagesSection(),
        ],
        // Display newly selected images
        if (selectedImages.isNotEmpty) ...[
          const SizedBox(height: 10),
          _buildNewImagesSection(),
        ],
      ],
    );
  }

  Widget _buildExistingImagesSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Padding(
          padding: EdgeInsets.only(left: 8.0, bottom: 8.0),
          child: Text(
            "Existing Images:",
            style: TextStyle(
              fontWeight: FontWeight.bold,
              color: AppColors.primary,
            ),
          ),
        ),
        SizedBox(
          height: 100,
          child: ListView.builder(
            scrollDirection: Axis.horizontal,
            itemCount: existingImagePaths.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),
                        color: Colors.grey[200],
                      ),
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(16),
                        child: Image.network(
                          _getImageUrl(existingImagePaths[index]),
                          fit: BoxFit.cover,
                          errorBuilder: (context, error, stackTrace) {
                            return Container(
                              color: Colors.grey[300],
                              child: Center(
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Icon(
                                      Icons.broken_image,
                                      color: Colors.grey[600],
                                      size: 24,
                                    ),
                                    SizedBox(height: 4),
                                    Text(
                                      'Image not found',
                                      style: TextStyle(
                                        fontSize: 8,
                                        color: Colors.grey[600],
                                      ),
                                      textAlign: TextAlign.center,
                                    ),
                                  ],
                                ),
                              ),
                            );
                          },
                          loadingBuilder: (context, child, loadingProgress) {
                            if (loadingProgress == null) return child;
                            return Center(
                              child: CircularProgressIndicator(
                                value:
                                    loadingProgress.expectedTotalBytes != null
                                    ? loadingProgress.cumulativeBytesLoaded /
                                          loadingProgress.expectedTotalBytes!
                                    : null,
                              ),
                            );
                          },
                        ),
                      ),
                    ),
                    Positioned(
                      top: 0,
                      right: 0,
                      child: GestureDetector(
                        onTap: () => _removeExistingImage(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,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              );
            },
          ),
        ),
      ],
    );
  }

  Widget _buildNewImagesSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Padding(
          padding: EdgeInsets.only(left: 8.0, bottom: 8.0),
          child: Text(
            "New Images:",
            style: TextStyle(
              fontWeight: FontWeight.bold,
              color: AppColors.primary,
            ),
          ),
        ),
        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,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              );
            },
          ),
        ),
      ],
    );
  }

  Widget _buildVideoLinksSection() {
    return 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(),
          ),
        ],
      ],
    );
  }

  Widget _buildSubmitButton() {
    return 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: isSubmitting ? null : _handleSubmit,
        child: isSubmitting
            ? const CircularProgressIndicator(color: Colors.white)
            : const Text(
                'Submit',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
      ),
    );
  }

  Future<void> _handleSubmit() async {
    if (_validateForm()) {
      setState(() {
        isSubmitting = true;
      });

      try {
        final model = VendorServiceUploadModel(
          id: widget.service.id.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: existingImagePaths,
          videos: videoLinks,
        );

        // Use the updated service class
        final serviceUpdate = Vendorserviceupadate();
        final result = await serviceUpdate.vendorserviceupdate(
          ConstsApi
              .vendorserviceupload, // Replace with your actual API endpoint
          model,
          selectedImages,
        );

        Fluttertoast.showToast(
          msg: 'Service updated successfully!',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          backgroundColor: Colors.green,
          textColor: Colors.white,
        );
        ref.invalidate(vendorserviceProvider);
        Navigator.pop(context, true); // Return true to indicate success
      } catch (e) {
        Fluttertoast.showToast(
          msg: 'Error updating service: $e',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          backgroundColor: Colors.red,
          textColor: Colors.white,
        );
      } finally {
        setState(() {
          isSubmitting = false;
        });
      }
    }
  }

  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),
      ),
    );
  }
}
