import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/ppm_provider.dart';
import 'package:test_sa/controllers/providers/api/user_provider.dart';
import 'package:test_sa/controllers/providers/settings/setting_provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.dart';
import 'package:test_sa/views/widgets/loaders/loading_manager.dart';

import '../../../../models/ppm/ppm.dart';
import '../../../widgets/loaders/lazy_loading.dart';
import '../../../widgets/loaders/no_data_found.dart';
import '../../../widgets/ppm/ppm_item.dart';

class PpmPage extends StatefulWidget {
  static const String id = "/ppm_page";

  const PpmPage({Key? key}) : super(key: key);

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

class _PpmPageState extends State<PpmPage> with TickerProviderStateMixin {
  late PpmProvider _visitsProvider;
  late UserProvider _userProvider;
  late SettingProvider _settingProvider;

  @override
  Widget build(BuildContext context) {
    _visitsProvider = Provider.of<PpmProvider>(context);
    _settingProvider = Provider.of<SettingProvider>(context);
    _userProvider = Provider.of<UserProvider>(context);

    return Scaffold(
      appBar: DefaultAppBar(title: context.translation.preventiveMaintenance),
      body: SafeArea(
        child: LoadingManager(
          isLoading: _visitsProvider.isLoading,
          isFailedLoading: _visitsProvider.ppms == null,
          stateCode: _visitsProvider.stateCode,
          onRefresh: () async {
            _visitsProvider.reset();
            await _visitsProvider.getVisits(user: _userProvider.user!, host: _settingProvider.host!);
          },
          child: _visitsProvider.ppms?.isEmpty ?? true
              ? NoDataFound(message: context.translation.noVisitsFound)
              : LazyLoading(
                  nextPage: _visitsProvider.nextPage,
                  onLazyLoad: () async {
                    await _visitsProvider.getVisits(user: _userProvider.user!, host: _settingProvider.host!);
                  },
                  child: ListView.builder(
                    itemCount: _visitsProvider.ppms!.length,
                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                    itemBuilder: (context, itemIndex) {
                      Ppm ppm = _visitsProvider.ppms![itemIndex];
                      return Padding(padding: const EdgeInsets.only(bottom: 8.0), child: PpmItem(ppm: ppm));
                    },
                  ),
                ),
        ),
      ),
    );
  }
}
