import 'dart:io';

import 'package:bookmywages/consts_widgets/app_colors.dart';
import 'package:bookmywages/routers/consts_router.dart';
import 'package:bookmywages/viewmodel/api_controller.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';

class VendorService extends ConsumerStatefulWidget {
  final int id;
  final String tittle;
  const VendorService({super.key, required this.id, required this.tittle});

  @override
  ConsumerState<VendorService> createState() => _VendorServiceState();
}

class _VendorServiceState extends ConsumerState<VendorService> {
  @override
  Widget build(BuildContext context) {
    final vendorServiceAsyncValue = ref.watch(vendorserviceProvider);

    return Scaffold(
      backgroundColor: AppColors.secondprimary,
      appBar: AppBar(
        backgroundColor: AppColors.secondprimary,
        leading: const Icon(Icons.arrow_back_ios_new),
        title: Text(
          '${widget.tittle} Service List',
          style: const TextStyle(
            fontFamily: 'Gilroy-Bold',
            fontWeight: FontWeight.w700,
            fontSize: 20,
            height: 1.0,
            letterSpacing: 0.2,
          ),
        ),
        centerTitle: true,
      ),
      body: vendorServiceAsyncValue.when(
        data: (services) {
          final filteredServices = services
              .where((service) => service.category == widget.id)
              .toList();

          if (filteredServices.isEmpty) {
            return const Center(child: Text("No services found"));
          }

          return ListView.builder(
            itemCount: filteredServices.length,
            padding: const EdgeInsets.all(16),
            itemBuilder: (context, index) {
              final service = filteredServices[index];
              return Container(
                margin: const EdgeInsets.only(bottom: 16),
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(20),
                  border: Border.all(color: const Color(0xFFCFCFCF), width: 1),
                  boxShadow: [
                    BoxShadow(
                      color: const Color(0x66A9A9A9),
                      blurRadius: 4,
                      offset: const Offset(0, 1),
                    ),
                  ],
                ),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: SizedBox(
                        width: 100,
                        height: 100,
                        child: _buildServiceImage(
                          (service.images1.isNotEmpty
                              ? service.images1.first
                              : null),
                        ),
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            service.serviceName,
                            style: const TextStyle(
                              fontFamily: 'Gilroy-Bold',
                              fontWeight: FontWeight.w700,
                              fontSize: 16,
                              height: 1.2,
                              letterSpacing: 0.2,
                              color: Colors.black,
                            ),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                          const SizedBox(height: 10),
                          Text(
                            'Name: ${service.serviceName}',
                            style: const TextStyle(
                              fontFamily: 'Gilroy-Medium',
                              fontWeight: FontWeight.w500,
                              fontSize: 14,
                              color: Color(0xFF5A5A5A),
                            ),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                          const SizedBox(height: 6),
                          Text(
                            'Cat: ${service.categoryName}',
                            style: const TextStyle(
                              fontFamily: 'Gilroy-Medium',
                              fontWeight: FontWeight.w500,
                              fontSize: 14,
                              color: Color(0xFF5A5A5A),
                            ),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                          const SizedBox(height: 6),
                          Text(
                            'Sub-Cat: ${service.categoryName}',
                            style: const TextStyle(
                              fontFamily: 'Gilroy-Medium',
                              fontWeight: FontWeight.w500,
                              fontSize: 14,
                              color: Color(0xFF5A5A5A),
                            ),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                          const SizedBox(height: 10),
                          Align(
                            alignment: Alignment.centerLeft,
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Flexible(
                                  child: SizedBox(
                                    height: 32,
                                    child: ElevatedButton(
                                      onPressed: () {
                                        Get.toNamed(
                                          RouterConts.vendorserviceupload,
                                          arguments: service,
                                        );
                                      },
                                      style: ElevatedButton.styleFrom(
                                        backgroundColor: const Color(
                                          0xFF0066FF,
                                        ),
                                        foregroundColor: Colors.white,
                                        shape: RoundedRectangleBorder(
                                          borderRadius: BorderRadius.circular(
                                            20,
                                          ),
                                          side: const BorderSide(
                                            color: Color(0xFFAAAAAA),
                                            width: 0.5,
                                          ),
                                        ),
                                        padding: EdgeInsets.zero,
                                      ),
                                      child: const FittedBox(
                                        child: Text(
                                          'Edit',
                                          style: TextStyle(
                                            fontFamily: 'Gilroy-Bold',
                                            fontWeight: FontWeight.w700,
                                            fontSize: 14,
                                            height: 1.0,
                                            letterSpacing: 0.28,
                                          ),
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                                const SizedBox(width: 8),
                                Flexible(
                                  child: SizedBox(
                                    height: 32,
                                    child: OutlinedButton(
                                      onPressed: () async {
                                        final result = await ref.read(
                                          deleteserviceProvider(
                                            service.id.toString(),
                                          ).future,
                                        );
                                        if (result) {
                                          Fluttertoast.showToast(
                                            msg: "Service deleted successfully",
                                            toastLength: Toast.LENGTH_SHORT,
                                            gravity: ToastGravity.BOTTOM,
                                          );
                                          ref.invalidate(
                                            vendorserviceProvider,
                                          ); // Refresh the service list
                                        } else {
                                          Fluttertoast.showToast(
                                            msg: "Failed to delete service",
                                            toastLength: Toast.LENGTH_SHORT,
                                            gravity: ToastGravity.BOTTOM,
                                          );
                                        }
                                      },

                                      style: OutlinedButton.styleFrom(
                                        backgroundColor: Colors.white,
                                        foregroundColor: Colors.black,
                                        shape: RoundedRectangleBorder(
                                          borderRadius: BorderRadius.circular(
                                            20,
                                          ),
                                        ),
                                        side: const BorderSide(
                                          color: Color(0xFFAAAAAA),
                                          width: 0.5,
                                        ),
                                        padding: EdgeInsets.zero,
                                      ),
                                      child: const FittedBox(
                                        child: Text(
                                          'Delete',
                                          style: TextStyle(
                                            fontFamily: 'Gilroy-Bold',
                                            fontWeight: FontWeight.w700,
                                            fontSize: 14,
                                            height: 1.0,
                                            letterSpacing: 0.28,
                                          ),
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              );
            },
          );
        },
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (err, stack) => Center(
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Text(
              "Error loading services: $err",
              textAlign: TextAlign.center,
            ),
          ),
        ),
      ),
    );
  }

  // Helper method to handle image loading with error handling
  Widget _buildServiceImage(String? imagePath) {
    if (imagePath == null || imagePath.isEmpty) {
      return Container(
        color: Colors.grey[200],
        child: const Icon(Icons.work, size: 40, color: Colors.grey),
      );
    }

    final bool isNetworkImage = imagePath.startsWith('http');
    final bool isValidFilePath =
        imagePath.startsWith('/') ||
        (imagePath.startsWith('file://') && imagePath.length > 7);

    if (isNetworkImage) {
      return CachedNetworkImage(
        imageUrl: imagePath,
        fit: BoxFit.cover,
        placeholder: (context, url) => Container(
          color: Colors.grey[200],
          child: const Center(child: CircularProgressIndicator()),
        ),
        errorWidget: (context, url, error) => Container(
          color: Colors.grey[200],
          child: const Icon(Icons.error, size: 40, color: Colors.red),
        ),
      );
    } else if (isValidFilePath) {
      return Image.file(
        File(imagePath.replaceFirst('file://', '')),
        fit: BoxFit.cover,
        errorBuilder: (context, error, stackTrace) {
          print('Error loading image: $error');
          return Container(
            color: Colors.grey[200],
            child: const Icon(Icons.broken_image, size: 40, color: Colors.red),
          );
        },
      );
    } else {
      print('Invalid image path format: $imagePath');
      return Container(
        color: Colors.grey[200],
        child: const Icon(
          Icons.image_not_supported,
          size: 40,
          color: Colors.grey,
        ),
      );
    }
  }
}
