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/components/template.dart';
import 'package:telnow_mobile_new/src/layouts/web/request_create.dart';
import 'package:telnow_mobile_new/src/utils/U.dart';
import 'package:telnow_mobile_new/src/utils/provider.dart';

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

  @override
  State<WebReqSelectPage> createState() => _WebReqSelectPageState();
}

class _WebReqSelectPageState extends State<WebReqSelectPage> {
  final RequestFunction reqFunc = RequestFunction();
  TextEditingController searchController = TextEditingController()..text = '';

  @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: PreferredSize(preferredSize: Size.fromHeight(0), child: AppBar(elevation: 0, backgroundColor: primaryColor)),
      body: Column(
        children: [
          Container(
            padding: EdgeInsets.symmetric(vertical: 25, horizontal: 100),
            child: Row(
              children: [
                Text(widget.title, style: TextStyle(color: textColor, fontSize: 17, fontWeight: FontWeight.w500), overflow: TextOverflow.ellipsis),
                SizedBox(width: 50),
                Expanded(
                  child: SizedBox(
                    width: double.infinity,
                    child: TextField(
                        style: const TextStyle(fontSize: 14, color: Colors.black),
                        controller: searchController,
                        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(15),
                            prefixIcon: Padding(padding: EdgeInsets.symmetric(horizontal: 15), 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
                        ),
                        onSubmitted: (val){
                          reqFunc.getData(context, val, widget);
                        }
                    ),
                  ),
                ),
                SizedBox(width: 20),
                SizedBox(
                  height: 40, width: 100,
                  child: ElevatedButton(
                    style: ButtonStyle(elevation: MaterialStateProperty.all<double>(0), backgroundColor: MaterialStateProperty.all<Color>(primaryColor), shape: MaterialStateProperty.all<RoundedRectangleBorder>(RoundedRectangleBorder(borderRadius: BorderRadius.circular(50))), side: MaterialStateProperty.all<BorderSide>(BorderSide(color: primaryColor))),
                    onPressed: ()=>reqFunc.getData(context, searchController.text.trim()==''?null:searchController.text.trim(), widget),
                    child: Text('searchButton'.tr(), style: TextStyle(fontSize: 14, color: Colors.white, fontWeight: FontWeight.w600)),
                  ),
                ),
                SizedBox(width: 50),
                GestureDetector(
                  child: Text('buttonBack'.tr(), style: TextStyle(color: primaryColor, fontSize: 14)),
                  onTap: ()=>navigateBack(context),
                )
              ],
            ),
          ),
          divider(),
          Expanded(
            child: Provider.of<RequestModule>(context).isLoad()? loadingTemplate() : Container(
              width: double.infinity,
              child: SingleChildScrollView(
                padding: EdgeInsets.symmetric(vertical: 25, horizontal: 100),
                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)
                      ],
                    )
                )) : LayoutBuilder(
                  builder: (context, constraints) {
                    double size = (constraints.maxWidth/6)-13;
                    double minWidth = 185;
                    double minHeight = 250;

                    return Wrap(
                      spacing: 15, runSpacing: 15,
                      children: List.generate(Provider.of<RequestModule>(context).data().length, (i){
                        return GestureDetector(
                          child: ConstrainedBox(
                            constraints: BoxConstraints(minWidth: minWidth, minHeight: minHeight),
                            child: Container(
                              width: size, height: size*1.4,
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Expanded(child: imageTiles(imageUrl: Provider.of<RequestModule>(context).data()[i]['_mobileImage'] ?? "null", width: double.infinity, height: double.infinity)),
                                  Container(
                                    height: ((size*1.4) > minHeight ? (size*1.4) : minHeight) / 2.3,
                                    padding: EdgeInsets.fromLTRB(6, 12, 6, 0),
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Text(Provider.of<RequestModule>(context).data()[i][U.langColumn(context, 'subject')], style: TextStyle(color: textColor, fontWeight: FontWeight.w600), maxLines: 2, overflow: TextOverflow.ellipsis),
                                        dashed(),
                                        Text(Provider.of<RequestModule>(context).data()[i][U.langColumn(context, 'subjectDescription')], style: TextStyle(color: textColor), maxLines: 2, overflow: TextOverflow.ellipsis)
                                      ],
                                    ),
                                  )
                                ],
                              ),
                              decoration: BoxDecoration(color: Colors.white, border: Border.all(color: textColor.withValues(alpha: 0.15)), borderRadius: BorderRadius.all(Radius.circular(12))),
                            ),
                          ),
                          onTap: ()=>navigateTo(context, WebReqCreatePage(user: widget.user, request: Provider.of<RequestModule>(context, listen: false).data()[i], fromSearch: true)),
                        );
                      }),
                    );
                  },
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}
