import 'package:flutter/material.dart';
import 'package:intl/intl.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';

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 = DateFormat('dd/MM/yyyy').format(startDate);
      final end = DateFormat('dd/MM/yyyy').format(endDate);
      return "$start - $end";
    }
    return "Date Range";
  }

  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: 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!),
        );
      }),
    ];

    if (tempSelectedTab == 'attendanceLogs') {
      widgets.addAll([
        const Divider(),
        Padding(
          padding: 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(() {}); // rebuild UI after date range is updated
          },
          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",
        onCancel: () => Navigator.pop(context),
        onSubmit: () => Navigator.pop(context, {
          'selectedTab': tempSelectedTab,
        }),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: buildMainFilters(),
        ),
      ),
    );
  }
}
