import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:marco/helpers/theme/app_theme.dart';
import 'package:marco/helpers/utils/mixins/ui_mixin.dart';
import 'package:marco/helpers/widgets/my_breadcrumb.dart';
import 'package:marco/helpers/widgets/my_breadcrumb_item.dart';
import 'package:marco/helpers/widgets/my_flex.dart';
import 'package:marco/helpers/widgets/my_flex_item.dart';
import 'package:marco/helpers/widgets/my_spacing.dart';
import 'package:marco/helpers/widgets/my_text.dart';
import 'package:marco/view/layouts/layout.dart';
import 'package:marco/controller/permission_controller.dart';
import 'package:marco/controller/dashboard/employees_screen_controller.dart';
import 'package:marco/helpers/widgets/my_loading_component.dart';
import 'package:marco/helpers/widgets/my_refresh_wrapper.dart';
import 'package:marco/model/my_paginated_table.dart';

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

  @override
  State<EmployeeScreen> createState() => _EmployeeScreenState();
}

class _EmployeeScreenState extends State<EmployeeScreen> with UIMixin {
  final EmployeesScreenController employeesScreenController =
      Get.put(EmployeesScreenController());
  final PermissionController permissionController =
      Get.put(PermissionController());

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      employeesScreenController.selectedProjectId = null;
      await employeesScreenController.fetchAllEmployees();
      employeesScreenController.update();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Layout(
      child: Obx(() {
        return LoadingComponent(
          isLoading: employeesScreenController.isLoading.value,
          loadingText: 'Loading Employees...',
          child: GetBuilder<EmployeesScreenController>(
            init: employeesScreenController,
            builder: (controller) {
              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: MySpacing.x(flexSpacing),
                    child: MyText.titleMedium("Employee",
                        fontSize: 18, fontWeight: 600),
                  ),
                  MySpacing.height(flexSpacing),
                  Padding(
                    padding: MySpacing.x(flexSpacing),
                    child: MyBreadcrumb(
                      children: [
                        MyBreadcrumbItem(name: 'Dashboard'),
                        MyBreadcrumbItem(name: 'Employee', active: true),
                      ],
                    ),
                  ),
                  MySpacing.height(flexSpacing),
                  Padding(
                    padding: MySpacing.x(flexSpacing),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Flexible(
                          child: Container(
                            decoration: BoxDecoration(
                              border: Border.all(
                                color: Colors.black,
                                width: 1.5,
                              ),
                              borderRadius: BorderRadius.circular(4),
                            ),
                            child: PopupMenuButton<String>(
                              onSelected: (String value) async {
                                if (value.isEmpty) {
                                  employeesScreenController.selectedProjectId =
                                      null;
                                  await employeesScreenController
                                      .fetchAllEmployees();
                                } else {
                                  employeesScreenController.selectedProjectId =
                                      value;
                                  await employeesScreenController
                                      .fetchEmployeesByProject(value);
                                }
                                employeesScreenController.update();
                              },
                              itemBuilder: (BuildContext context) {
                                List<PopupMenuItem<String>> items = [
                                  PopupMenuItem<String>(
                                    value: '',
                                    child: MyText.bodySmall('All Employees',
                                        fontWeight: 600),
                                  ),
                                ];

                                items.addAll(
                                  employeesScreenController.projects
                                      .map<PopupMenuItem<String>>((project) {
                                    return PopupMenuItem<String>(
                                      value: project.id,
                                      child: MyText.bodySmall(project.name),
                                    );
                                  }).toList(),
                                );

                                return items;
                              },
                              child: Padding(
                                padding: const EdgeInsets.symmetric(
                                    horizontal: 12.0, vertical: 8.0),
                                child: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Flexible(
                                      child: Text(
                                        employeesScreenController
                                                    .selectedProjectId ==
                                                null
                                            ? 'All Employees'
                                            : employeesScreenController.projects
                                                .firstWhere((project) =>
                                                    project.id ==
                                                    employeesScreenController
                                                        .selectedProjectId)
                                                .name,
                                        overflow: TextOverflow.ellipsis,
                                        style: const TextStyle(
                                            fontWeight: FontWeight.w600),
                                      ),
                                    ),
                                    const SizedBox(width: 4),
                                    const Icon(
                                      Icons.arrow_drop_down,
                                      size: 20,
                                      color: Colors.black,
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ),
                        ),
                        const SizedBox(width: 10),
                        ElevatedButton(
                          onPressed: () {
                            Get.toNamed('/employees/addEmployee');
                          },
                          child: Text('Add New Employee'),
                        ),
                      ],
                    ),
                  ),
                  MySpacing.height(flexSpacing),
                  Padding(
                    padding: MySpacing.x(flexSpacing / 2),
                    child: MyFlex(
                      children: [
                        MyFlexItem(sizes: 'lg-6 ', child: employeeListTab()),
                      ],
                    ),
                  ),
                ],
              );
            },
          ),
        );
      }),
    );
  }

  Widget employeeListTab() {
    if (employeesScreenController.employees.isEmpty) {
      return Center(
        child: MyText.bodySmall("No Employees Assigned to This Project",
            fontWeight: 600),
      );
    }

    final columns = <DataColumn>[
      DataColumn(label: MyText.labelLarge('Name', color: contentTheme.primary)),
      DataColumn(
          label: MyText.labelLarge('Contact', color: contentTheme.primary)),
    ];

    final rows =
        employeesScreenController.employees.asMap().entries.map((entry) {
      var employee = entry.value;
      return DataRow(
        cells: [
          DataCell(
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                MyText.bodyMedium(employee.name, fontWeight: 600),
                const SizedBox(height: 2),
                MyText.bodySmall(employee.jobRole, color: Colors.grey),
              ],
            ),
          ),
          DataCell(
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                MyText.bodyMedium(employee.email, fontWeight: 600),
                const SizedBox(height: 2),
                MyText.bodySmall(employee.phoneNumber, color: Colors.grey),
              ],
            ),
          ),
        ],
      );
    }).toList();

    return MyRefreshableContent(
      onRefresh: () async {
        if (employeesScreenController.selectedProjectId == null) {
          await employeesScreenController.fetchAllEmployees();
        } else {
          await employeesScreenController.fetchEmployeesByProject(
            employeesScreenController.selectedProjectId!,
          );
        }
      },
      child: MyPaginatedTable(
        columns: columns,
        rows: rows,
      ),
    );
  }
}
