
import 'package:bookmywages/consts_widgets/app_assets.dart';
import 'package:bookmywages/consts_widgets/app_colors.dart';
import 'package:bookmywages/model/cancel_booking.dart';
import 'package:bookmywages/model/vendor_model/vendor_booking_status.dart';
import 'package:bookmywages/viewmodel/api_controller.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:intl/intl.dart';

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

  @override
  ConsumerState<VendorBookinglist> createState() => _VendorBookinglistState();
}

class _VendorBookinglistState extends ConsumerState<VendorBookinglist> {
  Map<String, dynamic> getStatusInfo(int status) {
    switch (status) {
      case 0:
        return {
          'text': 'Pending',
          'color': Colors.orange,
          'bgColor': Colors.orange.shade100,
        };
      case 1:
        return {
          'text': 'Scheduled',
          'color': Colors.green,
          'bgColor': Colors.green.shade100,
        };
      case 2:
        return {
          'text': 'Completed',
          'color': Colors.blue,
          'bgColor': Colors.blue.shade100,
        };
      case 3:
        return {
          'text': 'Canceled',
          'color': Colors.red,
          'bgColor': Colors.red.shade100,
        };
      default:
        return {
          'text': 'pending',
          'color': Colors.blue,
          'bgColor': Colors.blue.shade100,
        };
    }
  }

  // Format date from API response
  String formatDate(String dateStr) {
    try {
      final date = DateTime.parse(dateStr);
      return DateFormat('MMMM dd, yyyy').format(date);
    } catch (e) {
      return dateStr;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.secondprimary,
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16),
        child: ref
            .watch(vendorbookingdetailsProvider)
            .when(
              data: (bookings) {
                if (bookings.isEmpty) {
                  return const Center(child: Text('No bookings found'));
                }

                return ListView.builder(
                  itemCount: bookings.length,
                  shrinkWrap: true,
                  physics: const ClampingScrollPhysics(),
                  itemBuilder: (context, index) {
                    final booking = bookings[index];
                    final statusInfo = getStatusInfo(booking.status ?? 0);

                    return Container(
                      margin: const EdgeInsets.only(bottom: 16),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(20),
                        border: Border.all(color: AppColors.lightGrey),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          // ID and View order
                          Padding(
                            padding: const EdgeInsets.only(
                              right: 12,
                              left: 12,
                              top: 12,
                            ),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  'ID : ${booking.id}',
                                  style: const TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontSize: 16,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          const Divider(),

                          // Image, Company, and Status
                          Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 12),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Stack(
                                  children: [
                                    ClipRRect(
                                      borderRadius: BorderRadius.circular(12),
                                      child:
                                          (booking.images1 != null &&
                                                  booking.images1!.isNotEmpty)
                                              ? Image.network(
                                                booking.images1!,
                                                width: 100,
                                                height: 110,
                                                fit: BoxFit.cover,
                                                errorBuilder: (
                                                  context,
                                                  error,
                                                  stackTrace,
                                                ) {
                                                  return Image.asset(
                                                    AppAssets.cleaning,
                                                    width: 100,
                                                    height: 110,
                                                    fit: BoxFit.cover,
                                                  );
                                                },
                                              )
                                              : Image.asset(
                                                AppAssets.cleaning,
                                                width: 100,
                                                height: 110,
                                                fit: BoxFit.cover,
                                              ),
                                    ),
                                    Positioned(
                                      top: 6,
                                      left: 6,
                                      child: Container(
                                        padding: const EdgeInsets.symmetric(
                                          horizontal: 6,
                                          vertical: 2,
                                        ),
                                        decoration: BoxDecoration(
                                          color: Colors.white,
                                          borderRadius: BorderRadius.circular(
                                            8,
                                          ),
                                        ),
                                        child: Row(
                                          mainAxisSize: MainAxisSize.min,
                                          children: [
                                            Container(
                                              width: 6,
                                              height: 6,
                                              decoration: const BoxDecoration(
                                                color: Colors.green,
                                                shape: BoxShape.circle,
                                              ),
                                            ),
                                            const SizedBox(width: 4),
                                            const Text(
                                              'Live',
                                              style: TextStyle(
                                                fontSize: 12,
                                                color: Colors.green,
                                                fontWeight: FontWeight.bold,
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                                const SizedBox(width: 12),
                                Flexible(
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        booking.name ?? 'No data',
                                        style: const TextStyle(
                                          fontFamily: 'Gilroy-Bold',
                                          fontWeight: FontWeight.w700,
                                          fontSize: 16.11,
                                          height: 14.5 / 16.11,
                                          letterSpacing: 0.01 * 16.11,
                                        ),
                                      ),
                                      const SizedBox(height: 4),
                                      Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Expanded(
                                            child: Text(
                                              booking.serviceName ?? '',
                                              style: const TextStyle(
                                                fontFamily: 'Gilroy-Medium',
                                                fontWeight: FontWeight.w500,
                                                fontSize: 13.91,
                                                height: 1.3,
                                                letterSpacing: 0.01 * 13.91,
                                                color: Color(0xFF5A5A5A),
                                              ),
                                            ),
                                          ),
                                          const SizedBox(width: 10),
                                          Expanded(
                                            child: Container(
                                              width:
                                                  booking.status == 3
                                                      ? 70
                                                      : booking.status == 1
                                                      ? 85
                                                      : 77.84,
                                              height:
                                                  booking.status == 3
                                                      ? 25
                                                      : booking.status == 1
                                                      ? 25
                                                      : 27.96,
                                              decoration: BoxDecoration(
                                                color:
                                                    booking.status == 3
                                                        ? const Color(
                                                          0xFFFFEEEE,
                                                        )
                                                        : booking.status == 1
                                                        ? const Color(
                                                          0xFFDAE9FF,
                                                        )
                                                        : const Color(
                                                          0xFFE6F7E6,
                                                        ),
                                                borderRadius:
                                                    BorderRadius.circular(6.05),
                                              ),
                                              child: Center(
                                                child: Text(
                                                  booking.status == 3
                                                      ? 'Cancel'
                                                      : booking.status == 1
                                                      ? 'completed'
                                                      : booking.status == 4
                                                      ? 'Scheduled'
                                                      : 'pending',
                                                  style: TextStyle(
                                                    fontFamily: 'Gilroy-Bold',
                                                    fontSize: 10.92,
                                                    fontWeight: FontWeight.w400,
                                                    color:
                                                        booking.status == 3
                                                            ? const Color(
                                                              0xFFFF0000,
                                                            )
                                                            : booking.status ==
                                                                1
                                                            ? const Color(
                                                              0xFF0066FF,
                                                            )
                                                            : const Color(
                                                              0xFF2E8B57,
                                                            ),
                                                    letterSpacing: 1.0,
                                                    height: 0.98,
                                                  ),
                                                ),
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                      const SizedBox(height: 6),

                                      Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Column(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            children: [
                                              const Text(
                                                'Date :',
                                                style: TextStyle(
                                                  fontFamily: 'Gilroy-Bold',
                                                  fontWeight: FontWeight.w700,
                                                  fontSize: 14.45,
                                                  height: 13 / 14.45,
                                                  letterSpacing: 0,
                                                ),
                                              ),
                                              const SizedBox(height: 10),
                                              Text(
                                                booking.serviceDate != null
                                                    ? _formatDate(
                                                      booking.serviceDate!,
                                                    )
                                                    : 'No date',
                                                style: const TextStyle(
                                                  fontFamily: 'Gilroy-Medium',
                                                  fontWeight: FontWeight.w400,
                                                  fontSize: 14.45,
                                                  height: 13 / 14.45,
                                                  letterSpacing: 0,
                                                ),
                                              ),
                                            ],
                                          ),
                                          Column(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            children: [
                                              const Text(
                                                'Time :',
                                                style: TextStyle(
                                                  fontFamily: 'Gilroy-Bold',
                                                  fontWeight: FontWeight.w700,
                                                  fontSize: 14.45,
                                                  height: 13 / 14.45,
                                                  letterSpacing: 0,
                                                ),
                                              ),
                                              const SizedBox(height: 10),
                                              Text(
                                                booking.serviceDate != null
                                                    ? DateFormat(
                                                      'h:mm a',
                                                    ).format(
                                                      DateTime.parse(
                                                        booking.serviceDate!,
                                                      ),
                                                    )
                                                    : 'No time',
                                                style: const TextStyle(
                                                  fontFamily: 'Gilroy-Medium',
                                                  fontWeight: FontWeight.w400,
                                                  fontSize: 14.45,
                                                  height: 13 / 14.45,
                                                  letterSpacing: 0,
                                                ),
                                              ),
                                            ],
                                          ),
                                        ],
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                          const SizedBox(height: 16),

                          /// Date / Time / Hours
                          Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 12),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Row(
                                  children: [
                                    const Text(
                                      "Mobile number : ",
                                      style: TextStyle(
                                        fontFamily: 'Gilroy-Bold',
                                        fontWeight: FontWeight.w700,
                                        fontSize: 14.45,
                                        height: 13 / 14.45,
                                        letterSpacing: 0,
                                      ),
                                    ),
                                    const SizedBox(width: 7),
                                    Text(
                                      booking.mobileNumber.toString(),
                                      style: const TextStyle(
                                        fontFamily: 'Gilroy-Medium',
                                        fontWeight: FontWeight.w400,
                                        fontSize: 14.45,
                                        height: 13 / 14.45,
                                        letterSpacing: 0,
                                      ),
                                    ),
                                  ],
                                ),
                                const SizedBox(height: 13),
                                Row(
                                  children: [
                                    const Text(
                                      "E-mail ID :",
                                      style: TextStyle(
                                        fontFamily: 'Gilroy-Bold',
                                        fontWeight: FontWeight.w700,
                                        fontSize: 14.45,
                                        height: 13 / 14.45,
                                        letterSpacing: 0,
                                      ),
                                    ),
                                    const SizedBox(width: 7),
                                    Text(
                                      booking.email.toString(),
                                      style: const TextStyle(
                                        fontFamily: 'Gilroy-Medium',
                                        fontWeight: FontWeight.w400,
                                        fontSize: 14.45,
                                        height: 13 / 14.45,
                                        letterSpacing: 0,
                                      ),
                                    ),
                                  ],
                                ),
                                const SizedBox(height: 13),
                                Row(
                                  children: [
                                    const Text(
                                      "Address : ",
                                      style: TextStyle(
                                        fontFamily: 'Gilroy-Bold',
                                        fontWeight: FontWeight.w700,
                                        fontSize: 14.45,
                                        height: 13 / 14.45,
                                        letterSpacing: 0,
                                      ),
                                    ),
                                    const SizedBox(width: 7),
                                    Text(
                                      booking.address.toString(),
                                      style: const TextStyle(
                                        fontFamily: 'Gilroy-Medium',
                                        fontWeight: FontWeight.w400,
                                        fontSize: 14.45,
                                        height: 13 / 14.45,
                                        letterSpacing: 0,
                                      ),
                                    ),
                                  ],
                                ),
                                const SizedBox(height: 13),
                                const Text(
                                  "Message : ",
                                  style: TextStyle(
                                    fontFamily: 'Gilroy-Bold',
                                    fontWeight: FontWeight.w700,
                                    fontSize: 14.45,
                                    height: 13 / 14.45,
                                    letterSpacing: 0,
                                  ),
                                ),
                                const SizedBox(height: 13),
                                Text(
                                  booking.message.toString(),
                                  style: const TextStyle(
                                    fontFamily: 'Gilroy-Medium',
                                    fontWeight: FontWeight.w400,
                                    fontSize: 14.45,
                                    height: 13 / 14.45,
                                    letterSpacing: 0,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          const SizedBox(height: 20),
                          if (booking.status == 0)
                            Padding(
                              padding: const EdgeInsets.all(8.0),

                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  SizedBox(
                                    height: 42,
                                    child: ElevatedButton(
                                      onPressed: () async {
                                        final scaffoldMessenger =
                                            ScaffoldMessenger.of(context);

                                        try {
                                          // Prepare data for status update
                                          final data = VendorBookingStatus(
                                            id: booking.id.toString(),
                                            status:
                                                "4", // Change to status 1 (confirmed)
                                          );

                                          // Call the provider to update status
                                          await ref.read(
                                            changebookingProvider(data).future,
                                          );

                                          Fluttertoast.showToast(
                                            msg:
                                                'Booking confirmed successfully',
                                            toastLength: Toast.LENGTH_SHORT,
                                            gravity: ToastGravity.BOTTOM,
                                          );

                                          // Refresh the booking list
                                          ref.invalidate(
                                            vendorbookingdetailsProvider,
                                          );
                                        } catch (e) {
                                          Fluttertoast.showToast(
                                            msg:
                                                'Failed to confirm booking: $e',
                                            toastLength: Toast.LENGTH_SHORT,
                                            gravity: ToastGravity.BOTTOM,
                                          );
                                        }
                                      },
                                      style: ElevatedButton.styleFrom(
                                        backgroundColor: const Color(
                                          0xFF0066FF,
                                        ),
                                        shape: RoundedRectangleBorder(
                                          borderRadius: BorderRadius.circular(
                                            20,
                                          ),
                                        ),
                                      ),
                                      child: const FittedBox(
                                        child: Text(
                                          "Confirmed",
                                          style: TextStyle(
                                            fontFamily: 'Gilroy-Bold',
                                            fontWeight: FontWeight.w800,
                                            fontSize: 14.45,
                                            height: 13 / 14.45,
                                            letterSpacing: 0.289,
                                            color: Colors.white,
                                          ),
                                        ),
                                      ),
                                    ),
                                  ),
                                  GestureDetector(
                                    onTap: () async {
                                      final data = CancelBookingRequest(
                                        id: booking.id.toString(),
                                        serviceId: booking.serviceId.toString(),
                                        type:
                                            booking.type == null
                                                ? "0"
                                                : booking.type.toString(),
                                      );

                                      final scaffoldMessenger =
                                          ScaffoldMessenger.of(context);
                                      final navigator = Navigator.of(context);

                                      try {
                                        await ref.read(
                                          cancelbookingProvider(data).future,
                                        );

                                        Fluttertoast.showToast(
                                          msg: 'Booking cancelled successfully',
                                          toastLength: Toast.LENGTH_SHORT,
                                          gravity: ToastGravity.BOTTOM,
                                        );

                                        ref.invalidate(
                                          vendorbookingdetailsProvider,
                                        );
                                      } catch (e) {
                                        Fluttertoast.showToast(
                                          msg: 'Failed to cancel booking: $e',
                                          toastLength: Toast.LENGTH_SHORT,
                                          gravity: ToastGravity.BOTTOM,
                                        );
                                      }
                                    },
                                    child: const Text(
                                      'Cancel Booking',
                                      style: TextStyle(
                                        fontFamily: 'Gilroy-Bold', // Add this
                                        fontWeight:
                                            FontWeight
                                                .w400, // 400 is normal weight
                                        fontSize: 14.45,
                                        height:
                                            13 /
                                            14.45, // Convert line-height to Flutter's height property
                                        letterSpacing: 0.02, // 2% as decimal
                                        color: Color(0xff534E4E),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            )
                          else if (booking.status == 4)
                            Padding(
                              padding: const EdgeInsets.all(8.0),

                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  SizedBox(
                                    height: 42,
                                    child: ElevatedButton(
                                      onPressed: () {},
                                      style: ElevatedButton.styleFrom(
                                        backgroundColor: const Color(
                                          0xFF0066FF,
                                        ),
                                        shape: RoundedRectangleBorder(
                                          borderRadius: BorderRadius.circular(
                                            20,
                                          ),
                                        ),
                                      ),
                                      child: const FittedBox(
                                        child: Text(
                                          "pending",
                                          style: TextStyle(
                                            fontFamily: 'Gilroy-Bold',
                                            fontWeight: FontWeight.w800,
                                            fontSize: 14.45,
                                            height: 13 / 14.45,
                                            letterSpacing: 0.289,
                                            color: Colors.white,
                                          ),
                                        ),
                                      ),
                                    ),
                                  ),
                                  GestureDetector(
                                    onTap: () async {
                                      final scaffoldMessenger =
                                          ScaffoldMessenger.of(context);

                                      try {
                                        // Prepare data for status update
                                        final data = VendorBookingStatus(
                                          id: booking.id.toString(),
                                          status:
                                              "1", // Change to status 1 (confirmed)
                                        );

                                        // Call the provider to update status
                                        await ref.read(
                                          changebookingProvider(data).future,
                                        );

                                        Fluttertoast.showToast(
                                          msg: 'Booking confirmed successfully',
                                          toastLength: Toast.LENGTH_SHORT,
                                          gravity: ToastGravity.BOTTOM,
                                        );

                                        // Refresh the booking list
                                        ref.invalidate(
                                          vendorbookingdetailsProvider,
                                        );
                                      } catch (e) {
                                        Fluttertoast.showToast(
                                          msg: 'Failed to confirm booking: $e',
                                          toastLength: Toast.LENGTH_SHORT,
                                          gravity: ToastGravity.BOTTOM,
                                        );
                                      }
                                    },
                                    child: const Text(
                                      'complete',
                                      style: TextStyle(
                                        fontFamily: 'Gilroy-Bold', // Add this
                                        fontWeight:
                                            FontWeight
                                                .w400, // 400 is normal weight
                                        fontSize: 14.45,
                                        height:
                                            13 /
                                            14.45, // Convert line-height to Flutter's height property
                                        letterSpacing: 0.02, // 2% as decimal
                                        color: Color(0xff534E4E),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),

                          const SizedBox(height: 10),
                        ],
                      ),
                    );
                  },
                );
              },
              loading: () => const Center(child: CircularProgressIndicator()),
              error:
                  (err, stack) =>
                      Center(child: Text('Error loading bookings: $err')),
            ),
      ),
    );
  }

  String _formatDate(String dateString) {
    try {
      return DateFormat('dd/MM/yyyy').format(DateTime.parse(dateString));
    } catch (e) {
      return dateString; // Fallback: return the original string if parsing fails
    }
  }
}
