import 'package:flutter/material.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'package:qhd_prevention/pages/home/SafeCheck/CheckPersonSign/safecheck_sign_detail.dart';
import 'package:qhd_prevention/pages/home/SafeCheck/CheckPersonSure/check_person_detail.dart';
import 'package:qhd_prevention/pages/home/SafeCheck/DangeCheck/safeCheck_assignment_list.dart';
import 'package:qhd_prevention/pages/home/SafeCheck/DangeCheck/safecheck_danger_detail.dart';
import 'package:qhd_prevention/pages/home/SafeCheck/Record/defend_record_detail_page.dart';
import 'package:qhd_prevention/pages/home/SafeCheck/Start/safeCheck_start_detail.dart';
import 'package:qhd_prevention/pages/home/tap/tabList/special_wrok/dh_work/dh_work_detai/hotwork_apply_detail.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/tools/tools.dart';
import 'package:qhd_prevention/customWidget/bottom_picker.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 DefendRecordListPage extends StatefulWidget {
  final String flow;

  const DefendRecordListPage({Key? key, required this.flow}) : super(key: key);

  @override
  _DefendRecordListPageState createState() => _DefendRecordListPageState();
}

class _DefendRecordListPageState extends State<DefendRecordListPage> {
  // Data and state variables
  List<dynamic> list = [];
  int currentPage = 1;
  int rows = 10;
  int totalPage = 1;
  bool isLoading = false;
  List stepList = [
    {'id': '', 'name': '请选择'},
    {'id': '0', 'name': '待检查人核实'},
    {'id': '1', 'name': '检查人核实中'},
    {'id': '2', 'name': '待被检查人确认'},
    {'id': '3', 'name': '待指派'},
    {'id': '4', 'name': '指派中'},
    {'id': '5', 'name': '指派完成'},
    {'id': '6', 'name': '检查待验收'},
    {'id': '7', 'name': '检查已验收'},
    {'id': '8', 'name': '已归档'},
    {'id': '-1', 'name': '检查人核实打回'},
    {'id': '-2', 'name': '被检查人申辩'},
  ];
  final TextEditingController _searchController = TextEditingController();

  int sindex = 0;
  String searchKeywords = '';

  List<Map<String, dynamic>> flowList = [];
  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 = {
        'INSPECTION_STATUS': sindex > 0 ? stepList[sindex]['id'] : '',
        'roleLevel': SessionService.instance.loginUser?['roleLevel'] ?? '',
        'supDeparIds': SessionService.instance.loginUser?['supDeparIds'] ?? '',
        'KEYWORDS': searchKeywords,
      };
      final url =
          '/app/safetyenvironmental/pleadList?showCount=-1&currentPage=$currentPage';
      final response = await ApiService.getSafeCheckSearchList(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 {
    await pushPage(
      DefendRecordDetailPage(
        INSPECTION_ID: item['INSPECTION_ID'] ?? '',
      ),
      context,
    );
    _fetchData();
  }

  Widget _buildFlowStepItem({
    required Map<String, dynamic> item,
    required bool isFirst,
    required bool isLast,
  }) {
    bool status = item['active'] == item['order'];
    // 依据状态设色
    final Color dotColor = status ? Colors.blue : Colors.grey;
    final Color textColor = status ? Colors.blue : Colors.black54;

    return ListTile(
      visualDensity: VisualDensity(vertical: -4),

      contentPadding: const EdgeInsets.symmetric(horizontal: 16),
      leading: Container(
        width: 24,
        alignment: Alignment.center,
        child: Column(
          mainAxisSize: MainAxisSize.max,
          children: [
            // 上方线段或占位
            isFirst
                ? SizedBox(height: 6 + 5)
                : Expanded(child: Container(width: 1, color: Colors.grey[300])),
            // 圆点
            CircleAvatar(radius: 6, backgroundColor: dotColor),
            // 下方线段或占位
            isLast
                ? SizedBox(height: 6 + 5)
                : Expanded(child: Container(width: 1, color: Colors.grey[300])),
          ],
        ),
      ),
      title: Text(
        item['title'] ?? '',
        style: TextStyle(color: textColor, fontSize: 15),
      ),
      subtitle: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (item['desc'] != null)
            Text(
              item['desc'],
              style: TextStyle(color: textColor, fontSize: 13),
            ),
        ],
      ),
    );
  }

  String _checkStatusWithId(String id) {
    for (Map item in stepList) {
      if (item['id'] == id) {
        return item['name'];
      }
    }
    return '';
  }

  Widget _buildListItem(Map<String, dynamic> item) {
    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(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    "安全检查记录",
                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    "检查状态: ${_checkStatusWithId(item['INSPECTION_STATUS'].toString())}",
                  ),
                  Text("检查类型: ${item['INSPECTION_TYPE_NAME'] ?? ''}"),
                ],
              ),
              const SizedBox(height: 8),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    "检查人: ${item['INSPECTION_USER_NAME'] ?? ''}",
                    maxLines: 5,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
              const SizedBox(height: 8),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    "检查发起人: ${item['INSPECTION_ORIGINATOR_NAME'] ?? ''}",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
              const SizedBox(height: 8),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text("被检查人: ${item['INSPECTED_SITEUSER_NAME'] ?? ''}"),
                ],
              ),
              const SizedBox(height: 8),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    "检查时间: ${item['INSPECTION_TIME_START'] ?? ''}至${item['INSPECTION_TIME_END'] ?? ''}",
                  ),
                ],
              ),
              const SizedBox(height: 8),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  SizedBox(),
                  CustomButton(
                    text: '申辩记录',
                    height: 32,
                    padding: EdgeInsets.symmetric(horizontal: 12),
                    margin: EdgeInsets.only(left: 0),
                    backgroundColor: Colors.blue,
                    onPressed: () => _goToDetail(item),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 显示底部选择器
  Future<void> _showStepPicker() async {
    if (stepList.isEmpty) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('正在加载步骤数据，请稍后...')));
      if (stepList.isEmpty) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('无法加载步骤数据')));
        return;
      }
    }

    // 创建选项列表
    final options = stepList.map((e) => e['name'] as String).toList();

    // 显示底部选择器
    final choice = await BottomPicker.show<String>(
      context,
      items: options,
      itemBuilder: (item) => Text(item, textAlign: TextAlign.center),
      initialIndex: sindex,
    );

    if (choice != null) {
      // 找到选择的索引
      final newIndex = options.indexOf(choice);
      if (newIndex != -1) {
        setState(() {
          sindex = newIndex;
        });
        _search();
      }
    }
  }

  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) {
    final int lastDoneIndex = flowList.lastIndexWhere((e) => e['STATUS'] == 1);

    return Scaffold(
      key: _scaffoldKey,
      appBar: MyAppbar(title: '${widget.flow}', actions: []),
      endDrawer: Drawer(
        child: SafeArea(
          child:
              flowList.isEmpty
                  ? Center(child: Text('暂无流程图数据'))
                  : ListView.builder(
                    padding: const EdgeInsets.symmetric(vertical: 16),
                    itemCount: flowList.length + 1, // +1 用来放标题
                    itemBuilder: (context, i) {
                      if (i == 0) {
                        return Padding(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 16,
                            vertical: 8,
                          ),
                          child: Text(
                            '查看流程图',
                            style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        );
                      }
                      final idx = i - 1;
                      final item = flowList[idx];
                      final bool isFirst = idx == 0;
                      final bool isLast = idx == flowList.length - 1;

                      return _buildFlowStepItem(
                        item: item,
                        isFirst: isFirst,
                        isLast: isLast,
                      );
                    },
                  ),
        ),
      ),

      body: SafeArea(
        child: Column(
          children: [
            // Filter bar
            Container(
              color: Colors.white,
              padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 8),
              child: Row(
                children: [
                  // 底部弹窗选择器
                  SizedBox(
                    width: 65,
                    child: TextButton(
                      onPressed: _showStepPicker,
                      style: TextButton.styleFrom(
                        padding: EdgeInsets.symmetric(
                          vertical: 12,
                          horizontal: 5,
                        ),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            '筛选',
                            style: TextStyle(
                              color: Colors.black87,
                              fontSize: 16,
                            ),
                          ),
                          Icon(Icons.arrow_drop_down, color: Colors.grey),
                        ],
                      ),
                    ),
                  ),
                  Expanded(
                    flex: 2,
                    child: SearchBarWidget(
                      showResetButton: false,
                      hintText: "请输入关键字",
                      // isClickableOnly: true,
                      onSearch: (text) {
                        _search();
                      },
                      controller: _searchController,
                    ),
                  ),
                ],
              ),
            ),
            const Divider(height: 1),
            // List
            Expanded(child: _buildListContent()),
          ],
        ),
      ),
    );
  }
}
