import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../../../core/components/spaces.dart';
import '../bloc/history_order/history_order_bloc.dart';
import '../widgets/order_card.dart';

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

  @override
  State<HistoryOrderPage> createState() => _HistoryOrderPageState();
}

class _HistoryOrderPageState extends State<HistoryOrderPage> {
  late Timer timer;
  @override
  void initState() {
    timer = Timer.periodic(const Duration(seconds: 5), (timer) {
      context
          .read<HistoryOrderBloc>()
          .add(const HistoryOrderEvent.getHistoryOrder());
    });
    context
        .read<HistoryOrderBloc>()
        .add(const HistoryOrderEvent.getHistoryOrder());
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Pesanan'),
      ),
      body: BlocBuilder<HistoryOrderBloc, HistoryOrderState>(
        builder: (context, state) {
          switch (state.status) {
            case HistoryOrderStateStatus.initial:
              return const Center(
                child: Text('No Data'),
              );
            case HistoryOrderStateStatus.error:
              return Center(
                child: Text(state.errorMessage),
              );
            default:
              if (state.orders?.orders?.isEmpty ?? true) {
                return const Center(
                  child: Text('No Data'),
                );
              }
              return ListView.separated(
                padding: const EdgeInsets.all(16.0),
                separatorBuilder: (context, index) => const SpaceHeight(16.0),
                itemCount: state.orders?.orders?.length ?? 0,
                itemBuilder: (context, index) => OrderCard(
                  data: state.orders!.orders![index],
                ),
              );
          }

          // return ListView.separated(
          //   padding: const EdgeInsets.all(16.0),
          //   separatorBuilder: (context, index) => const SpaceHeight(16.0),
          //   itemCount: transactions.length,
          //   itemBuilder: (context, index) => OrderCard(
          //     data: transactions[index],
          //   ),
          // );
        },
      ),
    );
  }
}
