import 'package:flutter/material.dart';
import 'package:qhd_prevention/pages/KeyProjects/KeyProject/keyProject_detail.dart';
import 'package:qhd_prevention/pages/KeyProjects/SafeCheck/safeCheck_detail.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/tools/tools.dart';
import 'package:qhd_prevention/customWidget/custom_button.dart';
import 'package:qhd_prevention/customWidget/search_bar_widget.dart';
import 'package:qhd_prevention/http/ApiService.dart';

class CheckListPage extends StatefulWidget {
  const CheckListPage({super.key, required this.OUTSOURCED_ID});

  final String OUTSOURCED_ID;
  @override
  _CheckListPageState createState() => _CheckListPageState();
}

class _CheckListPageState extends State<CheckListPage> {
  // Data and state variables
  List<dynamic> list = [];
  int currentPage = 1;
  int rows = 10;
  int totalPage = 1;
  bool isLoading = false;
  final TextEditingController _searchController = TextEditingController();

  List<Map<String, dynamic>> stepList = [];
  int sindex = 0;
  String searchKeywords = '';

  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _fetchData();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  void _onScroll() {
    if (_scrollController.position.pixels >=
        _scrollController.position.maxScrollExtent &&
        !isLoading) {
      if (currentPage < totalPage) {
        currentPage++;
        _fetchData();
      }
    }
  }

  Future<void> _fetchData() async {
    if (isLoading) return;
    setState(() => isLoading = true);

    try {
      final data = {'KEYWORDS': searchKeywords, 'OUTSOURCED_ID':widget.OUTSOURCED_ID};
      final url =
          '/app/keyprojectcheck/list?showCount=10&currentPage=$currentPage';
      final response = await ApiService.getSafeCheckReciordList(data, url);

      setState(() {
        if (currentPage == 1) {
          list = response['varList'];
        } else {
          list.addAll(response['varList']);
        }
        Map<String, dynamic> page = response['page'];
        totalPage = page['totalPage'] ?? 1;
        isLoading = false;
      });
    } catch (e) {
      print('Error fetching data: $e');
      setState(() => isLoading = false);
    }
  }

  void _search() {
    searchKeywords = _searchController.text.trim();
    currentPage = 1;
    list.clear();
    _fetchData();
  }

  void _goToDetail(Map<String, dynamic> item) async {
    pushPage(SafecheckDetail(OUTSOURCED_ID: widget.OUTSOURCED_ID,KEYPROJECTCHECK_ID: item['KEYPROJECTCHECK_ID'], isEdit: false,), context);
  }

  Widget _buildListItem(Map<String, dynamic> item) {
    bool showBadge =
        (item['STATE'] == '-1' || item['STATE'] == '-2') &&
            (item['CREATOR'] != null &&
                item['CREATOR'].toString() == SessionService.instance.loginUserId);

    return Card(
      color: Colors.white,
      margin: const EdgeInsets.all(8.0),
      child: InkWell(
        onTap: () => _goToDetail(item),
        child: Padding(
          padding: const EdgeInsets.all(12.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 标题 + 红点
              Row(
                children: [
                  Expanded(
                    child: Text(
                      "${item['INSPECTION_PLACE'] ?? ''}",
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              Text(
                "检查状态：${item['INSPECTION_STATUS']}",
              ),
              Text(
                "检查类型：${item['INSPECTION_TYPE_NAME']}",
              ),
              Text(
                "检查人：${item['INSPECTION_USERS']}",
              ),
              Text(
                "被检查人：${item['PERSON_NAME']}",
              ),
              Text(
                "检查时间：${item['INSPECTION_TIME_START']}-${item['INSPECTION_TIME_END']}",
              ),
              Text(
                "检查隐患数：${item['HIDDEN_COUNT']}",
              ),

              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  SizedBox(),
                  CustomButton(
                    onPressed: () { _goToDetail(item);},
                    text: '查看',
                    height: 30,
                    padding: EdgeInsets.symmetric(vertical: 5, horizontal: 15),
                    textStyle: TextStyle(fontSize: 13, color: Colors.white),
                    backgroundColor: Colors.blue,
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildListContent() {
    if (isLoading && list.isEmpty) {
      // 初始加载时显示居中的加载指示器
      return Center(child: CircularProgressIndicator());
    } else if (list.isEmpty) {
      // 没有数据
      return NoDataWidget.show();
    } else {
      // 有数据或加载更多
      return ListView.builder(
        padding: EdgeInsets.zero,

        controller: _scrollController,
        itemCount: list.length + (isLoading ? 1 : 0),
        itemBuilder: (context, index) {
          if (index >= list.length) {
            // 加载更多时在列表底部显示加载指示器
            return Padding(
              padding: const EdgeInsets.symmetric(vertical: 16.0),
              child: Center(child: CircularProgressIndicator()),
            );
          }
          return _buildListItem(list[index]);
        },
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: MyAppbar(title: '安全检查记录', actions: [
        TextButton(onPressed: () {
          pushPage(SafecheckDetail(OUTSOURCED_ID: widget.OUTSOURCED_ID,KEYPROJECTCHECK_ID: '', isEdit: true,), context);
        }, child: Text('发起', style: TextStyle(color: Colors.white, fontSize: 16),))
      ],),
      
      body: SafeArea(child: Column(
        children: [
          // Filter bar
          Container(
            color: Colors.white,
            padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 8),
            child: Row(
              children: [
                Expanded(
                  flex: 2,
                  child: SearchBarWidget(
                    showResetButton: false,
                    hintText: "请输入关键字",
                    // isClickableOnly: true,
                    onSearch: (text) {
                      _search();
                    },
                    controller: _searchController,
                  ),
                ),
              ],
            ),
          ),
          const Divider(height: 1),
          // List
          Expanded(child: _buildListContent()),
        ],
      )),
    );
  }
}
