import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/api_routes/urls.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/modules/internal_audit_module/models/system_internal_audit_form_model.dart';
import 'package:test_sa/modules/internal_audit_module/provider/internal_audit_provider.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/app_style/app_text_style.dart';
import 'package:test_sa/views/app_style/sizing.dart';

class SystemAuditWoAutoCompleteField extends StatefulWidget {
  final String initialValue;
  final int? woTypeId;
  final TextEditingController controller;
  final bool clearAfterPick;
  final Function(WoAutoCompleteModel) onPick;

  const SystemAuditWoAutoCompleteField({Key? key, required this.initialValue, this.woTypeId, required this.onPick, this.clearAfterPick = true, required this.controller}) : super(key: key);

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

class _SystemAuditWoAutoCompleteFieldState extends State<SystemAuditWoAutoCompleteField> {
  late InternalAuditProvider _provider;

  //
  // late TextEditingController _controller;

  bool loading = false;

  @override
  void initState() {
    // w controller = widget.controller ?? TextEditingController(text: widget.initialValue);
    super.initState();
    _provider = Provider.of<InternalAuditProvider>(context, listen: false);
  }

  @override
  void didUpdateWidget(covariant SystemAuditWoAutoCompleteField oldWidget) {
    // if (widget.initialValue != oldWidget.initialValue) {
    //   // _controller = widget.controller ?? TextEditingController(text: widget.initialValue);
    // }
    super.didUpdateWidget(oldWidget);
  }

  @override
  void dispose() {
    if (widget.controller == null) {
      // _controller.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final border = UnderlineInputBorder(borderSide: BorderSide.none, borderRadius: BorderRadius.circular(10));
    return Container(
      decoration: BoxDecoration(
        color: AppColor.background(context),
        borderRadius: BorderRadius.circular(AppStyle.borderRadius * AppStyle.getScaleFactor(context)),
        //  boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 10)],
      ),
      child: Autocomplete<WoAutoCompleteModel>(
        optionsBuilder: (TextEditingValue textEditingValue) async {
          if (textEditingValue.text.isEmpty) {
            if (loading) {
              setState(() {
                loading = false;
              });
            }
            return const Iterable<WoAutoCompleteModel>.empty();
          }
          if (!loading) {
            setState(() {
              loading = true;
            });
          }
          List<WoAutoCompleteModel> workOrders = (await _provider.getWorkOrderByWoType(text: textEditingValue.text, woId:widget.woTypeId));
          setState(() {
            loading = false;
          });
          return workOrders;
        },
        displayStringForOption: (WoAutoCompleteModel option) => option.displayName ?? '',
        fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) {
          return TextField(
            controller: widget.controller,
            focusNode: fieldFocusNode,
            style: AppTextStyles.bodyText.copyWith(color: AppColor.black10),
            textAlign: TextAlign.start,
            decoration: InputDecoration(
              border: border,
              disabledBorder: border,
              focusedBorder: border,
              enabledBorder: border,
              errorBorder: border,
              contentPadding: EdgeInsets.symmetric(vertical: 8.toScreenHeight, horizontal: 16.toScreenWidth),
              constraints: const BoxConstraints(),
              suffixIconConstraints: const BoxConstraints(maxHeight: 24, maxWidth: 24 + 8),
              filled: true,
              fillColor: AppColor.fieldBgColor(context),
              errorStyle: AppTextStyle.tiny.copyWith(color: context.isDark ? AppColor.red50 : AppColor.red60),
              floatingLabelStyle: AppTextStyle.body1.copyWith(fontWeight: FontWeight.w500, color: context.isDark ? null : AppColor.neutral20),
              labelText: context.translation.woNumber,
              labelStyle: AppTextStyles.tinyFont.copyWith(color: AppColor.textColor(context)),
              suffixIcon: loading ? CircularProgressIndicator(color: AppColor.loadingColor(context), strokeWidth: 3.0).paddingOnly(end: 8) : null,
            ),
            textInputAction: TextInputAction.search,
            onChanged: (text) {
              fieldTextEditingController.text = text;
            },
            onSubmitted: (String value) {
              onFieldSubmitted();
            },
          );
        },
        onSelected: (WoAutoCompleteModel selection) {
          if (widget.clearAfterPick) {
            widget.controller.clear();
          } else {
            widget.controller.text = (selection.displayName ?? "");
          }
          widget.onPick(selection);
        },
      ),
    );
  }

  // String getUrl(int? woTypeId) {
  //   if (woTypeId == null) return '';
  //   String base = URLs.woAutoCompleteBase;
  //   var urlMap = {
  //     1: '$base/ServiceRequest/WorkOrderAutoComplete', // CM
  //     2: '$base/GasRefill/GetGasRefillAutoComplete', // Gas Refill
  //     3: '$base/AssetTransfer/GetAssetTransferAutoComplete', // Asset Transfer
  //     4: '$base/PlanPreventiveVisit/GetAutoCompletePlanPreventiveVisit', // PPM Request
  //     5: '$base/PlanRecurrentTasks/GetPlanRecurrentTask', // Recurrent WO
  //     6: '$base/TaskJobs/AutocompleteTaskJob', // Task
  //     7: '$base/TaskJobs/AutocompleteTaskJob', // Recall & Alert
  //   };
  //   return urlMap[woTypeId] ?? '';
  // }
}
