import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:lottie/lottie.dart';
import 'package:provider/provider.dart';
import 'package:telnow_mobile_new/src/layouts/functions/request.dart';
import 'package:telnow_mobile_new/src/layouts/mobile/request_create.dart';
import 'package:telnow_mobile_new/src/layouts/components/template.dart';
import 'package:telnow_mobile_new/src/utils/U.dart';
import 'package:telnow_mobile_new/src/utils/provider.dart';

class MobReqSelectPage extends StatefulWidget {
  final String title;
  final String? groupCode;
  final String scope;
  final String? tenantCode;
  final String? placeholder;
  final Map<String, dynamic> user;
  const MobReqSelectPage({required this.title, this.groupCode, required this.scope, this.tenantCode, required this.user, this.placeholder, super.key});

  @override
  State<MobReqSelectPage> createState() => _MobReqSelectPageState();
}

class _MobReqSelectPageState extends State<MobReqSelectPage> {
  final RequestFunction reqFunc = RequestFunction();
  final debounce = Debouncer(milliseconds: 1000);

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      Provider.of<RequestModule>(context, listen: false).reset();

      if(widget.groupCode != null){
        Provider.of<RequestModule>(context, listen: false).setPlaceholder('${'searchIn'.tr()} ${widget.title}');
        reqFunc.getData(context, null, widget);
      }
      else{
        Provider.of<RequestModule>(context, listen: false).setPlaceholder(widget.placeholder ?? '');
      }
    });

    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: backgroundColor,
      appBar: appBarTemplate(context: context, exc: false, title: widget.title),
      body: Column(
        children: [
          Container(
            padding: EdgeInsets.fromLTRB(16, 0, 16, 16),
            child: SizedBox(
              width: double.infinity,
              child: TextField(
                  style: const TextStyle(fontSize: 14, color: Colors.black),
                  autofocus: widget.groupCode == null,
                  decoration: InputDecoration(
                      hintText: Provider.of<RequestModule>(context).placeholder(),
                      hintStyle: TextStyle(color: textColor.withValues(alpha: 0.5), fontSize: 14),
                      filled: true,
                      fillColor: backgroundColor,
                      hoverColor: Colors.black.withValues(alpha: 0.1),
                      contentPadding: EdgeInsets.all(13),
                      prefixIcon: Padding(padding: EdgeInsets.only(left: 20, right: 13), child: U.iconsax('search-normal-1', color: textColor, size: 24)),
                      border: InputBorder.none,
                      enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(50), borderSide: BorderSide(color: Color(0xff262626).withValues(alpha: 0.5))),
                      focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(50), borderSide: const BorderSide(color: primaryColor)),
                      isDense: true
                  ),
                  onChanged: (val){
                    debounce.run(() {
                      reqFunc.getData(context, val, widget);
                    });
                  }
              ),
            ),
          ),
          divider(),
          Expanded(
            child: Container(
              alignment: Alignment.topCenter,
              width: U.bodyWidth(context),
              child: Provider.of<RequestModule>(context).isLoad()? loadingTemplateNoVoid() : SingleChildScrollView(
                padding: EdgeInsets.symmetric(horizontal: 16),
                child: Provider.of<RequestModule>(context).isEmpty() ? Center(child: Padding(
                    padding: const EdgeInsets.only(top: 24.0),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        kIsWeb && !isCanvasKit ? Container(
                            width: 150, margin: EdgeInsets.only(top: 20, bottom: 10), padding: EdgeInsets.all(10),
                            child: Image(image: AssetImage('assets/image/error/EmptyData.png'))
                        ) : Lottie.asset('assets/image/lottie/Nodata.json', width: 250, height: 250, fit: BoxFit.fill),
                        RichText(text: TextSpan(
                            style: TextStyle(color: textColor.withValues(alpha: 0.65), fontStyle: FontStyle.italic, height: 1.5, fontSize: 16.0),
                            children: <TextSpan>[
                              TextSpan(text: U.getInternetStatus()?'notFoundKeyword'.tr():'noDataText'.tr()),
                              TextSpan(text: U.getInternetStatus()?'"${Provider.of<RequestModule>(context).keyword()}".':'', style: TextStyle(fontWeight: FontWeight.w600)),
                            ]
                        ),textAlign: TextAlign.center)
                      ],
                    )
                )) : Column(
                  children: List.generate(Provider.of<RequestModule>(context).data().length, (i){
                    return GestureDetector(
                      child: requestTiles(
                        image: Provider.of<RequestModule>(context).data()[i]['_mobileImage'] ?? "null",
                        title: Provider.of<RequestModule>(context).data()[i][U.langColumn(context, 'subject')] ?? '-',
                        subtitle: Provider.of<RequestModule>(context).data()[i][U.langColumn(context, 'subjectDescription')]??'-',
                      ),
                      onTap: ()=>navigateTo(context, MobReqCreatePage(user: widget.user, request: Provider.of<RequestModule>(context, listen: false).data()[i], fromSearch: true)),
                    );
                  }),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}
