import 'package:flutter/material.dart';
import 'package:on_field_work/controller/permission_controller.dart';
import 'package:on_field_work/controller/attendance/attendance_screen_controller.dart';
import 'package:on_field_work/helpers/widgets/my_text.dart';
import 'package:on_field_work/helpers/utils/base_bottom_sheet.dart';
import 'package:get/get.dart';
import 'package:on_field_work/helpers/widgets/date_range_picker.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> {

  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> _buildFilters() {
    final List<Widget> widgets = [];

    // Organization selector
    widgets.addAll([
      Padding(
        padding: const EdgeInsets.only(top: 12, bottom: 12),
        child: Align(
          alignment: Alignment.centerLeft,
          child: MyText.titleSmall("Change Organization", fontWeight: 600),
        ),
      ),
      Obx(() {
        if (widget.controller.isLoadingOrganizations.value) {
          return Container(
            height: 40,
            padding: const EdgeInsets.symmetric(horizontal: 12),
            decoration: BoxDecoration(
              color: Colors.grey.shade300,
              borderRadius: BorderRadius.circular(12),
            ),
          );
        } 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 Attendance Logs)
    if (widget.selectedTab == '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),
          ),
        ),
        DateRangePickerWidget(
          startDate: widget.controller.startDateAttendance,
          endDate: widget.controller.endDateAttendance,
          startLabel: "Start Date",
          endLabel: "End Date",
          onDateRangeSelected: (start, end) {
            setState(() {});
          },
        ),
      ]);
    }

    return widgets;
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: BaseBottomSheet(
        title: "Attendance Filter",
        submitText: "Apply",
        onCancel: () => Navigator.pop(context),
        onSubmit: () => Navigator.pop(context, {
          'selectedOrganization': widget.controller.selectedOrganization?.id,
        }),
        child: Padding(
          padding: const EdgeInsets.only(bottom: 24),
          child: SingleChildScrollView(
            physics: const BouncingScrollPhysics(),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: _buildFilters(),
            ),
          ),
        ),
      ),
    );
  }
}
