import 'package:flutter/material.dart';
import 'package:glowwheels/helpers/shopid_helper.dart';
import 'package:provider/provider.dart';
import 'package:google_fonts/google_fonts.dart';

import 'package:glowwheels/models/serviceboy_model.dart';
import '../provider/serviceboy_provider.dart';
import '../provider/order_provider.dart';

class AssignServiceBoyDialog extends StatefulWidget {
  final List<ServiceBoy> serviceBoys;
  final String orderId;

  const AssignServiceBoyDialog({
    Key? key,
    required this.serviceBoys,
    required this.orderId,
  }) : super(key: key);

  @override
  State<AssignServiceBoyDialog> createState() => _AssignServiceBoyDialogState();
}

class _AssignServiceBoyDialogState extends State<AssignServiceBoyDialog> {
  bool _isLoading = false;

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => ServiceBoyProvider(),
      child: Consumer<ServiceBoyProvider>(
        builder: (context, assignProvider, _) {
          return AlertDialog(
            backgroundColor: Colors.white,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
            title: const Text(
              "Select Service Boy",
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
            content: SizedBox(
              height: 200,
              width: double.maxFinite,
              child: ListView.builder(
                itemCount: widget.serviceBoys.length,
                itemBuilder: (context, index) {
                  final boy = widget.serviceBoys[index];
                  final isSelected = assignProvider.selectedBoy == boy;

                  return GestureDetector(
                    onTap: () => assignProvider.selectBoy(boy),
                    child: Container(
                      padding: const EdgeInsets.all(12),
                      margin: const EdgeInsets.symmetric(vertical: 4),
                      decoration: BoxDecoration(
                        color: isSelected ? const Color.fromRGBO(0, 80, 170, 1) : Colors.transparent,
                        borderRadius: BorderRadius.circular(8),
                        border: Border.all(color: Colors.grey.shade300),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            boy.name,
                            style: TextStyle(
                              color: isSelected ? Colors.white : Colors.black,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                          Text(
                            "Phone: ${boy.phone}",
                            style: TextStyle(
                              color: isSelected ? Colors.white70 : Colors.grey[700],
                              fontSize: 13,
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: Text(
                  "CANCEL",
                  style: GoogleFonts.poppins(
                    fontSize: 14,
                    color: const Color.fromRGBO(25, 25, 112, 1),
                    fontWeight: FontWeight.w400,
                  ),
                ),
              ),
              ElevatedButton(
                onPressed: assignProvider.selectedBoy != null && !_isLoading
                    ? () async {
                  setState(() {
                    _isLoading = true;
                  });

                  final selectedBoy = assignProvider.selectedBoy!;
                  final orderProvider = Provider.of<OrdersProvider>(context, listen: false);
                  final shopId = getShopId(context);

                  try {
                    await orderProvider.assignServiceBoyToOrder(
                      orderId: widget.orderId,
                      serviceBoyId: selectedBoy.id,
                      shopId: shopId!,
                    );

                    if (mounted) {
                      Navigator.of(context, rootNavigator: true).pop(

                          selectedBoy

                      ); // ✅ return selected boy
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(content: Text('Service boy assigned successfully!')),
                      );
                    }
                  } catch (e) {
                    if (mounted) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(content: Text('Failed to assign service boy: $e')),
                      );
                    }
                  } finally {
                    if (mounted) {
                      setState(() {
                        _isLoading = false;
                      });
                    }
                  }
                }
                    : null,
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF1B1464),
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)),
                ),
                child: _isLoading
                    ? const SizedBox(
                  width: 16,
                  height: 16,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                    color: Colors.white,
                  ),
                )
                    : Text(
                  "Assign",
                  style: GoogleFonts.inter(
                    fontSize: 12,
                    color: Colors.white,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ],
          );
        },
      ),
    );
  }
}
