import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:gymlink_module_web/components/app_bar.dart';
import 'package:gymlink_module_web/components/heading.dart';
import 'package:gymlink_module_web/components/history_item_card.dart';
import 'package:gymlink_module_web/interfaces/items.dart';
import 'package:gymlink_module_web/tools/history.dart';
import 'package:gymlink_module_web/tools/relative.dart';
import 'package:lazy_load_scrollview/lazy_load_scrollview.dart';

List<Map<String, String>> orders = [
  {"image": "product.png", "price": "120", "id": "66", "date": "11.09.2001"},
  {
    "image": "product.png",
    "price": "150",
    "id": "56",
    "date": "11.09.2001",
  },
  {
    "image": "product.png",
    "price": "250",
    "id": "98",
    "date": "11.09.2001",
  },
  {
    "image": "product.png",
    "price": "300",
    "id": "50",
    "date": "11.09.2001",
  },
  {
    "image": "product.png",
    "price": "100",
    "id": "30",
    "date": "11.09.2001",
  }
];

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

  @override
  State<HistoryPage> createState() => _HistoryPageState();
}

class _HistoryPageState extends State<HistoryPage> {
  List<GymHistoryItem> my_orders = [];
  late Timer _updateTimer;
  bool _isLoading = true;
  bool _isRefreshing = false;

  @override
  void initState() {
    super.initState();
    ordersRefresh();
  }

  void ordersRefresh() {
    _updateTimer = Timer.periodic(const Duration(minutes: 1), _onRefresh);
    Future.microtask(() => _onRefresh(_updateTimer));
  }

  void _onLoad() async {
    await Future.delayed(const Duration(milliseconds: 1000));
  }

  @override
  void dispose() {
    _updateTimer.cancel();
    super.dispose();
  }

  Future<void> _onRefresh(Timer timer) async {
    await Future.delayed(const Duration(milliseconds: 1000));
    var orders = await getHistory();
    setState(() {
      my_orders = orders;
      _isLoading = false;
      _isRefreshing = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: const GymLinkAppBar(),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          const GymLinkHeader(
            title: 'История заказов',
            toMain: true,
          ),
          const SizedBox(height: 5),
          kIsWeb && !_isLoading
              ? Center(
                  child: ElevatedButton(
                    onPressed: () {
                      setState(() => _isRefreshing = true);
                      _onRefresh(_updateTimer);
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Theme.of(context).primaryColor,
                      shape: const RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(Radius.circular(50)),
                      ),
                      foregroundColor: Colors.white,
                      fixedSize: const Size(180, 40),
                    ),
                    child: const Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text('Обновить'),
                        Spacer(),
                        Icon(Icons.refresh),
                        Spacer()
                      ],
                    ),
                  ),
                )
              : const SizedBox.shrink(),
          const SizedBox(height: 5),
          _isRefreshing
              ? const Center(child: CircularProgressIndicator())
              : const SizedBox.shrink(),
          const SizedBox(height: 5),
          _isLoading
              ? const Expanded(
                  child: Center(child: CircularProgressIndicator()))
              : Expanded(
                  child: Row(
                    children: [
                      Expanded(
                        child: LazyLoadScrollView(
                          onEndOfPage: _onLoad,
                          scrollOffset: 200,
                          child: RefreshIndicator(
                            edgeOffset: 55,
                            onRefresh: () => _onRefresh(_updateTimer),
                            child: my_orders.isEmpty
                                ? const Center(child: Text('Нет заказов'))
                                : Stack(
                                    children: [
                                      ListView.builder(
                                        itemCount: my_orders.length,
                                        itemBuilder: (context, index) {
                                          final item = my_orders[index];
                                          return HistoryItemCard(
                                            id: item.id,
                                            cost: item.sum,
                                            date: item.date,
                                            image: FutureBuilder(
                                              future: precacheImage(
                                                  NetworkImage(item.photo),
                                                  context),
                                              builder: (context, snapshot) {
                                                if (snapshot.connectionState ==
                                                    ConnectionState.done) {
                                                  return Image(
                                                    image: NetworkImage(
                                                        item.photo),
                                                    width: 50,
                                                  );
                                                } else {
                                                  return const CircularProgressIndicator();
                                                }
                                              },
                                            ),
                                          );
                                        },
                                      ),
                                    ],
                                  ),
                          ),
                        ),
                      ),
                      my_orders.isEmpty
                          ? const SizedBox.shrink()
                          : getSpacer(context: context)
                    ],
                  ),
                ),
        ],
      ),
    );
  }
}
