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 {
  final mode;
  const LeaveApplicationListScreen({super.key, required this.mode});

  @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 SafeArea(
      top: false,
      child: ChangeNotifierProvider(
        create: (_) {
          final provider = LeaveApplicationListProvider();
          Future.microtask(() {
            provider.fetchLeaveApplications(context, widget.mode);
          });
          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,
                                widget.mode,
                                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.symmetric(
                              horizontal: 8,
                              vertical: 10,
                            ),
                            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(),
                                                mode: widget.mode,
                                              ),
                                    ),
                                  ).then((_) {
                                    provider.fetchLeaveApplications(
                                      context,
                                      widget.mode,
                                    );
                                  });
                                },

                                child: Container(
                                  margin: const EdgeInsets.symmetric(
                                    horizontal: 8.5,
                                    vertical: 5,
                                  ),
                                  padding: const EdgeInsets.symmetric(
                                    horizontal: 12,
                                    vertical: 12,
                                  ),
                                  decoration: BoxDecoration(
                                    color:
                                        Colors
                                            .white, //Color(int.parse(item.rowColor!.replaceFirst('#', '0xff'))),
                                    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(
                                              widget.mode == "teamleader"
                                                  ? item.employeeName ?? "-"
                                                  : 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
                                      if (widget.mode == "teamleader")
                                        Container(
                                          padding: const EdgeInsets.symmetric(
                                            horizontal: 8,
                                            vertical: 4,
                                          ),
                                          decoration: BoxDecoration(
                                            color: Color(0x00FFFFFF),
                                            borderRadius: BorderRadius.circular(
                                              10,
                                            ),
                                          ),
                                          child: Text(
                                            item.leaveType ?? "-",
                                            style: TextStyle(
                                              fontFamily: "JakartaMedium",
                                              fontSize: 13,
                                              color: AppColors.app_blue,
                                            ),
                                          ),
                                        ),
                                    ],
                                  ),
                                ),
                              );
                            },
                          );
                        },
                      ),
                    ),
                    SizedBox(height: 28),
                  ],
                ),

                bottomNavigationBar:
                    widget.mode == "teamleader"
                        ? null
                        : Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 10,
                            vertical: 10,
                          ),
                          color: Colors.white,
                          child: InkResponse(
                            onTap: () {
                              HapticFeedback.selectionClick();
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder:
                                      (_) => ChangeNotifierProvider(
                                        create:
                                            (_) =>
                                                LeaveApplicationListProvider(),
                                        child: AddLeaveRequest(
                                          pageTitleName: "Add Leave Request",
                                        ),
                                      ),
                                ),
                              ).then((_) {
                                provider.fetchLeaveApplications(
                                  context,
                                  widget.mode,
                                );
                              });

                              // show add bill screen here
                            },
                            child: Container(
                              height: 45,
                              alignment: Alignment.center,
                              margin: EdgeInsets.symmetric(horizontal: 14),
                              padding: EdgeInsets.symmetric(
                                horizontal: 6,
                                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 Colors.redAccent.shade200;
      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
    }
  }
}
