import 'package:flutter/material.dart';
import 'package:frontend/Screens/group/group.dart';
import 'package:go_router/go_router.dart';
import 'package:responsive_builder/responsive_builder.dart';

import '../../routes/custom_appBar.dart';
import '../../routes/custom_drawer.dart';
import '../../services/apiService.dart';

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

  @override
  _OrganizationListState createState() => _OrganizationListState();
}

class _OrganizationListState extends State<OrganizationList> {
  final ApiService apiService = ApiService();

  Map<String, dynamic>? apiAllOrganization;

  @override
  void initState() {
    super.initState();
    loadAllOrganization();
  }

  Future<void> loadAllOrganization() async {
    try {
      final result = await apiService.fetchOrganization(context);
      setState(() {
        apiAllOrganization = result;
      });
      print("Fetched services: $apiAllOrganization");
    } catch (e) {
      print('Error fetching organization list: $e');
    }
  }

  // void deleteGroup(int groupId) {
  //   setState(() {
  //     apiAllGroups?.removeWhere((group) => group['group_id'] == groupId);
  //   });
  // }

  // Future<void> deleteGroupFromApi(int groupId) async {
  //   try {
  //     await apiService.deleteGroup(groupId); // your delete API call
  //     deleteGroup(groupId); // remove from UI list
  //   } catch (e) {
  //     print('Error deleting group: $e');
  //   }
  // }'

  @override
  Widget build(BuildContext context) {
    return ResponsiveBuilder(
      builder: (context, sizingInfo) {
        bool isDesktop =
            sizingInfo.deviceScreenType == DeviceScreenType.desktop;

        return Scaffold(
          backgroundColor: Colors.white,
          // appBar: isDesktop ? null : const CustomAppBar(title: 'Home'),
          // drawer: isDesktop ? null : CustomDrawer(isDesktop: false),
          appBar: CustomAppBar(isDesktop: isDesktop),
          drawer: CustomDrawer(isDesktop: false),
          body: Row(
            children: [
              // if (isDesktop) CustomDrawer(isDesktop: true),
              Expanded(child: buildGroupListLayout(isDesktop)),
            ],
          ),
        );
      },
    );
  }

  Widget buildGroupListLayout(bool isDesktop) {
    return Container(
      color: Colors.white,
      width: double.infinity,
      height: MediaQuery.of(context).size.height,
      margin: const EdgeInsets.all(8),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  const Text(
                    'Organization List',
                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                  ),
                  IconButton(
                    icon: const Icon(Icons.keyboard_arrow_down),
                    onPressed: () {},
                  ),
                ],
              ),
              ElevatedButton(
                style: ElevatedButton.styleFrom(
                  foregroundColor: Colors.white,
                  backgroundColor: Colors.blueAccent,
                ),
                onPressed: () async {
                  // List<dynamic> users = await futureUsers;
                  // context.go('/CreateGroup');
                },
                child: Row(
                  children: [
                    Icon(Icons.add_circle, color: Colors.white),
                    SizedBox(width: 5),
                    Text('Create Organization'),
                  ],
                ),
              ),
            ],
          ),
          Row(
            children: [
              Expanded(
                child: Container(
                  height: MediaQuery.of(context).size.height * 0.88,
                  margin: const EdgeInsets.only(bottom: 10),
                  // color: Colors.red.shade100,
                  child: SingleChildScrollView(
                    scrollDirection: Axis.vertical,
                    child: Column(children: [buildGroupListView(isDesktop)]),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  // Widget buildGroupListView(bool isDesktop) {
  //   return Container(
  //     child: Text("DAta"),
  //   );
  // }

  Widget buildGroupListView(bool isDesktop) {
    if (apiAllOrganization == null || apiAllOrganization!.isEmpty) {
      return Center(child: Text("No Data Found."));
    }

    return ListView.builder(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      itemCount: apiAllOrganization!.length,
      itemBuilder: (context, index) {
        final group = apiAllOrganization![index];
        return Card(
          margin: EdgeInsets.symmetric(vertical: 6, horizontal: 10),
          child: Padding(
            padding: const EdgeInsets.all(12.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      "Organization Name: ${group['name']}",
                      style: TextStyle(
                        fontSize: 13,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    Text(
                      "Organization Name: ${group['name']}",
                      style: TextStyle(
                        fontSize: 13,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 4),
                Text("Services: ${group['description'] ?? 'N/A'}"),
                Text("Created By : ${group['created_by']}"),
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    TextButton(
                      onPressed: () {
                        context.go("/CreateGroup", extra: group);

                        print("Edit ${group['group_id']}  $group");
                      },
                      child: Text("Edit"),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
