import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/Utils/GlobalConstants.dart';
import 'package:generp/screens/hrm/AddManualAttendance.dart';
import 'package:generp/screens/hrm/AttendanceRequestDetail.dart';
import 'package:provider/provider.dart';
import '../../Notifiers/hrmProvider/attendanceListProvider.dart';
import '../../Utils/app_colors.dart';
import '../../Utils/commonWidgets.dart';
import '../CommonFilter2.dart';
import '../commonDateRangeFilter.dart';
import 'AddLiveAttendance.dart';

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

  @override
  State<Attendancelist> createState() => _AttendancelistState();
}

class _AttendancelistState extends State<Attendancelist> {
  // @override
  // void initState() {
  //   super.initState();
  //   WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
  //     final provider = Provider.of<Attendancelistprovider>(context, listen: false);
  //     provider.fetchAttendanceRequests(context);
  //   });
  // }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      top: false,
        child: ChangeNotifierProvider(
      create: (_) {
        final provider = Attendancelistprovider();
        Future.microtask(() {
          provider.fetchAttendanceRequests(context);
        });
        return provider;
      },
      builder: (context, child) {
        return Consumer<Attendancelistprovider>(
          builder: (context, provider, child) {
            return Scaffold(
              appBar: AppBar(
                automaticallyImplyLeading: false,
                backgroundColor: Colors.white,
                title: Row(
                  children: [
                    InkResponse(
                      onTap: () => Navigator.pop(context, true),
                      child: SvgPicture.asset(
                        "assets/svg/appbar_back_button.svg",
                        height: 25,
                      ),
                    ),
                    const SizedBox(width: 10),
                    Text(
                      "Attendance List",
                      style: TextStyle(
                        fontSize: 18,
                        fontFamily: "Plus Jakarta Sans",
                        fontWeight: FontWeight.w600,
                        color: AppColors.semi_black,
                      ),
                    ),
                  ],
                ),
                actions: [
                  InkResponse(
                    onTap: () async {
                      final result = await CommonFilter2().showFilterBottomSheet(context);

                      if (result != null) {
                        final provider = Provider.of<Attendancelistprovider>(context, listen: false);

                        provider.updateFiltersFromSheet(
                          context,
                          type: result['type'] ?? "All",
                          selectedValue: result['selectedValue'] ?? "This Month",
                          customRange: result['dateRange'],
                        );
                      }
                    },
                    child: SvgPicture.asset(
                      "assets/svg/filter_ic.svg",
                      height: 25,
                    ),
                  ),
                  const SizedBox(width: 20),
                ],


              ),
              backgroundColor: const Color(0xFFF6F6F8),
              body: Column(
                children: [
                  /// Filter chips - show active filters
                  // if (provider.selectedType != "All" || provider.selectedDateRange != "This Month")
                  //   Container(
                  //     padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                  //     color: Colors.white,
                  //     child: Wrap(
                  //       spacing: 8,
                  //       children: [
                  //         if (provider.selectedType != "All")
                  //           Chip(
                  //             label: Text('Type: ${provider.selectedType}'),
                  //             onDeleted: () {
                  //               provider.setTypeFilter(context, "All");
                  //             },
                  //           ),
                  //         if (provider.selectedDateRange != "This Month")
                  //           Chip(
                  //             label: Text('Date: ${provider.selectedDateRange}'),
                  //             onDeleted: () {
                  //               provider.setDateRangeFilter(context, "This Month");
                  //             },
                  //           ),
                  //       ],
                  //     ),
                  //   ),

                  /// Attendance 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 attendance records found",
                              style: TextStyle(fontSize: 16, color: Colors.grey),
                            ),
                          );
                        }

                        final list = provider.response!.requestList!;
                        return ListView.builder(
                          padding: const EdgeInsets.all(8),
                          itemCount: list.length,
                          itemBuilder: (context, index) {
                            final item = list[index];

                            return InkWell(
                              borderRadius: BorderRadius.circular(16),
                              onTap: () {
                                ///  navigation flow
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (context) => AttendanceRequestDetailScreen(
                                      attendanceListId: item.id,
                                    ),
                                  ),
                                );
                              },
                              child: Container(
                                margin: const EdgeInsets.symmetric(horizontal: 8.5, vertical: 5),
                                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8.5),
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(16),
                                ),
                                child: Row(
                                  children: [
                                    /// Left Avatar Circle
                                    Container(
                                      height: 48,
                                      width: 50,
                                      padding: const EdgeInsets.all(8.0),
                                      decoration: BoxDecoration(
                                        color: _getAvatarColor(item.status),
                                        shape: BoxShape.circle,
                                      ),
                                      child: Center(
                                        child: Text(
                                          getText(item.status),
                                          style: TextStyle(
                                            color: _getTextColor(item.status),
                                            fontSize: 14,
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                      ),
                                    ),
                                    const SizedBox(width: 10),

                                    /// Middle Section
                                    Expanded(
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Text(
                                            item.type ?? "-",
                                            maxLines: 1,
                                            overflow: TextOverflow.ellipsis,
                                            style: TextStyle(
                                              fontFamily: "JakartaRegular",
                                              fontSize: 14,
                                              color: AppColors.semi_black,
                                            ),
                                          ),
                                          Text(
                                            item.date ?? "-",
                                            style: TextStyle(
                                              fontFamily: "JakartaRegular",
                                              fontSize: 14,
                                              color: AppColors.grey_semi,
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),

                                    /// Right Status (Live / Manual)
                                    Text(
                                      item.attendanceType ?? "-",
                                      textAlign: TextAlign.right,
                                      style: TextStyle(
                                        fontFamily: "JakartaMedium",
                                        fontSize: 14,
                                        color: (item.attendanceType ?? "").toLowerCase() == "live"
                                            ? Colors.green
                                            : Colors.orange,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            );
                          },
                        );
                      },
                    ),
                  )
                ],
              ),
              bottomNavigationBar: Container(
                alignment: Alignment.bottomCenter,
                height: 54,
                decoration: const BoxDecoration(color: Colors.white),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Expanded(
                      child: InkResponse(
                        onTap: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => AddLiveAttendanceScreen(),
                              settings: const RouteSettings(
                                name: 'AddLiveAttendanceScreen',
                              ),
                            ),
                          ).then((_) {
                            provider.fetchAttendanceRequests(context);
                          });
                        },
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            SvgPicture.asset("assets/svg/hrm/live.svg"),
                            const SizedBox(width: 10),
                            Text("Live Request",
                                style: TextStyle(color: AppColors.semi_black)),
                          ],
                        ),
                      ),
                    ),
                    const SizedBox(width: 10),
                    SvgPicture.asset("assets/svg/crm/vertical_line_ic.svg"),
                    const SizedBox(width: 10),
                    Expanded(
                      child: InkResponse(
                        onTap: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => const AddManualAttendanceScreen(),
                              settings: const RouteSettings(
                                  name: 'AddManualAttendanceScreen'),
                            ),
                          ).then((_) {
                            provider.fetchAttendanceRequests(context);
                          });
                        },
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            SvgPicture.asset("assets/svg/hrm/manual.svg"),
                            const SizedBox(width: 10),
                            Text("Manual Request",
                                style: TextStyle(color: AppColors.semi_black)),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            );

          },
        );
      },
    )
    );
  }


  /// Avatar color generator
  Color _getAvatarColor(value) {
    var color = AppColors.approved_bg_color;
    switch (value) {
      case 'Requested':
        return AppColors.requested_bg_color;
      case 'Level 1 Approved':
        return AppColors.approved_bg_color;
      case 'Level 1 Rejected':
        return AppColors.rejected_bg_color;
      case 'Level 2 Approved':
        return AppColors.approved_bg_color;
      case 'Level 2 Rejected':
        return AppColors.rejected_bg_color;
      case 'Updated':
        return AppColors.processed_bg_color;
      case 'Payment Rejected':
        return AppColors.rejected_bg_color;
    }
    return color;
  }

  Color _getTextColor(value) {
    var color = AppColors.approved_text_color;
    switch (value) {
      case 'Requested':
        return AppColors.requested_text_color;
      case 'Level 1 Approved':
        return AppColors.approved_text_color;
      case 'Level 1 Rejected':
        return AppColors.rejected_text_color;
      case 'Level 2 Approved':
        return AppColors.approved_text_color;
      case 'Level 2 Rejected':
        return AppColors.rejected_text_color;
      case 'Updated':
        return AppColors.processed_text_color;
    }
    return color;
  }

  getText(value) {
    switch (value) {
      case 'Requested':
        return "R";
      case 'Level 1 Approved':
        return "L1A";
      case 'Level 1 Rejected':
        return "L1R";
      case 'Level 2 Approved':
        return "L2A";
      case 'Level 2 Rejected':
        return "L2R";
      case 'Updated':
        return "U";
      default:
        return "Requested";
    }
  }
}