import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:on_field_work/helpers/utils/mixins/ui_mixin.dart';
import 'package:on_field_work/helpers/widgets/my_spacing.dart';
import 'package:on_field_work/helpers/widgets/my_text.dart';
import 'package:on_field_work/helpers/widgets/my_text_style.dart';
import 'package:on_field_work/helpers/utils/base_bottom_sheet.dart';
import 'package:on_field_work/helpers/widgets/date_range_picker.dart';
import 'package:on_field_work/controller/service_project/add_service_project_job_controller.dart';
import 'package:on_field_work/model/employees/employee_model.dart';
import 'package:on_field_work/model/employees/multiple_select_bottomsheet.dart';
import 'package:on_field_work/model/service_project/service_project_branches_model.dart';

class AddServiceProjectJobBottomSheet extends StatefulWidget {
  final String projectId;
  const AddServiceProjectJobBottomSheet({super.key, required this.projectId});

  @override
  State<AddServiceProjectJobBottomSheet> createState() =>
      _AddServiceProjectJobBottomSheetState();
}

class _AddServiceProjectJobBottomSheetState
    extends State<AddServiceProjectJobBottomSheet> with UIMixin {
  final formKey = GlobalKey<FormState>();
  final controller = Get.put(AddServiceProjectJobController());

  late RxList<EmployeeModel> _selectedEmployees;

  @override
  void initState() {
    super.initState();
    _selectedEmployees =
        RxList<EmployeeModel>.from(controller.selectedAssignees);
    controller.fetchBranches(widget.projectId);
  }

  @override
  void dispose() {
    Get.delete<AddServiceProjectJobController>();
    super.dispose();
  }

  InputDecoration _inputDecoration(String hint) => InputDecoration(
        hintText: hint,
        hintStyle: MyTextStyle.bodySmall(xMuted: true),
        filled: true,
        fillColor: Colors.grey.shade100,
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide(color: Colors.grey.shade300),
        ),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide(color: Colors.grey.shade300),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: const BorderSide(color: Colors.blueAccent, width: 1.5),
        ),
        contentPadding:
            const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
        isDense: true,
      );

  Widget _labelWithStar(String label, {bool required = false}) => Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          MyText.labelMedium(label),
          if (required)
            const Text(" *", style: TextStyle(color: Colors.red, fontSize: 14)),
        ],
      );

  Widget _textField(String label, TextEditingController ctrl,
          {bool required = false, int maxLines = 1}) =>
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _labelWithStar(label, required: required),
          MySpacing.height(8),
          TextFormField(
            controller: ctrl,
            maxLines: maxLines,
            decoration: _inputDecoration("Enter $label"),
            validator: required
                ? (v) => (v == null || v.trim().isEmpty)
                    ? "$label is required"
                    : null
                : null,
          ),
        ],
      );

  Widget _branchSelector() => Obx(() {
        if (controller.isBranchLoading.value) {
          return const Center(child: CircularProgressIndicator());
        }

        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            MyText.labelMedium("Select Branch (Optional)"),
            MySpacing.height(8),
            PopupMenuButton<Branch>(
              onSelected: (branch) {
                controller.selectedBranch.value = branch;
              },
              itemBuilder: (_) => controller.branches
                  .map(
                    (b) => PopupMenuItem(
                      value: b,
                      child: Text(b.branchName),
                    ),
                  )
                  .toList(),
              child: Container(
                padding:
                    const EdgeInsets.symmetric(horizontal: 14, vertical: 14),
                decoration: BoxDecoration(
                  color: Colors.grey.shade100,
                  borderRadius: BorderRadius.circular(12),
                  border: Border.all(color: Colors.grey.shade300),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Obx(() => Text(
                          controller.selectedBranch.value?.branchName ??
                              "Select Branch (Optional)",
                          style: MyTextStyle.bodySmall(
                            color: Colors.grey.shade700,
                          ),
                        )),
                    const Icon(Icons.arrow_drop_down),
                  ],
                ),
              ),
            ),
          ],
        );
      });

  Widget _employeeSelector() => Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _labelWithStar("Select Assignees", required: true),
          MySpacing.height(8),
          GestureDetector(
            onTap: () async {
              final selectedEmployees =
                  await showModalBottomSheet<List<EmployeeModel>>(
                context: context,
                isScrollControlled: true,
                builder: (_) => EmployeeSelectionBottomSheet(
                  multipleSelection: true,
                  initiallySelected: _selectedEmployees,
                ),
              );

              if (selectedEmployees != null) {
                _selectedEmployees.assignAll(selectedEmployees);
                controller.selectedAssignees.assignAll(selectedEmployees);
              }
            },
            child: AbsorbPointer(
              child: Obx(() => TextFormField(
                    decoration: _inputDecoration("Select Employees"),
                    controller: TextEditingController(
                      text: _selectedEmployees.isEmpty
                          ? ""
                          : _selectedEmployees
                              .map((e) => "${e.firstName} ${e.lastName}")
                              .join(", "),
                    ),
                    validator: (v) => _selectedEmployees.isEmpty
                        ? "Please select employees"
                        : null,
                  )),
            ),
          ),
          MySpacing.height(8),
          Obx(() => Wrap(
                spacing: 8,
                runSpacing: 4,
                children: _selectedEmployees
                    .map(
                      (emp) => Chip(
                        label: Text('${emp.firstName} ${emp.lastName}'),
                        onDeleted: () {
                          _selectedEmployees.remove(emp);
                          controller.selectedAssignees.remove(emp);
                        },
                      ),
                    )
                    .toList(),
              )),
        ],
      );

  // ----------------- UPDATED TAG INPUT -----------------

  Widget _tagInput() => Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            height: 48,
            child: TextFormField(
              controller: controller.tagCtrl,
              textInputAction: TextInputAction.done,

              // 🚀 Auto-create tag when space pressed
              onChanged: (value) {
                if (value.endsWith(' ')) {
                  final raw = value.trim();
                  if (raw.isNotEmpty) {
                    final parts = raw
                        .split(RegExp(r'[, ]+'))
                        .map((s) => s.trim())
                        .where((s) => s.isNotEmpty);

                    for (final p in parts) {
                      final clean = p.replaceAll('_', ' ');
                      if (!controller.enteredTags.contains(clean)) {
                        controller.enteredTags.add(clean);
                      }
                    }
                  }
                  controller.tagCtrl.clear();
                }
              },

              onEditingComplete: () {
                final raw = controller.tagCtrl.text.trim();
                if (raw.isEmpty) return;

                final parts = raw
                    .split(RegExp(r'[, ]+'))
                    .map((s) => s.trim())
                    .where((s) => s.isNotEmpty);

                for (final p in parts) {
                  final clean = p.replaceAll('_', ' ');
                  if (!controller.enteredTags.contains(clean)) {
                    controller.enteredTags.add(clean);
                  }
                }
                controller.tagCtrl.clear();
              },

              onFieldSubmitted: (v) {
                final raw = v.trim();
                if (raw.isEmpty) return;

                final parts = raw
                    .split(RegExp(r'[, ]+'))
                    .map((s) => s.trim())
                    .where((s) => s.isNotEmpty);

                for (final p in parts) {
                  final clean = p.replaceAll('_', ' ');
                  if (!controller.enteredTags.contains(clean)) {
                    controller.enteredTags.add(clean);
                  }
                }
                controller.tagCtrl.clear();
              },

              decoration: _inputDecoration("Start typing to add tags"),
              validator: (v) => controller.enteredTags.isEmpty
                  ? "Please add at least one tag"
                  : null,
            ),
          ),
          MySpacing.height(8),
          Obx(() => Wrap(
                spacing: 8,
                children: controller.enteredTags
                    .map((tag) => Chip(
                          label: Text(tag),
                          onDeleted: () => controller.enteredTags.remove(tag),
                        ))
                    .toList(),
              )),
        ],
      );

  // ------------------------------------------------------

  void _handleSubmit() {
    if (!(formKey.currentState?.validate() ?? false)) return;
    controller.titleCtrl.text = controller.titleCtrl.text.trim();
    controller.descCtrl.text = controller.descCtrl.text.trim();
    controller.createJob(widget.projectId);
  }

  @override
  Widget build(BuildContext context) {
    return BaseBottomSheet(
      title: "Add New Job",
      onCancel: () => Get.back(),
      onSubmit: _handleSubmit,
      child: Form(
        key: formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _textField("Title", controller.titleCtrl, required: true),
            MySpacing.height(16),
            _employeeSelector(),
            MySpacing.height(16),
            _branchSelector(),
            MySpacing.height(16),
            _labelWithStar("Tags", required: true),
            MySpacing.height(8),
            _tagInput(),
            MySpacing.height(16),
            _labelWithStar("Select Date Range", required: true),
            MySpacing.height(8),
            DateRangePickerWidget(
              startDate: controller.startDate,
              endDate: controller.dueDate,
              startLabel: "Start Date",
              endLabel: "Due Date",
              onDateRangeSelected: (start, end) {
                controller.startDate.value;
                controller.dueDate.value;
              },
            ),
            MySpacing.height(16),
            _textField("Description", controller.descCtrl,
                required: true, maxLines: 3),
          ],
        ),
      ),
    );
  }
}
