import 'dart:convert';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:gymlink_module_web/main_mobile.dart';
import 'package:gymlink_module_web/providers/main.dart';
import 'package:http/http.dart' as http;
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  runApp(const MyExampleApp());
}

Future<String> getToken(String token, String clientId) async {
  var url = Uri.https('gymlink.freemyip.com', 'api/auth/authorize_client');
  try {
    var response = await http.post(url,
        body: {'GymKey': token, 'id': clientId}); // Just testing token
    var decodedBody = jsonDecode(response.body) as Map;
    if (decodedBody['payload'] == null) {
      return '';
    }
    return decodedBody['payload']['token'];
  } catch (e) {
    return '';
  }
}

class MyExampleApp extends StatelessWidget {
  const MyExampleApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'GymLink Example App',
      debugShowCheckedModeBanner: false,
      home: const ExampleMainPage(),
      theme: ThemeData.light(useMaterial3: true),
    );
  }
}

class ExamplePage extends StatefulWidget {
  const ExamplePage({super.key});

  @override
  State<ExamplePage> createState() => _ExamplePageState();
}

Widget getDrawer(BuildContext context) => Drawer(
      child: Column(
        children: [
          const DrawerHeader(child: Text('Drawer Header')),
          ListTile(
            leading: const Icon(Icons.home),
            title: const Text('Home'),
            onTap: () => Navigator.of(context).push(
              MaterialPageRoute(
                builder: (context) => const ExampleMainPage(),
              ),
            ),
          ),
          ListTile(
            leading: const Icon(Icons.sell),
            title: const Text('Club 2'),
            onTap: () => Navigator.of(context).push(
              MaterialPageRoute(
                builder: (context) => ChangeNotifierProvider(
                  create: (_) => GymLinkProvider(),
                  child: Consumer<GymLinkProvider>(
                    builder: (_, value, __) => const ExampleClub2Page(),
                  ),
                ),
              ),
            ),
          ),
          ListTile(
            leading: const Icon(Icons.search),
            title: const Text('Example page'),
            onTap: () => Navigator.of(context).push(MaterialPageRoute(
              builder: (context) => const ExampleSecondPage(),
            )),
          ),
        ],
      ),
    );

class ExampleMainPage extends StatelessWidget {
  const ExampleMainPage({super.key});

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
        create: (_) => GymLinkProvider(),
        child: Consumer<GymLinkProvider>(
          builder: (_, value, __) => const ExamplePage(),
        ));
  }
}

class _ExamplePageState extends State<ExamplePage> {
  @override
  void initState() {
    super.initState();
    // Future.microtask(
    //     () => context.read<GymLinkProvider>().onTokenReceived('token123'));
    Future.microtask(() => context
        .read<GymLinkProvider>()
        .setTheme(ThemeData.light(useMaterial3: true)));

    Future.microtask(() => context.read<GymLinkProvider>().setOnError(() {
          const snackBar = SnackBar(
            content: Text('Ошибка подключения'),
            duration: Duration(seconds: 3), // Длительность отображения Snackbar
            behavior: SnackBarBehavior
                .fixed, // Поведение Snackbar (fixed или floating)
          );
          ScaffoldMessenger.of(context).showSnackBar(snackBar);
          Future.delayed(const Duration(seconds: 3))
              .then((value) => _setToken());
        }));

    Future.microtask(() async {
      await _setToken();
    });
  }

  Future<void> _setToken() async {
    final token = await getToken('eeb42dcb-8e5b-4f21-825a-3fc7ada43445', '123');
    if (token != '') {
      context.read<GymLinkProvider>().checkToken(token);
    } else {
      context.read<GymLinkProvider>().onError();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('GymLink Example App Gym 1'),
      ),
      resizeToAvoidBottomInset: false,
      drawer: getDrawer(context),
      body: const Column(
        children: [
          Text('test'),
          Expanded(
            child: MyApp(),
          ),
          SizedBox(
            height: 20,
          ),
          Text('Bottom text')
        ],
      ),
      floatingActionButton: IconButton(
        icon: const Icon(Icons.search),
        onPressed: () {
          context.read<GymLinkProvider>().changeTheme(
              Random().nextInt(0xffffff + 1),
              blackTheme: Random().nextBool());
        },
      ),
    );
  }
}

class ExampleClub2Page extends StatefulWidget {
  const ExampleClub2Page({super.key});

  @override
  State<ExampleClub2Page> createState() => _ExampleClub2PageState();
}

class _ExampleClub2PageState extends State<ExampleClub2Page> {
  @override
  void initState() {
    super.initState();
    // Future.microtask(
    //     () => context.read<GymLinkProvider>().onTokenReceived('token123'));
    Future.microtask(() => context
        .read<GymLinkProvider>()
        .setTheme(ThemeData.light(useMaterial3: true)));

    Future.microtask(() => context.read<GymLinkProvider>().setOnError(() {
          const snackBar = SnackBar(
            content: Text('Ошибка подключения'),
            duration: Duration(seconds: 3), // Длительность отображения Snackbar
            behavior: SnackBarBehavior
                .fixed, // Поведение Snackbar (fixed или floating)
          );
          ScaffoldMessenger.of(context).showSnackBar(snackBar);
          Future.delayed(const Duration(seconds: 3))
              .then((value) => _setToken());
        }));

    Future.microtask(() async {
      await _setToken();
    });
  }

  Future<void> _setToken() async {
    final token = await getToken('a8622a61-3142-487e-8db8-b6aebd4f04aa', '123');
    context.read<GymLinkProvider>().changeTheme(0xFFAABCAB);
    if (token != '') {
      context.read<GymLinkProvider>().checkToken(token);
    } else {
      context.read<GymLinkProvider>().onError();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('GymLink Example App Gym2'),
      ),
      resizeToAvoidBottomInset: false,
      drawer: getDrawer(context),
      body: const Column(
        children: [
          Text('test'),
          Expanded(
            child: MyApp(),
          ),
          SizedBox(
            height: 20,
          ),
          Text('Bottom text')
        ],
      ),
      floatingActionButton: IconButton(
        icon: const Icon(Icons.search),
        onPressed: () {
          // context.read<GymLinkProvider>().changeTheme(0xFFAABCAB);
        },
      ),
    );
  }
}

class ExampleSecondPage extends StatelessWidget {
  const ExampleSecondPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('GymLink Example App'),
      ),
      drawer: getDrawer(context),
      body: Center(
        child: TextButton(
            onPressed: () async {
              final prefs = await SharedPreferences.getInstance();
              prefs.remove('token');
              prefs.remove('history');
              prefs.remove('cart');
              prefs.remove('detail_history');
            },
            child: const Text('Clear')),
      ),
    );
  }
}
