import 'package:flutter/material.dart';
import 'package:food_health/api/dto/food_scan_dto.dart';
import 'package:food_health/api/endpoints/food_api.dart';

import 'widget/record_list_card.dart';

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

  @override
  State<RecordListPage> createState() => _RecordListPageState();
}

class _RecordListPageState extends State<RecordListPage> with TickerProviderStateMixin {
  bool _loading = true;

  //tab
  late TabController _tabController;
  final tabs = ["All", "Safe", "Warning", "Danger"];

  //列表数据
  List<FoodScanDto> _record = [];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: tabs.length, vsync: this);
    _loadData();
  }

  Future<void> _loadData() async {
    setState(() {
      _loading = true;
    });
    var res = await foodScanListApi();
    setState(() {
      _record = res;
      _loading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Food Check History"),
        bottom: TabBar(
          controller: _tabController,
          dividerColor: Colors.transparent,
          tabs: tabs.map((item) {
            return Tab(text: item);
          }).toList(),
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: tabs.asMap().entries.map((entry) {
          var index = entry.key;
          var filterList = _record.where((item) {
            if (index == 0) return true;
            return item.foodType == index;
          }).toList();

          return RefreshIndicator(
            onRefresh: () => _loadData(),
            child: RecordListCard(
              loading: _loading,
              records: filterList,
              onRefresh: () {
                _loadData();
              },
            ),
          );
        }).toList(),
      ),
    );
  }
}
