import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:on_field_work/controller/tenant/organization_selection_controller.dart';
import 'package:on_field_work/helpers/widgets/my_text.dart';
import 'package:on_field_work/model/attendance/organization_per_project_list_model.dart';

class OrganizationSelector extends StatelessWidget {
  final OrganizationController controller;

  /// Called whenever a new organization is selected (including "All Organizations").
  final Future<void> Function(Organization?)? onSelectionChanged;

  /// Optional height for the selector. If null, uses default padding-based height.
  final double? height;

  const OrganizationSelector({
    super.key,
    required this.controller,
    this.onSelectionChanged,
    this.height,
  });

  Widget _popupSelector({
    required String currentValue,
    required List<String> items,
  }) {
    return PopupMenuButton<String>(
      color: Colors.white,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      onSelected: (name) async {
        Organization? org = name == "All Organizations"
            ? null
            : controller.organizations.firstWhere((e) => e.name == name);

        controller.selectOrganization(org);

        if (onSelectionChanged != null) {
          await onSelectionChanged!(org);
        }
      },
      itemBuilder: (context) => items
          .map((e) => PopupMenuItem<String>(value: e, child: MyText(e)))
          .toList(),
      child: Container(
        height: height,
        padding: const EdgeInsets.symmetric(horizontal: 12),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border.all(color: Colors.grey.shade300),
          borderRadius: BorderRadius.circular(12),
        ),
        child: Center(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Expanded(
                child: Text(
                  currentValue,
                  style: const TextStyle(
                    color: Colors.black87,
                    fontSize: 13,
                    height: 1.2,
                  ),
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              const Icon(Icons.arrow_drop_down, color: Colors.grey, size: 18),
            ],
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      if (controller.isLoadingOrganizations.value) {
        return Container(
          height: height ?? 40,
          padding: const EdgeInsets.symmetric(horizontal: 12),
          decoration: BoxDecoration(
            color: Colors.grey.shade300,
            borderRadius: BorderRadius.circular(12),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                width: 100,
                height: 14,
                color: Colors.grey.shade400,
              ),
              Container(
                width: 18,
                height: 18,
                decoration: BoxDecoration(
                  color: Colors.grey.shade400,
                  shape: BoxShape.circle,
                ),
              ),
            ],
          ),
        );
      } else if (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,
            ),
          ),
        );
      }

      final orgNames = [
        "All Organizations",
        ...controller.organizations.map((e) => e.name)
      ];

      return _popupSelector(
        currentValue: controller.currentSelection,
        items: orgNames,
      );
    });
  }
}
