import 'package:bookmywages/consts_widgets/app_assets.dart';
import 'package:bookmywages/consts_widgets/app_colors.dart';
import 'package:bookmywages/model/Categories_model.dart';
import 'package:bookmywages/model/subcategory_model.dart';
import 'package:bookmywages/routers/consts_router.dart';
import 'package:bookmywages/viewmodel/api_controller.dart';
import 'package:bookmywages/viewmodel/consts_api.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:get/get.dart';

// Utility class for responsive sizing
class ResponsiveSize {
  static double getWidthPercentage(BuildContext context, double percentage) {
    return MediaQuery.of(context).size.width * percentage;
  }

  static double getHeightPercentage(BuildContext context, double percentage) {
    return MediaQuery.of(context).size.height * percentage;
  }

  static double getFontSize(BuildContext context, double baseFontSize) {
    double screenWidth = MediaQuery.of(context).size.width;
    // Scale font based on screen width
    if (screenWidth < 320) return baseFontSize * 0.8;
    if (screenWidth < 480) return baseFontSize * 0.9;
    return baseFontSize;
  }
}

class ListServiceScreen extends ConsumerStatefulWidget {
  final String id; // Changed from int to String
  final String service;
  final String? subcategoryId; // Added subcategoryId parameter

  const ListServiceScreen({
    super.key,
    required this.id,
    required this.service,
    this.subcategoryId, // Added subcategoryId parameter
  });

  @override
  ConsumerState<ListServiceScreen> createState() => _ListServiceScreenState();
}

class _ListServiceScreenState extends ConsumerState<ListServiceScreen> {
  int selectedIndex = 0;
  String? selectedSubcategoryId;
  String? selectedCategory;
  String? selectedSubcategory;
  String? selectedType;
  List<CategoriesModel> categories = [];
  List<SubcategoryModel> subcategories = [];
  String? selectedTypeValue;

  // For view more bottom sheet
  int viewMoreSelectedIndex = 0;
  String? tempSelectedSubcategoryId;

  // Search functionality variables
  final TextEditingController _searchController = TextEditingController();
  String _searchQuery = '';

  @override
  void initState() {
    super.initState();
    // Add search listener
    _searchController.addListener(() {
      setState(() {
        _searchQuery = _searchController.text;
      });
    });
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final isPortrait =
        MediaQuery.of(context).orientation == Orientation.portrait;
    final itemSize = isPortrait ? size.width * 0.16 : size.width * 0.1;

    // Fetching subcategory and services
    final subcategoryAsyncValue = ref.watch(
      subcategoryProvider(widget.id.toString()), // Fetching subcategories
    );

    // Fetching services based on selected filters
    final servicesAsyncValue = ref.watch(
      serviceProvider((
        categoryId:
            selectedCategory ??
            widget.id.toString(), // Use selected category or default
        subcategoryId: selectedSubcategoryId,
        selecttype: selectedTypeValue ?? widget.service,
      )),
    );

    return Scaffold(
      resizeToAvoidBottomInset: false,
      backgroundColor: AppColors.secondprimary,
      body: SafeArea(
        child: SingleChildScrollView(
          child: Padding(
            padding: EdgeInsets.symmetric(
              horizontal: ResponsiveSize.getWidthPercentage(context, 0.04),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(
                  height: ResponsiveSize.getHeightPercentage(context, 0.02),
                ),
                // iOS style back button and title
                Stack(
                  alignment: Alignment.center,
                  children: [
                    Align(
                      alignment: Alignment.centerLeft,
                      child: GestureDetector(
                        onTap: () => Navigator.pop(context),
                        child: Icon(
                          Icons.arrow_back_ios_new,
                          size: 20,
                          color: Colors.black,
                        ),
                      ),
                    ),
                    Center(
                      child: Text(
                        'List of Service',
                        style: TextStyle(
                          fontSize: ResponsiveSize.getFontSize(context, 20),
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(
                  height: ResponsiveSize.getHeightPercentage(context, 0.05),
                ),

                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Expanded(
                      flex: 5,
                      child: Container(
                        width: 323.63, // fixed width from your value
                        height: 60.3, // fixed height
                        // position if needed (usually use Padding or layout widget instead)
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(15.08),
                          border: Border.all(
                            color: const Color(0xFFAEAEAE),
                            width: 1.01,
                          ),
                        ),
                        child: TextFormField(
                          controller: _searchController,
                          decoration: InputDecoration(
                            contentPadding: const EdgeInsets.symmetric(
                              horizontal: 16,
                              vertical: 20,
                            ),
                            border: InputBorder.none,
                            hintText: 'Search your service',
                            hintStyle: TextStyle(color: Colors.grey[600]),
                            prefixIcon: Icon(
                              Icons.search_sharp,
                              color: Colors.grey[600],
                            ),
                            suffixIcon: _searchQuery.isNotEmpty
                                ? IconButton(
                                    icon: Icon(
                                      Icons.clear,
                                      color: Colors.grey[600],
                                    ),
                                    onPressed: () {
                                      _searchController.clear();
                                      setState(() {
                                        _searchQuery = '';
                                      });
                                    },
                                  )
                                : null,
                          ),
                          style: const TextStyle(
                            fontSize: 16,
                            color: Colors.black,
                          ),
                          onChanged: (value) {
                            setState(() {
                              _searchQuery = value;
                            });
                          },
                        ),
                      ),
                    ),
                    SizedBox(width: 5),
                    Expanded(
                      flex: 1,
                      child: Container(
                        width: 62.31,
                        height: 60.30,
                        decoration: BoxDecoration(
                          color: Colors.white, // #FFFFFF
                          borderRadius: BorderRadius.circular(15.08),
                          border: Border.all(
                            color: const Color(0xFFAEAEAE),
                            width: 1.01,
                          ),
                        ),
                        child: Center(
                          child: IconButton(
                            onPressed: () =>
                                showCommanFilterBottomSheet(context),
                            icon: Image.asset(
                              AppAssets.filtericon,
                              height: 25,
                              width: 25,
                              color: const Color(0xff797777),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),

                SizedBox(
                  height: ResponsiveSize.getHeightPercentage(context, 0.02),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      'Sub - categories',
                      style: TextStyle(
                        fontFamily: 'Gilroy-Bold',
                        fontWeight: FontWeight.w700,
                        fontSize: size.width * 0.055, // Responsive font size
                        height: 1.0,
                        letterSpacing: size.width * 0.0005,
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        showViewMoreBottomSheet(context, subcategoryAsyncValue);
                      },
                      child: Text(
                        'View more',
                        style: TextStyle(
                          fontFamily: 'Gilroy-Bold',
                          fontWeight: FontWeight.w700,
                          fontSize: MediaQuery.of(context).size.width * 0.04,
                          height: 1.0,
                          letterSpacing:
                              MediaQuery.of(context).size.width * 0.0005,
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(
                  height: ResponsiveSize.getHeightPercentage(context, 0.04),
                ),
                subcategoryAsyncValue.when(
                  loading: () => SizedBox(
                    height: ResponsiveSize.getHeightPercentage(context, 0.14),
                    child: Row(
                      children: List.generate(
                        4,
                        (index) => Padding(
                          padding: EdgeInsets.only(
                            right: ResponsiveSize.getWidthPercentage(
                              context,
                              0.05,
                            ),
                          ),
                          child: Column(
                            children: [
                              Container(
                                height: itemSize,
                                width: itemSize,
                                decoration: BoxDecoration(
                                  color: Colors.grey.shade300,
                                  shape: BoxShape.circle,
                                ),
                              ),
                              SizedBox(
                                height: ResponsiveSize.getHeightPercentage(
                                  context,
                                  0.01,
                                ),
                              ),
                              Container(
                                height: 12,
                                width: itemSize * 0.8,
                                color: Colors.grey.shade300,
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                  error: (err, stack) => Text('Error: $err'),
                  data: (subcategories) {
                    return SizedBox(
                      height: ResponsiveSize.getHeightPercentage(context, 0.14),
                      child: ListView.builder(
                        scrollDirection: Axis.horizontal,
                        itemCount: subcategories.length + 1,
                        itemBuilder: (context, index) {
                          bool isSelected = index == selectedIndex;

                          if (index == 0) {
                            return GestureDetector(
                              onTap: () {
                                setState(() {
                                  selectedIndex = 0;
                                  selectedSubcategoryId = null;
                                  selectedCategory = widget.id.toString();
                                });
                              },
                              child: Padding(
                                padding: EdgeInsets.only(
                                  right: ResponsiveSize.getWidthPercentage(
                                    context,
                                    0.05,
                                  ),
                                ),
                                child: Column(
                                  children: [
                                    Container(
                                      height: itemSize,
                                      width: itemSize,
                                      decoration: BoxDecoration(
                                        color: isSelected
                                            ? Colors.blue.shade100
                                            : Colors.grey.shade200,
                                        shape: BoxShape.circle,
                                      ),
                                      child: Image.asset(AppAssets.allicon),
                                    ),
                                    SizedBox(
                                      height:
                                          ResponsiveSize.getHeightPercentage(
                                            context,
                                            0.01,
                                          ),
                                    ),
                                    Text(
                                      'All',
                                      textAlign: TextAlign.center,
                                      style: TextStyle(
                                        fontSize: ResponsiveSize.getFontSize(
                                          context,
                                          12,
                                        ),
                                        fontWeight: FontWeight.w500,
                                        color: isSelected
                                            ? Colors.black
                                            : Colors.grey,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            );
                          }

                          final subcategory = subcategories[index - 1];
                          return GestureDetector(
                            onTap: () {
                              setState(() {
                                selectedIndex = index;
                                selectedSubcategoryId = subcategory.id
                                    .toString();
                              });
                            },
                            child: Padding(
                              padding: EdgeInsets.only(
                                right: ResponsiveSize.getWidthPercentage(
                                  context,
                                  0.05,
                                ),
                              ),
                              child: Column(
                                children: [
                                  Container(
                                    height: itemSize,
                                    width: itemSize,
                                    decoration: BoxDecoration(
                                      color: isSelected
                                          ? Colors.blue.shade100
                                          : Colors.grey.shade200,
                                      shape: BoxShape.circle,
                                    ),
                                    child: Padding(
                                      padding: EdgeInsets.all(itemSize * 0.18),
                                      child: CachedNetworkImage(
                                        imageUrl: subcategory.icon1,
                                        fit: BoxFit.contain,
                                        placeholder: (context, url) => SizedBox(
                                          width: 20,
                                          height: 20,
                                          child: Icon(
                                            Icons.category,
                                            size: 20,
                                            color: Colors.grey,
                                          ),
                                        ),
                                        errorWidget: (context, url, error) =>
                                            Icon(
                                              Icons.broken_image,
                                              color: Colors.grey,
                                            ),
                                      ),
                                    ),
                                  ),
                                  SizedBox(
                                    height: ResponsiveSize.getHeightPercentage(
                                      context,
                                      0.01,
                                    ),
                                  ),
                                  SizedBox(
                                    width: itemSize,
                                    child: Text(
                                      subcategory.name,
                                      textAlign: TextAlign.center,
                                      overflow: TextOverflow.visible,
                                      maxLines: 2,
                                      style: TextStyle(
                                        fontFamily: 'Gilroy-Medium',
                                        fontWeight: FontWeight.w400,
                                        fontSize: ResponsiveSize.getFontSize(
                                          context,
                                          12,
                                        ),
                                        height: 1.2,
                                        color: isSelected
                                            ? Colors.black
                                            : Color(0xff909090),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          );
                        },
                      ),
                    );
                  },
                ),
                SizedBox(
                  height: ResponsiveSize.getHeightPercentage(context, 0.03),
                ),

                servicesAsyncValue.when(
                  data: (allServices) {
                    // Filter services based on search query
                    final services = _searchQuery.isEmpty
                        ? allServices
                        : allServices.where((service) {
                            final serviceName = service.serviceName
                                .toLowerCase();
                            final vendorName = service.vendorName.toLowerCase();
                            final categoryName = service.categoryName
                                .toLowerCase();
                            final vendorDisplayName = service.vendorDisplayName
                                .toLowerCase();
                            final query = _searchQuery.toLowerCase();

                            return serviceName.contains(query) ||
                                vendorName.contains(query) ||
                                categoryName.contains(query) ||
                                vendorDisplayName.contains(query);
                          }).toList();

                    if (services.isEmpty) {
                      return Center(
                        child: Padding(
                          padding: EdgeInsets.only(
                            top: ResponsiveSize.getHeightPercentage(
                              context,
                              0.1,
                            ),
                          ),
                          child: Text(
                            _searchQuery.isNotEmpty
                                ? 'No services found for "$_searchQuery"'
                                : 'No services available.',
                            style: TextStyle(
                              fontSize: ResponsiveSize.getFontSize(context, 16),
                            ),
                          ),
                        ),
                      );
                    }
                    return ListView.builder(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      itemCount: services.length,
                      itemBuilder: (context, index) {
                        final service = services[index];

                        return Padding(
                          padding: EdgeInsets.only(
                            bottom: ResponsiveSize.getHeightPercentage(
                              context,
                              0.02,
                            ),
                          ),
                          child: GestureDetector(
                            onTap: () {
                              Get.toNamed(
                                RouterConts.detailserivce,
                                arguments: service.id,
                              );
                            },
                            child: Container(
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(
                                  ResponsiveSize.getWidthPercentage(
                                    context,
                                    0.05,
                                  ),
                                ),
                                border: Border.all(color: AppColors.lightGrey),
                              ),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Stack(
                                    children: [
                                      ClipRRect(
                                        borderRadius: BorderRadius.circular(
                                          ResponsiveSize.getWidthPercentage(
                                            context,
                                            0.03,
                                          ),
                                        ),
                                        child:
                                            service.images1 != null &&
                                                service.images1!.isNotEmpty
                                            ? CachedNetworkImage(
                                                imageUrl:
                                                    service.images1!.first,
                                                height:
                                                    ResponsiveSize.getHeightPercentage(
                                                      context,
                                                      0.18,
                                                    ),
                                                width: double.infinity,
                                                fit: BoxFit.cover,
                                                placeholder: (context, url) =>
                                                    Container(
                                                      height:
                                                          ResponsiveSize.getHeightPercentage(
                                                            context,
                                                            0.18,
                                                          ),
                                                      width: double.infinity,
                                                      color: Colors.grey[300],
                                                      child: Icon(
                                                        Icons.image,
                                                        size: 50,
                                                        color: Colors.grey,
                                                      ),
                                                    ),
                                                errorWidget:
                                                    (
                                                      context,
                                                      url,
                                                      error,
                                                    ) => Container(
                                                      height:
                                                          ResponsiveSize.getHeightPercentage(
                                                            context,
                                                            0.18,
                                                          ),
                                                      width: double.infinity,
                                                      color: Colors.grey[300],
                                                      child: Icon(
                                                        Icons.broken_image,
                                                        size:
                                                            ResponsiveSize.getWidthPercentage(
                                                              context,
                                                              0.1,
                                                            ),
                                                        color: Colors.grey,
                                                      ),
                                                    ),
                                              )
                                            : Container(
                                                height:
                                                    ResponsiveSize.getHeightPercentage(
                                                      context,
                                                      0.18,
                                                    ),
                                                width: double.infinity,
                                                color: Colors.grey[300],
                                                child: Icon(
                                                  Icons.image,
                                                  size: 50,
                                                  color: Colors.grey,
                                                ),
                                              ),
                                      ),

                                      Positioned(
                                        top: ResponsiveSize.getHeightPercentage(
                                          context,
                                          0.008,
                                        ),
                                        left: ResponsiveSize.getWidthPercentage(
                                          context,
                                          0.015,
                                        ),
                                        child: Container(
                                          width:
                                              ResponsiveSize.getWidthPercentage(
                                                context,
                                                0.2,
                                              ),
                                          height:
                                              ResponsiveSize.getHeightPercentage(
                                                context,
                                                0.035,
                                              ),
                                          padding: EdgeInsets.symmetric(
                                            horizontal:
                                                ResponsiveSize.getWidthPercentage(
                                                  context,
                                                  0.015,
                                                ),
                                            vertical:
                                                ResponsiveSize.getHeightPercentage(
                                                  context,
                                                  0.002,
                                                ),
                                          ),
                                          decoration: BoxDecoration(
                                            color: service.serviceType == 1
                                                ? Color(0xFFFFE9E9)
                                                : Color(0xFFE9FFEF),
                                            borderRadius: BorderRadius.circular(
                                              ResponsiveSize.getWidthPercentage(
                                                context,
                                                0.04,
                                              ),
                                            ),
                                          ),
                                          child: Row(
                                            mainAxisSize: MainAxisSize.min,
                                            children: [
                                              Image.asset(
                                                service.serviceType == 1
                                                    ? AppAssets.paidicon
                                                    : AppAssets.freeicon,
                                                width:
                                                    ResponsiveSize.getWidthPercentage(
                                                      context,
                                                      0.045,
                                                    ),
                                                height:
                                                    ResponsiveSize.getWidthPercentage(
                                                      context,
                                                      0.045,
                                                    ),
                                              ),
                                              SizedBox(
                                                width:
                                                    ResponsiveSize.getWidthPercentage(
                                                      context,
                                                      0.01,
                                                    ),
                                              ),
                                              Text(
                                                service.serviceType == 1
                                                    ? 'Paid'
                                                    : 'Free',
                                                style: TextStyle(
                                                  fontFamily: 'Gilroy-Bold',
                                                  fontWeight: FontWeight.w400,
                                                  fontSize:
                                                      ResponsiveSize.getFontSize(
                                                        context,
                                                        14,
                                                      ),
                                                  height: 0.93,
                                                  letterSpacing: 1,
                                                  color:
                                                      service.serviceType == 1
                                                      ? Colors.red
                                                      : Color(0xff3A942C),
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                  SizedBox(
                                    height: ResponsiveSize.getHeightPercentage(
                                      context,
                                      0.015,
                                    ),
                                  ),
                                  Padding(
                                    padding: EdgeInsets.symmetric(
                                      horizontal:
                                          ResponsiveSize.getWidthPercentage(
                                            context,
                                            0.03,
                                          ),
                                    ),
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceBetween,
                                          children: [
                                            Expanded(
                                              child: Text(
                                                service.vendorName,
                                                overflow: TextOverflow.ellipsis,
                                                style: TextStyle(
                                                  fontFamily: 'Gilroy-Bold',
                                                  fontWeight: FontWeight.w700,
                                                  fontSize:
                                                      ResponsiveSize.getFontSize(
                                                        context,
                                                        18,
                                                      ),
                                                  height: 1.1,
                                                  letterSpacing: 1,
                                                ),
                                              ),
                                            ),
                                            Row(
                                              children: [
                                                Icon(
                                                  Icons.star,
                                                  color: Colors.orange,
                                                  size:
                                                      ResponsiveSize.getWidthPercentage(
                                                        context,
                                                        0.04,
                                                      ),
                                                ),
                                                SizedBox(
                                                  width:
                                                      ResponsiveSize.getWidthPercentage(
                                                        context,
                                                        0.01,
                                                      ),
                                                ),
                                                Text(
                                                  '4.5',
                                                  style: TextStyle(
                                                    fontSize:
                                                        ResponsiveSize.getFontSize(
                                                          context,
                                                          14,
                                                        ),
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ],
                                        ),
                                        SizedBox(
                                          height:
                                              ResponsiveSize.getHeightPercentage(
                                                context,
                                                0.005,
                                              ),
                                        ),
                                        Text(
                                          service.serviceName,
                                          style: TextStyle(
                                            fontFamily: 'Gilroy-Medium',
                                            fontWeight: FontWeight.w400,
                                            fontSize:
                                                ResponsiveSize.getFontSize(
                                                  context,
                                                  14,
                                                ),
                                            height: 1.1,
                                            letterSpacing: 1,
                                            color: Color(0xFF5A5A5A),
                                          ),
                                        ),
                                        SizedBox(
                                          height:
                                              ResponsiveSize.getHeightPercentage(
                                                context,
                                                0.01,
                                              ),
                                        ),

                                        // Use responsive layout for the bottom row
                                        LayoutBuilder(
                                          builder: (context, constraints) {
                                            // Determine layout based on available width instead of fixed breakpoints
                                            bool useVerticalLayout =
                                                constraints.maxWidth < 300;

                                            if (useVerticalLayout) {
                                              return Column(
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.start,
                                                children: [
                                                  _buildVendorInfoContainer(
                                                    context,
                                                    service,
                                                  ),
                                                  SizedBox(
                                                    height:
                                                        ResponsiveSize.getHeightPercentage(
                                                          context,
                                                          0.01,
                                                        ),
                                                  ),
                                                  _buildPriceContainer(
                                                    context,
                                                    service,
                                                  ),
                                                ],
                                              );
                                            } else {
                                              // For normal screens, keep horizontal layout
                                              return Row(
                                                mainAxisAlignment:
                                                    MainAxisAlignment
                                                        .spaceBetween,
                                                children: [
                                                  _buildVendorInfoContainer(
                                                    context,
                                                    service,
                                                  ),
                                                  _buildPriceContainer(
                                                    context,
                                                    service,
                                                  ),
                                                ],
                                              );
                                            }
                                          },
                                        ),
                                      ],
                                    ),
                                  ),
                                  SizedBox(
                                    height: ResponsiveSize.getHeightPercentage(
                                      context,
                                      0.012,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        );
                      },
                    );
                  },
                  loading: () => ListView.builder(
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    itemCount: 3, // Show 3 skeleton items
                    itemBuilder: (context, index) {
                      return Padding(
                        padding: EdgeInsets.only(
                          bottom: ResponsiveSize.getHeightPercentage(
                            context,
                            0.02,
                          ),
                        ),
                        child: Container(
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(
                              ResponsiveSize.getWidthPercentage(context, 0.05),
                            ),
                            border: Border.all(color: AppColors.lightGrey),
                          ),
                          child: Column(
                            children: [
                              Container(
                                height: ResponsiveSize.getHeightPercentage(
                                  context,
                                  0.18,
                                ),
                                width: double.infinity,
                                decoration: BoxDecoration(
                                  color: Colors.grey.shade300,
                                  borderRadius: BorderRadius.circular(
                                    ResponsiveSize.getWidthPercentage(
                                      context,
                                      0.03,
                                    ),
                                  ),
                                ),
                              ),
                              Padding(
                                padding: EdgeInsets.all(
                                  ResponsiveSize.getWidthPercentage(
                                    context,
                                    0.03,
                                  ),
                                ),
                                child: Column(
                                  children: [
                                    Container(
                                      height: 20,
                                      color: Colors.grey.shade300,
                                    ),
                                    SizedBox(height: 8),
                                    Container(
                                      height: 16,
                                      color: Colors.grey.shade300,
                                    ),
                                    SizedBox(height: 8),
                                    Container(
                                      height: 16,
                                      color: Colors.grey.shade300,
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                      );
                    },
                  ),
                  error: (error, _) => Center(
                    child: Padding(
                      padding: EdgeInsets.only(
                        top: ResponsiveSize.getHeightPercentage(context, 0.1),
                      ),
                      child: Text('Error loading services: $error'),
                    ),
                  ),
                ),
                // Add padding at the bottom for better scrolling experience
                SizedBox(
                  height: ResponsiveSize.getHeightPercentage(context, 0.03),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // New method for View More bottom sheet
  void showViewMoreBottomSheet(
    BuildContext context,
    AsyncValue<List<SubcategoryModel>> subcategoryAsyncValue,
  ) {
    // Reset temp selection to current selection
    viewMoreSelectedIndex = selectedIndex;
    tempSelectedSubcategoryId = selectedSubcategoryId;
    final size = MediaQuery.of(context).size;
    final isPortrait =
        MediaQuery.of(context).orientation == Orientation.portrait;
    final itemSize = isPortrait ? size.width * 0.16 : size.width * 0.1;
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (BuildContext context) {
        return Consumer(
          builder: (context, ref, child) {
            // Fetch subcategories with category ID 0 for view more
            final viewMoreSubcategoryAsyncValue = ref.watch(
              subcategoryProvider(
                "0",
              ), // Always use category ID 0 for view more
            );

            return StatefulBuilder(
              builder: (context, setModalState) {
                return Container(
                  height: MediaQuery.of(context).size.height * 0.8,
                  padding: EdgeInsets.all(20),
                  child: Column(
                    children: [
                      // Header
                      Stack(
                        alignment: Alignment.center,
                        children: [
                          // Back button (left-aligned)
                          Align(
                            alignment: Alignment.centerLeft,
                            child: GestureDetector(
                              onTap: () => Navigator.pop(context),
                              child: Icon(Icons.arrow_back_ios, size: 18),
                            ),
                          ),
                          // Centered title
                          Text(
                            'Sub-categories',
                            style: TextStyle(
                              fontFamily: 'Gilroy-Bold',
                              fontWeight: FontWeight.w700,
                              fontSize:
                                  MediaQuery.of(context).size.width * 0.045,
                            ),
                          ),
                          // Check button (right-aligned)
                          Align(
                            alignment: Alignment.centerRight,
                            child: FloatingActionButton(
                              mini: true,
                              backgroundColor: Colors.green,
                              onPressed: () {
                                setState(() {
                                  selectedIndex = viewMoreSelectedIndex;
                                  selectedSubcategoryId =
                                      tempSelectedSubcategoryId;
                                  selectedCategory =
                                      tempSelectedSubcategoryId != null
                                      ? "0"
                                      : widget.id.toString();
                                });
                                Navigator.pop(context);
                              },
                              child: Icon(Icons.check, color: Colors.white),
                            ),
                          ),
                        ],
                      ),
                      SizedBox(height: 20),

                      // Content based on API data with category ID 0
                      Expanded(
                        child: viewMoreSubcategoryAsyncValue.when(
                          loading: () => GridView.builder(
                            gridDelegate:
                                SliverGridDelegateWithFixedCrossAxisCount(
                                  crossAxisCount: 3,
                                  crossAxisSpacing: 10,
                                  mainAxisSpacing: 10,
                                  childAspectRatio: 1,
                                ),
                            itemCount: 6, // Show 6 skeleton items
                            itemBuilder: (context, index) {
                              return Column(
                                children: [
                                  Container(
                                    height: itemSize,
                                    width: itemSize,
                                    decoration: BoxDecoration(
                                      color: Colors.grey.shade300,
                                      shape: BoxShape.circle,
                                    ),
                                  ),
                                  SizedBox(height: 8),
                                  Container(
                                    height: 12,
                                    width: itemSize * 0.8,
                                    color: Colors.grey.shade300,
                                  ),
                                ],
                              );
                            },
                          ),
                          error: (err, stack) => Center(
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Icon(Icons.error, size: 48, color: Colors.red),
                                SizedBox(height: 16),
                                Text(
                                  'Error loading subcategories',
                                  style: TextStyle(
                                    color: Colors.red,
                                    fontSize: 16,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                                SizedBox(height: 8),
                                Text(
                                  '$err',
                                  style: TextStyle(color: Colors.grey),
                                  textAlign: TextAlign.center,
                                ),
                                SizedBox(height: 16),
                                ElevatedButton(
                                  onPressed: () {
                                    // Refresh the provider
                                    ref.refresh(subcategoryProvider("0"));
                                  },
                                  child: Text('Retry'),
                                ),
                              ],
                            ),
                          ),
                          data: (subcategories) {
                            print(
                              'View More Subcategories loaded: ${subcategories.length}',
                            );

                            if (subcategories.isEmpty) {
                              return Center(
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Icon(
                                      Icons.category,
                                      size: 48,
                                      color: Colors.grey,
                                    ),
                                    SizedBox(height: 16),
                                    Text(
                                      'No subcategories found',
                                      style: TextStyle(
                                        fontSize: 16,
                                        color: Colors.grey,
                                      ),
                                    ),
                                  ],
                                ),
                              );
                            }

                            // Calculate total items (subcategories + 1 for "All")
                            int totalItems = subcategories.length + 1;

                            return GridView.builder(
                              shrinkWrap: true,
                              physics: BouncingScrollPhysics(),
                              gridDelegate:
                                  SliverGridDelegateWithFixedCrossAxisCount(
                                    crossAxisCount: 3,
                                    crossAxisSpacing: 10,
                                    mainAxisSpacing: 10,
                                    childAspectRatio:
                                        1, // Changed to 1 for square items
                                  ),
                              itemCount: totalItems,
                              itemBuilder: (context, index) {
                                bool isSelected =
                                    index == viewMoreSelectedIndex;

                                // First item is "All"
                                if (index == 0) {
                                  return GestureDetector(
                                    onTap: () {
                                      setModalState(() {
                                        viewMoreSelectedIndex = 0;
                                        tempSelectedSubcategoryId = null;
                                      });
                                    },
                                    child: Column(
                                      children: [
                                        Container(
                                          height: itemSize,
                                          width: itemSize,
                                          decoration: BoxDecoration(
                                            color: isSelected
                                                ? Colors.blue.shade100
                                                : Colors.grey.shade200,
                                            shape: BoxShape.circle,
                                          ),
                                          child: Image.asset(AppAssets.allicon),
                                        ),
                                        SizedBox(
                                          height:
                                              ResponsiveSize.getHeightPercentage(
                                                context,
                                                0.01,
                                              ),
                                        ),
                                        Text(
                                          'All',
                                          textAlign: TextAlign.center,
                                          style: TextStyle(
                                            fontSize:
                                                ResponsiveSize.getFontSize(
                                                  context,
                                                  12,
                                                ),
                                            fontWeight: FontWeight.w500,
                                            color: isSelected
                                                ? Colors.black
                                                : Colors.grey,
                                          ),
                                        ),
                                      ],
                                    ),
                                  );
                                }

                                // Subcategory items
                                final subcategory = subcategories[index - 1];
                                return GestureDetector(
                                  onTap: () {
                                    setModalState(() {
                                      viewMoreSelectedIndex = index;
                                      tempSelectedSubcategoryId = subcategory.id
                                          .toString();
                                    });
                                  },
                                  child: Column(
                                    children: [
                                      Container(
                                        height: itemSize,
                                        width: itemSize,
                                        decoration: BoxDecoration(
                                          color: isSelected
                                              ? Colors.blue.shade100
                                              : Colors.grey.shade200,
                                          shape: BoxShape.circle,
                                        ),
                                        child: Padding(
                                          padding: EdgeInsets.all(
                                            itemSize * 0.18,
                                          ),
                                          child: CachedNetworkImage(
                                            imageUrl: subcategory.icon1,
                                            fit: BoxFit.contain,
                                            placeholder: (context, url) => Icon(
                                              Icons.category,
                                              size: 20,
                                              color: Colors.grey,
                                            ),
                                            errorWidget:
                                                (context, url, error) => Icon(
                                                  Icons.broken_image,
                                                  color: Colors.grey,
                                                ),
                                          ),
                                        ),
                                      ),
                                      SizedBox(
                                        height:
                                            ResponsiveSize.getHeightPercentage(
                                              context,
                                              0.01,
                                            ),
                                      ),
                                      SizedBox(
                                        width: itemSize,
                                        child: Text(
                                          subcategory.name,
                                          textAlign: TextAlign.center,
                                          overflow: TextOverflow.visible,
                                          maxLines: 2,
                                          style: TextStyle(
                                            fontFamily: 'Gilroy-Medium',
                                            fontWeight: FontWeight.w400,
                                            fontSize:
                                                ResponsiveSize.getFontSize(
                                                  context,
                                                  12,
                                                ),
                                            height: 1.2,
                                            color: isSelected
                                                ? Colors.black
                                                : Color(0xff909090),
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                );
                              },
                            );
                          },
                        ),
                      ),
                    ],
                  ),
                );
              },
            );
          },
        );
      },
    );
  }

  Widget _buildVendorInfoContainer(BuildContext context, dynamic service) {
    final size = MediaQuery.of(context).size;
    final useSmallLayout = size.width < 320;

    return Container(
      padding: EdgeInsets.all(ResponsiveSize.getWidthPercentage(context, 0.02)),
      decoration: BoxDecoration(
        border: Border.all(color: const Color(0xFFE9E9E9), width: 0.96),
        color: const Color(0xFFF3F3F3),
        borderRadius: BorderRadius.circular(
          ResponsiveSize.getWidthPercentage(context, 0.06),
        ),
      ),
      width: useSmallLayout
          ? ResponsiveSize.getWidthPercentage(context, 0.85)
          : ResponsiveSize.getWidthPercentage(context, 0.5),

      child: Row(
        children: [
          CircleAvatar(
            radius: ResponsiveSize.getWidthPercentage(context, 0.05),
            backgroundImage: AssetImage(AppAssets.login),
          ),
          SizedBox(width: ResponsiveSize.getWidthPercentage(context, 0.02)),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  service.vendorDisplayName,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    fontFamily: 'Gilroy-Medium',
                    fontWeight: FontWeight.w500,
                    fontSize: ResponsiveSize.getFontSize(context, 14),
                    height: 1.1,
                    color: Color(0xFF353434),
                  ),
                ),
                SizedBox(
                  height: ResponsiveSize.getHeightPercentage(context, 0.005),
                ),
                Text(
                  service.categoryName,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    fontFamily: 'Gilroy-Regular',
                    fontWeight: FontWeight.w400,
                    fontSize: ResponsiveSize.getFontSize(context, 12),
                    height: 1.1,
                    color: Color(0xFF717171),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // Price container extracted as a method for reuse
  Widget _buildPriceContainer(BuildContext context, dynamic service) {
    final size = MediaQuery.of(context).size;
    final useSmallLayout = size.width < 320;

    return Container(
      height: ResponsiveSize.getHeightPercentage(context, 0.035),
      width: useSmallLayout
          ? ResponsiveSize.getWidthPercentage(context, 0.5)
          : ResponsiveSize.getWidthPercentage(context, 0.25),
      decoration: BoxDecoration(
        color: AppColors.primary,
        borderRadius: BorderRadius.circular(
          ResponsiveSize.getWidthPercentage(context, 0.05),
        ),
        border: Border.all(color: Colors.white, width: 1.5),
      ),
      child: Center(
        child: Text(
          'Rs.${service.amount}',
          style: TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.bold,
            fontSize: ResponsiveSize.getFontSize(context, 14),
          ),
        ),
      ),
    );
  }

  // Fix for the type mismatch issue in showCommanFilterBottomSheet method
  void showCommanFilterBottomSheet(BuildContext context) {
    // Local variables to track selection within the bottom sheet
    String? localSelectedCategory;
    String? localSelectedSubcategory;
    String? localSelectedType;

    // Local subcategories list for the bottom sheet
    List<dynamic> localSubcategories = List.from(subcategories);

    // Local categories list with a check to ensure it's not empty
    List<CategoriesModel> localCategories = List.from(categories);

    // If categories are empty, load them directly before showing the sheet
    if (localCategories.isEmpty) {
      final categoryRepo = ref.read(categoryRepositoryProvider);
      categoryRepo
          .fetchCategories(ConstsApi.catgories)
          .then((loadedCategories) {
            localCategories = loadedCategories;
            // Continue showing the bottom sheet after categories are loaded
            _displayBottomSheet(
              context,
              localCategories,
              localSubcategories,
              localSelectedCategory,
              localSelectedSubcategory,
              localSelectedType,
            );
          })
          .catchError((e) {
            print('Error loading categories for filter: $e');
            // Show the bottom sheet anyway, but with empty categories
            _displayBottomSheet(
              context,
              [],
              localSubcategories,
              localSelectedCategory,
              localSelectedSubcategory,
              localSelectedType,
            );
          });
    } else {
      // Categories already loaded, show the bottom sheet directly
      _displayBottomSheet(
        context,
        localCategories,
        localSubcategories,
        localSelectedCategory,
        localSelectedSubcategory,
        localSelectedType,
      );
    }
  }

  // Extracted the bottom sheet UI into a separate method
  void _displayBottomSheet(
    BuildContext context,
    List<CategoriesModel> localCategories,
    List<dynamic> localSubcategories,
    String? localSelectedCategory,
    String? localSelectedSubcategory,
    String? localSelectedType,
  ) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setModalState) {
            // Helper function to load subcategories within the modal
            Future<void> loadSubcategoriesForModal(String categoryId) async {
              final subcategoryRepo = ref.read(subcategoryRepositoryProvider);
              try {
                final newSubcategories = await subcategoryRepo
                    .fetchSubcategories(ConstsApi.subcat, categoryId);

                // Update the local subcategories using setModalState
                setModalState(() {
                  localSubcategories = newSubcategories;
                });
              } catch (e) {
                print('Error loading subcategories: $e');
                setModalState(() {
                  localSubcategories = [];
                });
              }
            }

            return Container(
              height: 809,
              margin: const EdgeInsets.only(top: 210),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: const BorderRadius.only(
                  topLeft: Radius.circular(40),
                  topRight: Radius.circular(40),
                ),
                border: Border.all(color: const Color(0xFF858181), width: 1),
              ),
              child: Padding(
                padding: const EdgeInsets.symmetric(
                  horizontal: 45.0,
                  vertical: 35,
                ),
                child: Column(
                  children: [
                    // Header
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        const Text(
                          "Filter",
                          style: TextStyle(
                            fontFamily: 'Gilroy',
                            fontWeight: FontWeight.w900,
                            fontSize: 25,
                            height: 1.0,
                          ),
                        ),
                        IconButton(
                          onPressed: () {
                            Navigator.pop(context);
                          },
                          icon: Image.asset(
                            AppAssets.filtericon,
                            height: 25,
                            width: 25,
                            color: const Color(0xff797777),
                          ),
                        ),
                      ],
                    ),

                    const SizedBox(height: 40),

                    // Category Dropdown with localized category data
                    Container(
                      width: 361,
                      height: 58,
                      padding: const EdgeInsets.symmetric(horizontal: 12),
                      decoration: BoxDecoration(
                        color: const Color(0xFFFDFDFD),
                        borderRadius: BorderRadius.circular(12),
                        border: Border.all(
                          color: const Color(0xFFD3D3D3),
                          width: 1,
                        ),
                      ),
                      child: DropdownButtonHideUnderline(
                        child: DropdownButton<String>(
                          hint: Text("Select Category"),
                          value: localCategories.isEmpty
                              ? null
                              : (localCategories.any(
                                      (cat) =>
                                          cat.id.toString() ==
                                          localSelectedCategory,
                                    )
                                    ? localSelectedCategory
                                    : null),
                          isExpanded: true,
                          items: localCategories.isEmpty
                              ? [
                                  DropdownMenuItem<String>(
                                    value: "no_categories",
                                    child: Text("No categories available"),
                                  ),
                                ]
                              : localCategories.map((category) {
                                  return DropdownMenuItem<String>(
                                    value: category.id.toString(),
                                    child: Text(category.name),
                                  );
                                }).toList(),
                          onChanged: localCategories.isEmpty
                              ? null
                              : (value) {
                                  if (value != null &&
                                      value != "no_categories") {
                                    // First reset the subcategory and clear local subcategories
                                    setModalState(() {
                                      localSelectedCategory = value;
                                      localSelectedSubcategory =
                                          null; // Reset subcategory selection
                                      localSubcategories =
                                          []; // Clear subcategories while loading
                                    });

                                    // Then load subcategories for selected category
                                    loadSubcategoriesForModal(value);
                                  }
                                },
                        ),
                      ),
                    ),

                    // Rest of your bottom sheet code remains the same...
                    const SizedBox(height: 20),

                    // Subcategory Dropdown
                    Container(
                      width: 361,
                      height: 58,
                      padding: const EdgeInsets.symmetric(horizontal: 12),
                      decoration: BoxDecoration(
                        color: const Color(0xFFFDFDFD),
                        borderRadius: BorderRadius.circular(12),
                        border: Border.all(
                          color: const Color(0xFFD3D3D3),
                          width: 1,
                        ),
                      ),
                      child: DropdownButtonHideUnderline(
                        child: DropdownButton<String>(
                          hint: Text("Select Subcategory"),
                          value: localSubcategories.isEmpty
                              ? null
                              : (localSubcategories.any(
                                      (subcat) =>
                                          subcat.id.toString() ==
                                          localSelectedSubcategory,
                                    )
                                    ? localSelectedSubcategory
                                    : null),
                          isExpanded: true,
                          items: localSubcategories.isEmpty
                              ? [
                                  DropdownMenuItem<String>(
                                    value: "no_subcategories",
                                    child: Text("No subcategories available"),
                                  ),
                                ]
                              : localSubcategories.map((subcategory) {
                                  return DropdownMenuItem<String>(
                                    value: subcategory.id.toString(),
                                    child: Text(subcategory.name),
                                  );
                                }).toList(),
                          onChanged: localSubcategories.isEmpty
                              ? null
                              : (value) {
                                  if (value != null &&
                                      value != "no_subcategories") {
                                    setModalState(() {
                                      localSelectedSubcategory = value;
                                    });
                                  }
                                },
                        ),
                      ),
                    ),

                    const SizedBox(height: 20),

                    // Type Dropdown
                    Container(
                      width: 361,
                      height: 58,
                      padding: const EdgeInsets.symmetric(horizontal: 12),
                      decoration: BoxDecoration(
                        color: const Color(0xFFFDFDFD),
                        borderRadius: BorderRadius.circular(12),
                        border: Border.all(
                          color: const Color(0xFFD3D3D3),
                          width: 1,
                        ),
                      ),
                      child: DropdownButtonHideUnderline(
                        child: DropdownButton<String>(
                          hint: Text("Select Type"),
                          value:
                              (localSelectedType == "Free" ||
                                  localSelectedType == "Paid")
                              ? localSelectedType
                              : null,
                          isExpanded: true,
                          items: ["Free", "Paid"].map((type) {
                            return DropdownMenuItem<String>(
                              value: type,
                              child: Text(type),
                            );
                          }).toList(),
                          onChanged: (value) {
                            setModalState(() {
                              localSelectedType = value;
                            });
                          },
                        ),
                      ),
                    ),
                    SizedBox(height: 50),
                    // Save Button
                    SizedBox(
                      width: double.infinity,
                      height: 58,
                      child: ElevatedButton(
                        style: ElevatedButton.styleFrom(
                          backgroundColor: const Color(0xFF000000),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12),
                            side: const BorderSide(
                              color: Color(0xFFD3D3D3),
                              width: 1,
                            ),
                          ),
                        ),
                        // Save Button
                        onPressed: () {
                          // Apply filters and update parent state
                          setState(() {
                            // Store the selected category from filter (only if valid selection)
                            if (localSelectedCategory != null &&
                                localSelectedCategory != "no_categories") {
                              selectedCategory = localSelectedCategory;
                            }
                            if (localSelectedSubcategory != null &&
                                localSelectedSubcategory !=
                                    "no_subcategories") {
                              selectedSubcategory = localSelectedSubcategory;
                            }
                            if (localSelectedType != null) {
                              selectedType = localSelectedType;
                            }

                            // Update the class level categories and subcategories
                            categories = List.from(localCategories);
                            subcategories = List.from(localSubcategories);

                            // Special case: if no category is selected, use the widget's default category
                            selectedCategory ??= widget.id.toString();

                            // Reset subcategory index if we're returning to the main category
                            if (selectedCategory == widget.id.toString()) {
                              selectedIndex = 0; // Set to "All"
                            }

                            // Update subcategory ID for service provider
                            if (selectedSubcategory != null &&
                                selectedSubcategory != "no_subcategories") {
                              selectedSubcategoryId = selectedSubcategory;
                            } else {
                              selectedSubcategoryId =
                                  null; // Reset if none selected
                            }

                            // Convert type string to number for service provider
                            if (localSelectedType != null) {
                              if (localSelectedType == "Paid") {
                                selectedTypeValue = '1';
                              } else if (localSelectedType == "Free") {
                                selectedTypeValue = 'free';
                              }
                            } else {
                              selectedTypeValue =
                                  null; // Reset if none selected
                            }

                            print(
                              "Filter applied - Category: ${selectedCategory ?? widget.id.toString()}, Subcategory: $selectedSubcategoryId, Type: $selectedTypeValue",
                            );
                          });

                          Navigator.pop(context);
                        },

                        child: const Text(
                          'Save',
                          style: TextStyle(
                            color: Colors.white,
                            fontFamily: 'Gilroy',
                            fontSize: 16,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            );
          },
        );
      },
    );
  }
}
