import 'package:bookmywages/consts_widgets/app_colors.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';

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

  @override
  ConsumerState<EnquriyPage> createState() => _EnquriyPageState();
}

class _EnquriyPageState extends ConsumerState<EnquriyPage> {
  int? expandedIndex;

  @override
  Widget build(BuildContext context) {
    final enquiryListAsync = ref.watch(enquriylistProvider);

    return Scaffold(
      backgroundColor: AppColors.secondprimary,
      body: enquiryListAsync.when(
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (error, stack) => Center(child: Text('Error: $error')),
        data: (enquiries) => SingleChildScrollView(
          scrollDirection: Axis.vertical,
          child: Column(
            children: List.generate(enquiries.length, (index) {
              final enquiry = enquiries[index];
              final isExpanded = expandedIndex == index;

              return SizedBox(
                width: double.infinity,
                child: Column(
                  children: [
                    Container(
                      margin: const EdgeInsets.symmetric(
                        vertical: 10,
                        horizontal: 16,
                      ),
                      decoration: BoxDecoration(
                        color: AppColors.secondprimary,
                        borderRadius: BorderRadius.circular(11),
                        border: Border.all(
                          color: const Color(0xFFE8E8E8),
                          width: 1,
                        ),
                        boxShadow: const [
                          BoxShadow(
                            color: Color(0x66AEAEAE),
                            offset: Offset(0, 2),
                            blurRadius: 4,
                          ),
                        ],
                      ),
                      child: Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Column(
                          children: [
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                ClipRRect(
                                  borderRadius: BorderRadius.circular(10),
                                  child: (enquiry.images1.isEmpty)
                                      ? Container(
                                          width: 89,
                                          height: 64,
                                          color: Colors.grey[300],
                                          child: Icon(
                                            Icons.image,
                                            color: Colors.grey[600],
                                          ),
                                        )
                                      : Image.network(
                                          enquiry.images1.first,
                                          width: 89,
                                          height: 64,
                                          fit: BoxFit.cover,
                                          errorBuilder:
                                              (context, error, stackTrace) =>
                                                  Container(
                                                    width: 89,
                                                    height: 64,
                                                    color: Colors.grey[300],
                                                    child: Icon(
                                                      Icons.broken_image,
                                                      color: Colors.grey[600],
                                                    ),
                                                  ),
                                        ),
                                ),

                                const SizedBox(width: 10),
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        enquiry.vendorName ?? 'vendorName',
                                        style: const TextStyle(
                                          fontFamily: 'Gilroy-Bold',
                                          fontWeight: FontWeight.w700,
                                          fontSize: 16,
                                          height: 18.14 / 16,
                                          letterSpacing: 0.16,
                                          color: Colors.black,
                                        ),
                                      ),
                                      const SizedBox(height: 12),
                                      GestureDetector(
                                        onTap: () {
                                          setState(() {
                                            expandedIndex = isExpanded
                                                ? null
                                                : index;
                                          });
                                        },
                                        child: Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceBetween,
                                          children: [
                                            Expanded(
                                              child: Text(
                                                enquiry.serviceName,
                                                textAlign: TextAlign.left,
                                                maxLines: 2,
                                                overflow: TextOverflow.ellipsis,
                                                style: const TextStyle(
                                                  fontFamily: 'Gilroy-Medium',
                                                  fontWeight: FontWeight.w400,
                                                  fontSize: 16.11,
                                                  height: 17.3 / 16.11,
                                                  letterSpacing: 0.1611,
                                                  color: Colors.black,
                                                ),
                                              ),
                                            ),
                                            const SizedBox(width: 4),
                                            Flex(
                                              direction: Axis.horizontal,
                                              mainAxisSize: MainAxisSize.min,
                                              children: [
                                                Text(
                                                  isExpanded
                                                      ? "View Less"
                                                      : "View More",
                                                  style: const TextStyle(
                                                    fontWeight: FontWeight.w600,
                                                    fontSize: 13.15,
                                                    height: 5.71 / 13.15,
                                                    color: Color(0xFFFF3D00),
                                                  ),
                                                ),
                                                const SizedBox(width: 5),
                                                Icon(
                                                  isExpanded
                                                      ? Icons.keyboard_arrow_up
                                                      : Icons
                                                            .keyboard_arrow_down,
                                                  color: const Color(
                                                    0xffFF3D00,
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ],
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),
                    if (isExpanded)
                      Container(
                        width: double.infinity,
                        margin: const EdgeInsets.symmetric(horizontal: 16),
                        padding: const EdgeInsets.all(16),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(16.43),
                          border: Border.all(
                            color: const Color(0xFFE8E8E8),
                            width: 0.82,
                          ),
                          boxShadow: const [
                            BoxShadow(
                              color: Color(0xA9A9A940),
                              blurRadius: 3.29,
                              offset: Offset(0, 0.82),
                            ),
                          ],
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text.rich(
                                  TextSpan(
                                    children: [
                                      const TextSpan(
                                        text: "Name  : ",
                                        style: TextStyle(
                                          fontFamily: 'Gilroy-Bold',
                                          fontWeight: FontWeight.w700,
                                          fontSize: 13,
                                          height: 1.239,
                                        ),
                                      ),
                                      TextSpan(
                                        text: enquiry.name ?? 'No Name',
                                        style: const TextStyle(
                                          fontFamily: 'Gilroy-Medium',
                                          fontWeight: FontWeight.w400,
                                          fontSize: 13,
                                          height: 1.239,
                                          color: Color(0xFF373636),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                                IconButton(
                                  icon: const Icon(
                                    Icons.delete,
                                    color: AppColors.red,
                                    size: 20,
                                  ),
                                  onPressed: () async {
                                    final shouldDelete = await showDialog(
                                      context: context,
                                      builder: (context) => AlertDialog(
                                        title: const Text('Delete Enquiry'),
                                        content: const Text(
                                          'Are you sure you want to delete this enquiry?',
                                        ),
                                        actions: [
                                          TextButton(
                                            onPressed: () => Navigator.of(
                                              context,
                                            ).pop(false),
                                            child: const Text('Cancel'),
                                          ),
                                          TextButton(
                                            onPressed: () =>
                                                Navigator.of(context).pop(true),
                                            child: const Text('Delete'),
                                          ),
                                        ],
                                      ),
                                    );

                                    if (shouldDelete == true) {
                                      Fluttertoast.showToast(
                                        msg: 'Deleting enquiry...',
                                        toastLength: Toast.LENGTH_SHORT,
                                        gravity: ToastGravity.BOTTOM,
                                        backgroundColor: Colors.grey,
                                        textColor: Colors.white,
                                      );

                                      try {
                                        final success = await ref.read(
                                          enquriydeleteProvider(
                                            enquiry.id.toString(),
                                          ).future,
                                        );

                                        if (success) {
                                          // Reset expanded index and refresh the list
                                          setState(() {
                                            expandedIndex = null;
                                          });

                                          await Future.delayed(
                                            const Duration(milliseconds: 300),
                                          );

                                          ref.invalidate(enquriylistProvider);

                                          Fluttertoast.showToast(
                                            msg: 'Enquiry deleted successfully',
                                            toastLength: Toast.LENGTH_SHORT,
                                            gravity: ToastGravity.BOTTOM,
                                            backgroundColor: Colors.green,
                                            textColor: Colors.white,
                                          );
                                        } else {
                                          Fluttertoast.showToast(
                                            msg: 'Failed to delete enquiry',
                                            toastLength: Toast.LENGTH_SHORT,
                                            gravity: ToastGravity.BOTTOM,
                                            backgroundColor: Colors.red,
                                            textColor: Colors.white,
                                          );
                                        }
                                      } catch (e) {
                                        Fluttertoast.showToast(
                                          msg: 'Error: ${e.toString()}',
                                          toastLength: Toast.LENGTH_LONG,
                                          gravity: ToastGravity.BOTTOM,
                                          backgroundColor: Colors.red,
                                          textColor: Colors.white,
                                        );
                                      }
                                    }
                                  },
                                ),
                              ],
                            ),
                            const SizedBox(height: 8),
                            _infoText(
                              "Mobile number : ",
                              enquiry.mobile ?? 'No Mobile',
                            ),
                            const SizedBox(height: 13),
                            _infoText(
                              "E-mail Id :  ",
                              enquiry.email ?? 'No Email',
                            ),
                            const SizedBox(height: 13),
                            _infoText(
                              "Message :  ",
                              enquiry.message ?? 'No Message',
                            ),
                          ],
                        ),
                      ),
                  ],
                ),
              );
            }),
          ),
        ),
      ),
    );
  }

  Widget _infoText(String label, String value) {
    return Text.rich(
      TextSpan(
        children: [
          TextSpan(
            text: label,
            style: const TextStyle(
              fontFamily: 'Gilroy-Bold',
              fontWeight: FontWeight.w700,
              fontSize: 13,
              height: 1.239,
            ),
          ),
          TextSpan(
            text: value,
            style: const TextStyle(
              fontFamily: 'Gilroy-Medium',
              fontWeight: FontWeight.w400,
              fontSize: 13,
              height: 1.239,
              color: Color(0xFF373636),
            ),
          ),
        ],
      ),
    );
  }
}
