// Copyright (C) 2022 WYATT GROUP
// Please see the AUTHORS file for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

import 'dart:math';

import 'package:crud_bloc_example/models.dart';
import 'package:crud_bloc_example/user_cubit.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wyatt_crud_bloc/wyatt_crud_bloc.dart';

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    final CrudDataSource<User> userLocalDataSource =
        CrudInMemoryDataSourceImpl<User>(toMap: (user) => user.toMap());

    final CrudRepository<User> userRepository =
        CrudRepositoryImpl(crudDataSource: userLocalDataSource);

    return RepositoryProvider<CrudRepository<User>>.value(
      value: userRepository,
      child: BlocProvider<UserCubit>(
        create: (context) => UserCubit(userRepository)..getAll(),
        child: MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: const MyHomePage(),
        ),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter Demo Home Page'),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            const SizedBox(height: 20),
            const Text("Data:"),
            BlocBuilder<UserCubit, CrudState>(
              builder: (context, state) {
                return CrudBuilder.typed<CrudListLoaded<User?>>(
                  state: state,
                  builder: ((context, state) {
                    return ListView.builder(
                      shrinkWrap: true,
                      itemCount: state.data.length,
                      itemBuilder: (context, index) {
                        final user = state.data.elementAt(index);
                        return ListTile(
                          title: Text(user?.name ?? 'Error'),
                          subtitle: Text(user?.id ?? 'Error'),
                          onTap: () {
                            context.read<UserCubit>().delete(
                                  (user?.id)!,
                                );
                          },
                        );
                      },
                    );
                  }),
                  initialBuilder: (context, state) => const Text("Loading..."),
                  loadingBuilder: (context, state) => const Text("Loading..."),
                  errorBuilder: (context, state) => Text("Error: $state"),
                );
              },
            ),

            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                final r = Random().nextInt(1000);
                context.read<UserCubit>().create(
                      User(
                          id: '$r',
                          name: 'Wyatt $r',
                          email: '$r@wyattapp.io',
                          phone: '06$r'),
                    );
              },
              child: const Text("Create"),
            ),
            ElevatedButton(
              onPressed: () {
                context.read<UserCubit>().deleteAll();
              },
              child: const Text("DeleteAll"),
            ),
            ElevatedButton(
              onPressed: () {
                context.read<UserCubit>().getAll();
              },
              child: const Text("GetAll"),
            ),
            ElevatedButton(
              onPressed: () {
                context
                    .read<UserCubit>()
                    .query([LimitQuery(2)]);
              },
              child: const Text("Query"),
            ),
            const SizedBox(height: 20),
          ],
        ),
      ),
    );
  }
}
