//request main page

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/all_requests_provider.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/models/search_all_requests_model.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/pages/land_page/my_request/all_requests_filter_page.dart';
import 'package:test_sa/new_views/pages/land_page/my_request/all_requests_search_page.dart';
import 'package:test_sa/new_views/pages/land_page/widgets/request_item_view_list.dart';
import 'package:test_sa/views/widgets/loaders/lazy_loading.dart';

class MyRequestsPage extends StatefulWidget {
  const MyRequestsPage({Key? key}) : super(key: key);

  @override
  State<MyRequestsPage> createState() => _MyRequestsPageState();
}

class _MyRequestsPageState extends State<MyRequestsPage> {
  AllRequestsProvider? _provider;
  SearchAllRequestsModel? _search;

  late List<String> requestsList;
  int selectedRequest = 0;

  @override
  Widget build(BuildContext context) {
    if (_provider == null) {
      requestsList = [
        context.translation.allWorkOrder,
        context.translation.correctiveMaintenance,
        context.translation.gasRefillRequest,
        context.translation.deviceTransferRequest,
        context.translation.preventiveMaintenance,
        context.translation.recurrentWo,
      ];
      _provider = Provider.of<AllRequestsProvider>(context, listen: false);
      _provider!.reset();
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _provider!.getAllRequests(context);
      });
    }

    return Scaffold(
        appBar: AppBar(
          automaticallyImplyLeading: false,
          titleSpacing: 0,
          title: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                height: 40,
                padding: const EdgeInsets.only(left: 16, right: 8),
                alignment: Alignment.center,
                decoration: ShapeDecoration(
                  color: context.isDark ? AppColor.neutral50 : AppColor.neutral30,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10),
                  ),
                ),
                child: Row(
                  children: [
                    Icon(Icons.search, color: context.isDark ? AppColor.neutral10 : AppColor.neutral20, size: 19),
                    8.width,
                    Text(
                      context.translation.search,
                      style: AppTextStyles.bodyText.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.neutral20),
                    ).expanded,
                  ],
                ),
              ).onPress(() async {
                final result = await Navigator.push(context, MaterialPageRoute(builder: (context) => AllRequestsSearchPage(data: _search)));
                if (result != null) {
                  _search = result;
                  setState(() {});
                }
              }).expanded,
              16.width,
              Text(
                context.translation.filter,
                style: AppTextStyles.bodyText2.copyWith(color: AppColor.blueStatus(context)),
              ).onPress(() async {
                final result = await Navigator.push(context, MaterialPageRoute(builder: (context) => AllRequestsFilterPage(data: _search)));
                if (result != null) {
                  _search = result;
                  setState(() {});
                }
              }),
            ],
          ).paddingOnly(start: 16, end: 16),
        ),
        body: Consumer<AllRequestsProvider>(builder: (context, snapshot, _) {
          return Column(
            children: [
              if (_filterIsEmpty())
                SizedBox(
                  height: 50.toScreenHeight,
                  child: ListView.separated(
                      scrollDirection: Axis.horizontal,
                      padding: const EdgeInsets.only(top: 16, right: 16, left: 16),
                      itemBuilder: (cxt, index) => Container(
                            alignment: Alignment.center,
                            padding: const EdgeInsets.symmetric(horizontal: 8),
                            foregroundDecoration: selectedRequest != index
                                ? null
                                : ShapeDecoration(
                                    color: (context.isDark ? AppColor.neutral30 : AppColor.neutral50).withOpacity(0.1),
                                    shape: RoundedRectangleBorder(
                                      side: BorderSide(width: 1, color: AppColor.blueStatus(context)),
                                      borderRadius: BorderRadius.circular(7),
                                    ),
                                  ),
                            decoration: ShapeDecoration(
                              color: selectedRequest == index ? AppColor.selectedButtonColor(context) : AppColor.unSelectedButtonColor(context).withOpacity(snapshot.isAllLoading ? 0.7 : 1),
                              shape: RoundedRectangleBorder(
                                side: selectedRequest == index ? BorderSide(width: 1, color: AppColor.blueStatus(context)) : BorderSide.none,
                                borderRadius: BorderRadius.circular(7),
                              ),
                              shadows: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 14, offset: const Offset(0, 0), spreadRadius: 0)],
                            ),
                            child: Text(requestsList[index], style: AppTextStyles.bodyText2.copyWith(height: 1, color: AppColor.filterButtonTextColor(context))),
                          ).onPress(() {
                            if (snapshot.isAllLoading) {
                              return;
                            }

                            if (selectedRequest != index) {
                              setState(() {
                                selectedRequest = index;
                              });
                              _provider!.reset();
                              _provider!.getAllRequests(context, typeTransaction: selectedRequest == 0 ? null : selectedRequest);
                            }
                          }),
                      separatorBuilder: (cxt, index) => 8.width,
                      itemCount: requestsList.length),
                ),
              LazyLoading(
                nextPage: snapshot.nextPage,
                onLazyLoad: () async {
                  snapshot.getAllRequests(context, typeTransaction: selectedRequest == 0 ? null : selectedRequest, search: _search);
                },
                child: RequestItemViewList(snapshot.allRequestsAndCount?.requestsDetails ?? [], snapshot.isAllLoading),
              ).expanded,
            ],
          );
        }));
  }

  bool _filterIsEmpty() {
    if (_search == null) return true;
    if ((_search!.requestNumber?.value?.isNotEmpty ?? false) ||
        (_search!.assetNo?.value?.isNotEmpty ?? false) ||
        (_search!.assetName?.value?.isNotEmpty ?? false) ||
        (_search!.manufacture?.value?.isNotEmpty ?? false) ||
        (_search!.sn?.value?.isNotEmpty ?? false) ||
        (_search!.statuses?.isNotEmpty ?? false) ||
        (_search!.startDate != null) ||
        (_search!.endDate != null)) {
      return false;
    }
    return true;
  }
}
