import 'package:flutter/material.dart';
import 'package:marco/controller/permission_controller.dart';
import 'package:marco/controller/attendance/attendance_screen_controller.dart';
import 'package:marco/helpers/widgets/my_text.dart';
import 'package:marco/helpers/utils/permission_constants.dart';
import 'package:marco/helpers/utils/base_bottom_sheet.dart';
import 'package:get/get.dart';
import 'package:marco/helpers/utils/date_time_utils.dart';

class AttendanceFilterBottomSheet extends StatefulWidget {
  final AttendanceController controller;
  final PermissionController permissionController;
  final String selectedTab;

  const AttendanceFilterBottomSheet({
    super.key,
    required this.controller,
    required this.permissionController,
    required this.selectedTab,
  });

  @override
  State<AttendanceFilterBottomSheet> createState() =>
      _AttendanceFilterBottomSheetState();
}

class _AttendanceFilterBottomSheetState
    extends State<AttendanceFilterBottomSheet> {
  late String tempSelectedTab;

  @override
  void initState() {
    super.initState();
    tempSelectedTab = widget.selectedTab;
  }

  String getLabelText() {
    final startDate = widget.controller.startDateAttendance;
    final endDate = widget.controller.endDateAttendance;

    if (startDate != null && endDate != null) {
      final start =
          DateTimeUtils.formatDate(startDate, 'dd MMM yyyy'); 
      final end = DateTimeUtils.formatDate(endDate, 'dd MMM yyyy');
      return "$start - $end";
    }
    return "Date Range";
  }

  Widget _popupSelector({
    required String currentValue,
    required List<String> items,
    required ValueChanged<String> onSelected,
  }) {
    return PopupMenuButton<String>(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      onSelected: onSelected,
      itemBuilder: (context) => items
          .map((e) => PopupMenuItem<String>(
                value: e,
                child: MyText(e),
              ))
          .toList(),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        decoration: BoxDecoration(
          color: Colors.grey.shade100,
          border: Border.all(color: Colors.grey.shade300),
          borderRadius: BorderRadius.circular(12),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(
              child: MyText(
                currentValue,
                style: const TextStyle(color: Colors.black87),
                overflow: TextOverflow.ellipsis,
              ),
            ),
            const Icon(Icons.arrow_drop_down, color: Colors.grey),
          ],
        ),
      ),
    );
  }

  Widget _buildOrganizationSelector(BuildContext context) {
    final orgNames = [
      "All Organizations",
      ...widget.controller.organizations.map((e) => e.name)
    ];

    return _popupSelector(
      currentValue:
          widget.controller.selectedOrganization?.name ?? "All Organizations",
      items: orgNames,
      onSelected: (name) {
        if (name == "All Organizations") {
          setState(() {
            widget.controller.selectedOrganization = null;
          });
        } else {
          final selectedOrg = widget.controller.organizations
              .firstWhere((org) => org.name == name);
          setState(() {
            widget.controller.selectedOrganization = selectedOrg;
          });
        }
      },
    );
  }

  List<Widget> buildMainFilters() {
    final hasRegularizationPermission = widget.permissionController
        .hasPermission(Permissions.regularizeAttendance);

    final viewOptions = [
      {'label': 'Today\'s Attendance', 'value': 'todaysAttendance'},
      {'label': 'Attendance Logs', 'value': 'attendanceLogs'},
      {'label': 'Regularization Requests', 'value': 'regularizationRequests'},
    ];

    final filteredOptions = viewOptions.where((item) {
      return item['value'] != 'regularizationRequests' ||
          hasRegularizationPermission;
    }).toList();

    final List<Widget> widgets = [
      Padding(
        padding: const EdgeInsets.only(bottom: 4),
        child: Align(
          alignment: Alignment.centerLeft,
          child: MyText.titleSmall("View", fontWeight: 600),
        ),
      ),
      ...filteredOptions.map((item) {
        return RadioListTile<String>(
          dense: true,
          contentPadding: EdgeInsets.zero,
          title: MyText.bodyMedium(
            item['label']!,
            fontWeight: 500,
          ),
          value: item['value']!,
          groupValue: tempSelectedTab,
          onChanged: (value) => setState(() => tempSelectedTab = value!),
        );
      }),
    ];

    // 🔹 Organization filter
    widgets.addAll([
      const Divider(),
      Padding(
        padding: const EdgeInsets.only(top: 12, bottom: 12),
        child: Align(
          alignment: Alignment.centerLeft,
          child: MyText.titleSmall("Choose Organization", fontWeight: 600),
        ),
      ),
      Obx(() {
        if (widget.controller.isLoadingOrganizations.value) {
          return const Center(child: CircularProgressIndicator());
        } else if (widget.controller.organizations.isEmpty) {
          return Center(
            child: Padding(
              padding: const EdgeInsets.symmetric(vertical: 16.0),
              child: MyText.bodyMedium(
                "No organizations found",
                fontWeight: 500,
                color: Colors.grey,
              ),
            ),
          );
        }
        return _buildOrganizationSelector(context);
      }),
    ]);

    // 🔹 Date Range only for attendanceLogs
    if (tempSelectedTab == 'attendanceLogs') {
      widgets.addAll([
        const Divider(),
        Padding(
          padding: const EdgeInsets.only(top: 12, bottom: 4),
          child: Align(
            alignment: Alignment.centerLeft,
            child: MyText.titleSmall("Date Range", fontWeight: 600),
          ),
        ),
        InkWell(
          borderRadius: BorderRadius.circular(10),
          onTap: () async {
            await widget.controller.selectDateRangeForAttendance(
              context,
              widget.controller,
            );
            setState(() {});
          },
          child: Ink(
            decoration: BoxDecoration(
              color: Colors.white,
              border: Border.all(color: Colors.grey.shade400),
              borderRadius: BorderRadius.circular(10),
            ),
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
            child: Row(
              children: [
                const Icon(Icons.date_range, color: Colors.black87),
                const SizedBox(width: 12),
                Expanded(
                  child: MyText.bodyMedium(
                    getLabelText(),
                    fontWeight: 500,
                    color: Colors.black87,
                  ),
                ),
                const Icon(Icons.arrow_drop_down, color: Colors.black87),
              ],
            ),
          ),
        ),
      ]);
    }

    return widgets;
  }

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
      child: BaseBottomSheet(
        title: "Attendance Filter",
        submitText: "Apply",
        onCancel: () => Navigator.pop(context),
        onSubmit: () => Navigator.pop(context, {
          'selectedTab': tempSelectedTab,
          'selectedOrganization': widget.controller.selectedOrganization?.id,
        }),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: buildMainFilters(),
        ),
      ),
    );
  }
}
