import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:http/http.dart';
import 'package:intl/intl.dart';
import 'package:nhance_partner/presentation/providers/userRoleProvider.dart';
import '../../../../core/routing/routes.dart';
import '../../../../core/services/api_service.dart';
import '../../../../data/utils/Pagination.dart';
import '../../../layouts/responsive_layout.dart';
import '../../../providers/manager_provider.dart';
import '../../../widgets/custom_action_popup.dart';

class EndrosmentSubList extends ConsumerStatefulWidget {
  final dynamic policyNumber;
  const EndrosmentSubList({super.key, this.policyNumber});
  @override
  ConsumerState<EndrosmentSubList> createState() => EndrosmentSubListState();
}

class EndrosmentSubListState extends ConsumerState<EndrosmentSubList> {
  int currentPage = 1;
  int itemsPerPage = 10;
  late ApiService apiService;

  // List<Map<String, dynamic>> dataVal = [];
  List<Map<String, dynamic>> getStaffData = [];
  List<Map<String, dynamic>> originalData = [];
  List<Map<String, dynamic>> filteredData = [];
  bool isLoading = false;

  @override
  void initState() {
    super.initState();

    apiService = ApiService();
    if (widget.policyNumber != null) {
      getEndrosmentList(widget.policyNumber);
    }
    // Future.microtask(() {
    //   // final id = ref.read(managerIdProvider);
    //   // final roleId = ref.read(userRoleProvider);
    //
    // });
  }

  Future<void> getEndrosmentList(id) async {
    print('POLID - $id');
    // print('getClaimList called MagId - $managerId - $role');
    setState(() {
      isLoading = true;
    });
    // dynamic id = widget.policyNumber;
    try {
      final response = await apiService.findSingleEnrosmentData(id);

      if (response['status'] == 'success') {
        final data = response['data'];
        print('getEndrosmentData - ${response['data']}');
        setState(() {
          if (data is List) {
            print('getEndrosmentData 1');
            // Already a list of maps
            getStaffData = List<Map<String, dynamic>>.from(data);
          } else if (data is Map) {
            print('getEndrosmentData 2 ');
            // Single object, wrap in a list

            getStaffData = [Map<String, dynamic>.from(data)];

            print('getEndrosmentData 2 - $getStaffData');
          } else {
            print('getEndrosmentData 3');
            getStaffData = [];
          }
          // getStaffData = List<Map<String, dynamic>>.from(response['data']);
          originalData = getStaffData;
          filteredData = List.from(originalData);
          // print('originalData - $getClaimPolicies');
        });
      } else {
        getStaffData = [];
        originalData = [];
      }
    } catch (e) {
      print('Exception occurred: $e');
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  final TextEditingController _searchStaffController = TextEditingController();

  String _formatDate(String rawDate) {
    try {
      final dateTime = DateTime.parse(rawDate);
      return DateFormat('dd/MM/yyyy  HH:mm').format(dateTime); // 24-hour format
    } catch (e) {
      return rawDate; // fallback if parsing fails
    }
  }

  List<dynamic> get _paginatedData {
    // Sort descending by id first
    final sortedData = [...filteredData]
      ..sort((a, b) => int.parse(b['id']) - int.parse(a['id']));

    final startIndex = (currentPage - 1) * itemsPerPage;
    final endIndex = (currentPage * itemsPerPage).clamp(0, sortedData.length);

    return sortedData.sublist(startIndex, endIndex);
  }

  List<Widget> _buildPopupMenuActions(BuildContext context, dynamic data) {
    return [
      GestureDetector(
        onTap: () {
          Navigator.pop(context);
          print('EDITStaff - ${data['id']}');
          // dynamic id = data['id'];
          // context.go('/tabEnquiry/$id');

          // update provider
          final id = data['id'].toString();
          ref.read(enquiryIdProvider.notifier).state = id;
          context.go(AppRoutes.tabEnquiry);
        },
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(Icons.edit_sharp, color: Color(0xFF319718), size: 18),
            SizedBox(width: 10),
            Text('Edit'),
          ],
        ),
      ),
    ];
  }

  @override
  Widget build(BuildContext context) {
    return SelectionArea(
        child: Container(
      // color: Colors.yellow.shade50,
      width: MediaQuery.of(context).size.width * 0.6,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Container(
            // color: Colors.green,
            // color: Colors.green.shade50,
            width: MediaQuery.of(context).size.width,

            padding: EdgeInsets.all(8.0),
            child: Column(
              children: [
                if (!ResponsiveLayout.isMobile(context))
                  Container(
                    decoration: BoxDecoration(
                      color: Colors.white,
                      // color: Color(0xFFEDF6F5),
                      borderRadius: BorderRadius.circular(6),
                    ),
                    padding: const EdgeInsets.symmetric(
                      vertical: 12,
                      horizontal: 16,
                    ),
                    child: const Row(
                      children: [
                        Expanded(
                          flex: 2,
                          child: Text('Endorsement Type', style: _headerStyle),
                        ),
                        Expanded(
                          flex: 2,
                          child: Text(
                            'Endorsement Number',
                            style: _headerStyle,
                          ),
                        ),

                        Expanded(
                          flex: 3,
                          child: Text('Remarks', style: _headerStyle),
                        ),
                        Expanded(
                          flex: 2,
                          child: Text('Status', style: _headerStyle),
                        ),

                        // Expanded(
                        //   flex: 1,
                        //   child: Text('Action', style: _headerStyle),
                        // ),
                      ],
                    ),
                  ),

                _buildDataTable(context),
              ],
            ),
          ),
        ],
      ),
    ) );
  }

  Widget _buildDataTable1(BuildContext context) {
    print('DATA -1');
    if (filteredData.isEmpty) {
      return const SizedBox(
        height: 50,
        child: Center(child: Text('No available data')),
      );
    }
    print('DATA -2');
    // final sortedData = [..._paginatedData];
    final sortedData = [...filteredData];
    print('DATA -$sortedData');
    return ListView.builder(
      itemCount: ResponsiveLayout.isMobile(context)
          ? sortedData
                .length // only cards for mobile
          : sortedData.length + 1, // +1 for header in desktop
      // itemCount: sortedData.length,
      itemBuilder: (context, index) {
        print('DAta Itembuilder');
        if (!ResponsiveLayout.isMobile(context) && index == 0) {
          return _buildHeader();
        }
        print('DAta Itembuilder 1');
        final startIndex = (currentPage - 1) * itemsPerPage;
        print('DAta Itembuilder 2');
        final item =
            sortedData[index - (ResponsiveLayout.isMobile(context) ? 0 : 1)];
        final sno = startIndex + index;

        print('DAta Itembuilder 3');
        // return _buildDataRow(item, sno);

        return !ResponsiveLayout.isMobile(context)
            ? _buildDataRow(item, sno)
            : _buildDataCard(item, sno);
      },
    );
  }

  Widget _buildDataTable(BuildContext context) {
    print('DATA -1');
    if (filteredData.isEmpty) {
      return const SizedBox(
        height: 50,
        child: Center(child: Text('No available data')),
      );
    }
    print('DATA -2');

    final sortedData = [...filteredData];
    print('DATA -$sortedData');

    return ListView.builder(
      shrinkWrap: true, // 👈 important when inside Column
      physics: const NeverScrollableScrollPhysics(), // let parent scroll
      itemCount: sortedData.length,
      itemBuilder: (context, index) {
        print('DAta Itembuilder 1');
        final startIndex = (currentPage - 1) * itemsPerPage;
        final item = sortedData[index];
        final sno = startIndex + index + 1;

        print('DAta Itembuilder 2');
        return !ResponsiveLayout.isMobile(context)
            ? _buildDataRow(item, sno)
            : _buildDataCard(item, sno);
      },
    );
  }

  Widget _buildHeader() {
    return SizedBox.shrink();
  }

  Widget _buildDataRow(Map<String, dynamic> item, sno) {
    print('Build - $item'); // Debug: check data
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 16),
      decoration: BoxDecoration(
        color: Color(0xFFEDF6F5),
        border: const Border(
          bottom: BorderSide(color: Color(0xFFEAEAEA), width: 1),
        ),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        children: [
          Expanded(
            flex: 2,
            child: Text(
              item['endorsement_type_value'] ?? '-',
              style: _dataBold,
            ),
          ),
          Expanded(
            flex: 2,
            child: Text(item['endorsement_no'] ?? '-', style: _dataBold),
          ),
          Expanded(
            flex: 3,
            child: Text(
              item['endorsement_description'] ?? '-',
              style: _dataBold,
            ),
          ),
          Expanded(
            flex: 2,
            child: Text(item['status'] ?? '-', style: _dataBold),
          ),

          // Expanded(
          //   flex: 1,
          //   child: Row(
          //     children: [
          //       PopupMenuButton<int>(
          //         color: Colors.white,
          //         padding: EdgeInsets.zero,
          //         offset: Offset(0, 30),
          //         icon: Icon(
          //           Icons.more_vert,
          //           color: Color(0xFF475569),
          //           size: 14,
          //         ),
          //         itemBuilder: (context) => [
          //           CustomPopupMenuEntry(
          //             child: Container(
          //               padding: EdgeInsets.symmetric(
          //                 horizontal: 8,
          //                 vertical: 8,
          //               ),
          //               child: Column(
          //                 mainAxisSize: MainAxisSize.min,
          //                 mainAxisAlignment: MainAxisAlignment.center,
          //                 children: _buildPopupMenuActions(context, item),
          //               ),
          //             ),
          //           ),
          //         ],
          //       ),
          //     ],
          //   ),
          // ),
        ],
      ),
    );
  }

  Widget _buildDataCard(Map<String, dynamic> item, int sno) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 6, horizontal: 8),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: const Color(0xFFFFFFFF),
        borderRadius: BorderRadius.circular(8.0),
        border: Border.all(color: const Color(0xffD9EBE8)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Title + menu
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                child: Text(
                  item['endorsement_type_value'] ?? '-',
                  style: _headerStyle,
                ),
              ),
              // PopupMenuButton<int>(
              //   color: Colors.white,
              //   padding: EdgeInsets.zero,
              //   offset: const Offset(0, 30),
              //   icon: const Icon(
              //     Icons.more_vert,
              //     color: Color(0xFF475569),
              //     size: 16,
              //   ),
              //   itemBuilder: (context) => [
              //     PopupMenuItem<int>(
              //       value: 1,
              //       child: Column(
              //         mainAxisSize: MainAxisSize.min,
              //         children: _buildPopupMenuActions(context, item),
              //       ),
              //     ),
              //   ],
              // ),
            ],
          ),
          // Description
          Text(
            item['endorsement_description'] ?? '-',
            style: _cardBodyStyle,
            maxLines: 3,
            overflow: TextOverflow.ellipsis,
          ),
          // Status
          Row(
            children: [
              const Text(
                "Status: ",
                style: TextStyle(
                  color: Colors.green,
                  fontWeight: FontWeight.w600,
                  fontSize: 12,
                ),
              ),
              Text(
                item['status'] ?? '-',
                style: TextStyle(
                  // color: (item['status'] == "Completed")
                  //     ? Colors.green
                  //     : Colors.orange,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  static final _dataBold = TextStyle(
    fontSize: 14,

    fontWeight: FontWeight.w400,
    color: Color(0xFF000000),
  );

  static final _dataSub = TextStyle(
    fontSize: 10,
    fontWeight: FontWeight.w300,
    color: Color(0xFF585757),
  );

  static const _headerStyle = TextStyle(
    color: Colors.black,
    fontWeight: FontWeight.bold,
  );
  static const _cardheaderStyle = TextStyle(
    color: Colors.black,
    fontWeight: FontWeight.w600,
    fontSize: 12,
  );

  static const _cardBodyStyle = TextStyle(
    color: Color(0xFF545454),
    fontWeight: FontWeight.w400,
    fontSize: 12,
  );
}
