import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/svg.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import '../../Notifiers/hrmProvider/leaveApplicationListProvider.dart';
import '../../Utils/app_colors.dart';
import '../../Utils/commonWidgets.dart';
import '../commonDateRangeFilter.dart';
import 'AddLeaveRequestScreen.dart';
import 'LeaveApplicationDetailScreen.dart';

class LeaveApplicationListScreen extends StatefulWidget {
  const LeaveApplicationListScreen({super.key});

  @override
  State<LeaveApplicationListScreen> createState() => _LeaveApplicationListScreenState();
}

class _LeaveApplicationListScreenState extends State<LeaveApplicationListScreen> {
  // @override
  // void initState() {
  //   super.initState();
  //   WidgetsBinding.instance.addPostFrameCallback((_) {
  //     final provider = Provider.of<LeaveApplicationListProvider>(context, listen: false);
  //     provider.fetchLeaveApplications(context);
  //   });
  // }


  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) {
        final provider = LeaveApplicationListProvider();
        Future.microtask(() {
          provider.fetchLeaveApplications(context);
        });
        return provider;
      },
      builder: (context, child) {
        return Consumer<LeaveApplicationListProvider>(
          builder: (context, provider, child) {
            return Scaffold(
                appBar: appbar2New(
                  context,
                  "Leave Application List",
                  provider.resetForm,
                  Row(
                    children: [
                      InkResponse(
                        onTap: () async {
                          var cf = Commondaterangefilter();
                          var result = await cf.showFilterBottomSheet(context);
                          if (result != null) {
                            var dateRange = result['dateRange'] as DateTimeRange?;
                            var formatted = result['formatted'] as List<String>;
                            if (formatted.isNotEmpty) {
                              provider.setDateRangeFilter("Custom", customRange: dateRange);
                              provider.fetchLeaveApplications(
                                context,
                                dateRange: "Custom",
                                customRange: dateRange,
                              );
                            }
                          }
                        },
                        child: SvgPicture.asset("assets/svg/filter_ic.svg", height: 25),
                      ),
                    ],
                  ),
                  0xFFFFFFFF,
                ),
                backgroundColor: const Color(0xFFF6F6F8),
              body: Column(
                children: [
                  /// Filter chips (if you want visible filter indicators)
                  // if (provider.selectedStatus != "All" || provider.selectedDateRange != "This Month")
                  //   Container(
                  //     padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                  //     color: Colors.white,
                  //     child: Row(
                  //       children: [
                  //         if (provider.selectedStatus != "All")
                  //           Chip(
                  //             label: Text('Status: ${provider.selectedStatus}'),
                  //             onDeleted: () {
                  //               provider.setStatusFilter("All");
                  //               provider.fetchLeaveApplications(context);
                  //             },
                  //           ),
                  //         if (provider.selectedDateRange != "This Month")
                  //           Chip(
                  //             label: Text('Date: ${provider.selectedDateRange}'),
                  //             onDeleted: () {
                  //               provider.setDateRangeFilter("This Month");
                  //               provider.fetchLeaveApplications(context);
                  //             },
                  //           ),
                  //       ],
                  //     ),
                  //   ),

                  /// Leave application list
                  Expanded(
                    child: Builder(
                      builder: (context) {
                        if (provider.isLoading) {
                          return const Center(child: CircularProgressIndicator(color: Colors.blue));
                        }
                        if (provider.errorMessage != null) {
                          return Center(child: Text(provider.errorMessage!));
                        }
                        if (provider.response?.requestList == null ||
                            provider.response!.requestList!.isEmpty) {
                          return const Center(child: Text("No leave applications found"));
                        }

                        final list = provider.response!.requestList!;
                        return ListView.builder(
                          padding: const EdgeInsets.all(8),
                          itemCount: list.length,
                          itemBuilder: (context, index) {
                            final item = list[index];
                            // Parse the full string into a DateTime object
                            DateTime parsedFromDate = DateFormat("dd MMM yyyy, hh:mm a").parse(item.fromPeriod.toString());
                            String dateFromMonth = DateFormat("dd MMM").format(parsedFromDate);
                            // Parse the full string into a DateTime object
                            DateTime parsedToDate = DateFormat("dd MMM yyyy, hh:mm a").parse(item.toPeriod.toString());

                            String dateToMonth = DateFormat("dd MMM yyyy").format(parsedToDate);

                            return InkWell(
                              borderRadius: BorderRadius.circular(16),
                              onTap: () {
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (context) => LeaveApplicationDetailScreen(
                                      leaveRequestId: item.id.toString(),
                                    ),
                                  ),
                                ).then((_) {
                                  provider.fetchLeaveApplications(context);
                                });
                              },

                              child: Container(
                                margin: const EdgeInsets.symmetric(horizontal: 8.5, vertical: 5),
                                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(16),
                                ),
                                child: Row(
                                  children: [
                                    /// Left Status Circle
                                    Container(
                                      height: 48,
                                      width: 48,
                                      padding: const EdgeInsets.all(8.0),
                                      decoration: BoxDecoration(
                                        color: _getStatusBackgroundColor(item.status),
                                        shape: BoxShape.circle,
                                      ),
                                      child: Center(
                                        child: Text(
                                          _getStatusInitials(item.status),
                                          style: TextStyle(
                                            color: _getStatusTextColor(item.status),
                                            fontSize: 14,
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                      ),
                                    ),
                                    const SizedBox(width: 12),

                                    /// Middle Section - Leave Details
                                    Expanded(
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Text(
                                            item.leaveType ?? "-",
                                            maxLines: 1,
                                            overflow: TextOverflow.ellipsis,
                                            style: TextStyle(
                                              fontFamily: "JakartaRegular",
                                              fontSize: 14,
                                              color: AppColors.semi_black,
                                            ),
                                          ),
                                          const SizedBox(height: 4),
                                          Row(
                                            children: [
                                              Text(
                                                dateFromMonth ?? "-",
                                                style: TextStyle(
                                                  fontFamily: "JakartaRegular",
                                                  fontSize: 14,
                                                  color: AppColors.grey_semi,
                                                ),
                                              ),
                                              Text(
                                                " - ${dateToMonth}" ?? "-",
                                                style: TextStyle(
                                                  fontFamily: "JakartaRegular",
                                                  fontSize: 14,
                                                  color: AppColors.grey_semi,
                                                ),
                                              ),
                                            ],
                                          ),
                                          // const SizedBox(height: 2),
                                          // Text(
                                          //   "Period: ${item.fromPeriod ?? "-"} to ${item.toPeriod ?? "-"}",
                                          //   style: const TextStyle(
                                          //     fontSize: 12.5,
                                          //     color: Color(0xff818181),
                                          //     fontFamily: "Plus Jakarta Sans",
                                          //   ),
                                          // ),
                                        ],
                                      ),
                                    ),

                                    // /// Right Status
                                    // Container(
                                    //   padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                                    //   decoration: BoxDecoration(
                                    //     color: _getStatusBackgroundColor(item.status),
                                    //     borderRadius: BorderRadius.circular(10),
                                    //   ),
                                    //   child: Text(
                                    //     item.status ?? "-",
                                    //     style: TextStyle(
                                    //       fontFamily: "JakartaMedium",
                                    //       fontSize: 13,
                                    //       color: _getStatusTextColor(item.status),
                                    //     ),
                                    //   ),
                                    // ),
                                  ],
                                ),
                              ),
                            );
                          },
                        );
                      },
                    ),
                  )
                ],
              ),

              floatingActionButtonLocation:
              FloatingActionButtonLocation.centerFloat,
              floatingActionButton: InkResponse(
                onTap: () {
                  HapticFeedback.selectionClick();
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (_) => ChangeNotifierProvider(
                        create: (_) => LeaveApplicationListProvider(),
                        child: AddLeaveRequest(pageTitleName: "Add Leave Request"),
                      ),
                    ),
                  ).then((_) {
                    provider.fetchLeaveApplications(context);
                  });

                  // show add bill screen here
                },
                child: Container(
                  height: 45,
                  alignment: Alignment.center,
                  margin: EdgeInsets.symmetric(horizontal: 20),
                  padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                  decoration: BoxDecoration(
                    color: AppColors.app_blue,
                    borderRadius: BorderRadius.circular(15),
                  ),
                  child: Text(
                    "Add Leave Request",
                    style: TextStyle(
                      fontSize: 15,
                      fontFamily: "JakartaMedium",
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            );
          },
        );
      },
    );
  }



  /// Get status background color
  Color _getStatusBackgroundColor(String? status) {
    switch (status?.toLowerCase()) {
      case 'approved':
        return AppColors.approved_bg_color;
      case 'rejected':
        return AppColors.rejected_bg_color;
      case 'requested':
      default:
        return AppColors.requested_bg_color;
    }
  }

  /// Get status text color
  Color _getStatusTextColor(String? status) {
    switch (status?.toLowerCase()) {
      case 'approved':
        return AppColors.approved_text_color;
      case 'rejected':
        return AppColors.rejected_text_color;
      case 'requested':
      default:
        return AppColors.requested_text_color;
    }
  }

  /// Get status initials
  String _getStatusInitials(String? status) {
    switch (status?.toLowerCase()) {
      case 'approved':
        return "A";
      case 'rejected':
        return "R";
      case 'requested':
      default:
        return "P"; // Pending
    }
  }
}