import 'package:flutter/material.dart';
import 'package:qhd_prevention/http/ApiService.dart';
import 'package:qhd_prevention/pages/home/NFC/home_nfc_add_page.dart';
import 'package:qhd_prevention/pages/home/NFC/home_nfc_detail_page.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/tools/tools.dart';

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

  @override
  State<HomeNfcListPage> createState() => _HomeNfcListPageState();
}

class _HomeNfcListPageState extends State<HomeNfcListPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;

  // 数据源（真实数据）
  final List<Map<String, dynamic>> _pendingList = [];
  final List<Map<String, dynamic>> _recordList = [];

  // 分页状态 - 待巡检
  int _pendingPage = 1;
  final int _pageSize = 20;
  bool _pendingLoading = false;
  bool _pendingHasMore = true;
  final ScrollController _pendingScrollController = ScrollController();

  // 分页状态 - 巡检记录
  int _recordPage = 1;
  bool _recordLoading = false;
  bool _recordHasMore = true;
  final ScrollController _recordScrollController = ScrollController();

  // 页面 loading（用于首次加载指示）
  bool _initialLoadingPending = false;
  bool _initialLoadingRecord = false;

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

    // Tab 切换时触发加载（如果对应列表为空）
    _tabController.addListener(() {
      if (!_tabController.indexIsChanging) {
        final idx = _tabController.index;
        if (idx == 0 && _pendingList.isEmpty) {
          _refreshPending();
        } else if (idx == 1 && _recordList.isEmpty) {
          _refreshRecord();
        }
      }
    });

    // 滚动监听，上拉触底加载更多
    _pendingScrollController.addListener(() {
      if (_pendingScrollController.position.pixels >=
              _pendingScrollController.position.maxScrollExtent - 80 &&
          !_pendingLoading &&
          _pendingHasMore) {
        _loadMorePending();
      }
    });

    _recordScrollController.addListener(() {
      if (_recordScrollController.position.pixels >=
              _recordScrollController.position.maxScrollExtent - 80 &&
          !_recordLoading &&
          _recordHasMore) {
        _loadMoreRecord();
      }
    });

    // 首次默认加载待巡检列表
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _refreshPending();
    });
  }

  @override
  void dispose() {
    _tabController.dispose();
    _pendingScrollController.dispose();
    _recordScrollController.dispose();
    super.dispose();
  }

  String _checkStatusName(String status) {
    if (status == '0') {
      return '已巡检';
    } else if (status == '1') {
      return '超期未巡检';
    } else if (status == '2') {
      return '巡检中';
    } else {
      return '待巡检';
    }
  }

  Future<void> _refreshPending() async {
    setState(() {
      _pendingPage = 1;
      _pendingHasMore = true;
      _initialLoadingPending = true;
    });
    try {
      await _getTaskList(page: 1, replace: true);
    } finally {
      if (mounted) {
        setState(() {
          _initialLoadingPending = false;
        });
      }
    }
  }

  Future<void> _loadMorePending() async {
    if (_pendingLoading || !_pendingHasMore) return;
    await _getTaskList(page: _pendingPage + 1, replace: false);
  }

  Future<void> _refreshRecord() async {
    setState(() {
      _recordPage = 1;
      _recordHasMore = true;
      _initialLoadingRecord = true;
    });
    try {
      await _getTaskDetailList(page: 1, replace: true);
    } finally {
      if (mounted) {
        setState(() {
          _initialLoadingRecord = false;
        });
      }
    }
  }

  Future<void> _loadMoreRecord() async {
    if (_recordLoading || !_recordHasMore) return;
    await _getTaskDetailList(page: _recordPage + 1, replace: false);
  }

  //NFC任务列表
  Future<void> _getTaskList({required int page, required bool replace}) async {
    setState(() {
      _pendingLoading = true;
    });
    try {
      final res = await ApiService.nfcTaskList(_pageSize, page);
      // // 适配后端返回：尝试找到数组数据
      // List<dynamic>? list;
      if (res['result'] == 'success') {
        List<dynamic> list = res['varList'];

        final parsed =
            list.map<Map<String, dynamic>>((e) {
              return e;
            }).toList();

        //
        // 判断是否还有更多：如果返回数量 < pageSize 则没有更多
        final bool gotLessThanPage = parsed.length < _pageSize;

        if (replace) {
          setState(() {
            _pendingList.clear();
            _pendingList.addAll(parsed);
            _pendingPage = 1;
            _pendingHasMore = !gotLessThanPage;
          });
        } else {
          setState(() {
            _pendingList.addAll(parsed);
            _pendingPage = page;
            if (parsed.isEmpty)
              _pendingHasMore = false;
            else if (parsed.length < _pageSize)
              _pendingHasMore = false;
          });
        }
      }
    } catch (e) {
      // 错误处理
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('获取待巡检列表失败：$e')));
      }
    } finally {
      if (mounted) {
        setState(() {
          _pendingLoading = false;
        });
      }
    }
  }

  Future<void> _getTaskDetailList({
    required int page,
    required bool replace,
  }) async {
    setState(() {
      _recordLoading = true;
    });
    try {
      final res = await ApiService.nfcInspectionRecord(_pageSize, page);
      // // 适配后端返回：尝试找到数组数据
      // List<dynamic>? list;
      if (res['result'] == 'success') {
        List<dynamic> list = res['varList'];

        final parsed =
            list.map<Map<String, dynamic>>((e) {
              return e;
            }).toList();

        //
        // 判断是否还有更多：如果返回数量 < pageSize 则没有更多
        final bool gotLessThanPage = parsed.length < _pageSize;

        if (replace) {
          setState(() {
            _recordList.clear();
            _recordList.addAll(parsed);
            _recordPage = 1;
            _recordHasMore = !gotLessThanPage;
          });
        } else {
          setState(() {
            _recordList.addAll(parsed);
            _recordPage = page;
            if (parsed.isEmpty)
              _recordHasMore = false;
            else if (parsed.length < _pageSize)
              _recordHasMore = false;
          });
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('获取巡检记录失败：$e')));
      }
    } finally {
      if (mounted) {
        setState(() {
          _recordLoading = false;
        });
      }
    }
  }

  // ---------- UI ----------

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppbar(
        title: '巡检列表',
        actions: [
          TextButton(
            onPressed: () {
               pushPage(const HomeNfcAddPage(), context);
            },
            child: const Text(
              "NFC绑定",
              style: TextStyle(color: Colors.white, fontSize: 16),
            ),
          ),
        ],
      ),
      body: SafeArea(
        child: Column(
          children: [
            // Tab bar
            TabBar(
              controller: _tabController,
              labelStyle: const TextStyle(fontSize: 16),
              indicator: const UnderlineTabIndicator(
                borderSide: BorderSide(width: 3.0, color: Colors.blue),
                insets: EdgeInsets.symmetric(horizontal: 50.0),
              ),
              labelColor: Colors.blue,
              unselectedLabelColor: Colors.grey,
              tabs: const [Tab(text: '待巡检'), Tab(text: '巡检记录')],
            ),
            const SizedBox(height: 8),
            // Tab 内容
            Expanded(
              child: TabBarView(
                controller: _tabController,
                children: [
                  // 待巡检 - 支持下拉刷新和上拉加载
                  _buildPendingList(),
                  // 巡检记录 - 支持下拉刷新和上拉加载
                  _buildRecordList(),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildPendingList() {
    if (_initialLoadingPending && _pendingList.isEmpty) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_pendingList.isEmpty) {
      return NoDataWidget.show(); // 你的无数据控件
    }

    return RefreshIndicator(
      onRefresh: _refreshPending,
      child: ListView.builder(
        controller: _pendingScrollController,
        itemCount: _pendingList.length + 1, // 最后一项作为加载更多指示
        padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 0),
        itemBuilder: (context, index) {
          if (index == _pendingList.length) {
            // 底部加载更多区域
            if (_pendingHasMore) {
              return const Padding(
                padding: EdgeInsets.symmetric(vertical: 12),
                child: Center(child: CircularProgressIndicator()),
              );
            } else {
              return const Padding(
                padding: EdgeInsets.symmetric(vertical: 12),
                child: Center(child: Text('没有更多数据')),
              );
            }
          }
          final item = _pendingList[index];
          return Container(
            margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            child: GestureDetector(
              onTap: () {
                pushPage(HomeNfcDetailPage(info: item, isEdit: true,), context);
              },
              child: _pendingCard(item, false),
            ),
          );
        },
      ),
    );
  }

  Widget _buildRecordList() {
    if (_initialLoadingRecord && _recordList.isEmpty) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_recordList.isEmpty) {
      return NoDataWidget.show();
    }

    return RefreshIndicator(
      onRefresh: _refreshRecord,
      child: ListView.builder(
        controller: _recordScrollController,
        itemCount: _recordList.length + 1,
        padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 0),
        itemBuilder: (context, index) {
          if (index == _recordList.length) {
            if (_recordHasMore) {
              return const Padding(
                padding: EdgeInsets.symmetric(vertical: 12),
                child: Center(child: CircularProgressIndicator()),
              );
            } else {
              return const Padding(
                padding: EdgeInsets.symmetric(vertical: 12),
                child: Center(child: Text('没有更多数据')),
              );
            }
          }
          final item = _recordList[index];
          return GestureDetector(
            onTap: () {
              pushPage(HomeNfcDetailPage(info: item, isEdit: false,), context);
            },
            child: Container(
              margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 0),
              child: _pendingCard(item, true),
            ),
          );
        },
      ),
    );
  }

  /// 构建待巡检卡片
  Widget _pendingCard(Map<String, dynamic> item, bool isFinish) {
    String finishState = '';
    Color textColor = Colors.blue;
    if (isFinish) {
      if (item['PATROL_STATUS'] == '0') {
        finishState = '已巡检';
        textColor = Colors.blue;
      } else if (item['PATROL_STATUS'] == '1') {
        finishState = '超期未巡检';
        textColor = Colors.red;
      } else if (item['PATROL_STATUS'] == '2') {
        finishState = '巡检中';
        textColor = Colors.deepOrange;
      }
    } else {
      if (FormUtils.hasValue(item, 'INSPECTED_POINTS')) {
        final inspected = (item['INSPECTED_POINTS'] is int) ? item['INSPECTED_POINTS'] as int : int.tryParse('${item['INSPECTED_POINTS']}') ?? 0;
        finishState = inspected > 0 ? '巡检中' : '待巡检';
        textColor = inspected > 0 ? Colors.deepOrange : Colors.blue;
      }
    }

    return Container(
      margin: const EdgeInsets.symmetric(vertical: 0, horizontal: 0),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 用 Stack 只包含图片 + 标题/状态
          Stack(
            children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(10),
                child: Image.asset(
                  'assets/images/xj_top.png',
                  height: 70,
                  width: double.infinity,
                  fit: BoxFit.cover,
                ),
              ),
              Positioned(
                top: 12,
                left: 12,
                child: Text(
                  item['TASK_NAME'] ?? '',
                  style: const TextStyle(
                    color: Colors.black87,
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              Positioned(
                top: 12,
                right: 12,
                child: Container(
                  height: 30,
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
                  decoration: BoxDecoration(
                    color: Colors.white.withOpacity(0.5),
                    borderRadius: BorderRadius.circular(15),
                  ),
                  child: Center(
                    child: Text(
                      finishState,
                      style: TextStyle(color: textColor, fontSize: 14),
                    ),
                  ),
                ),
              ),
            ],
          ),

          // 使用 Transform 提上白色容器（视觉上覆盖图片底部）
          Transform.translate(
            offset: const Offset(0, -20),
            child: Container(
              width: double.infinity,
              padding: const EdgeInsets.fromLTRB(16, 12, 16, 12),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(10),
                boxShadow: const [
                  BoxShadow(color: Colors.black12, blurRadius: 4, offset: Offset(0, 1))
                ],
              ),
              child: _buildInfoGrid(item, isFinish),
            ),
          ),
        ],
      ),
    );
  }


  /// 构建信息网格
  Widget _buildInfoGrid(Map<String, dynamic> item, bool isFinish) {
    return Column(
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('负责部门：${item['DEPARTMENT_NAME'] ?? ''}'),
                  const SizedBox(height: 8),
                  Text('巡检类型：${item['PATROL_TYPE_NAME'] ?? ''}'),
                  const SizedBox(height: 8),
                  isFinish ? Text('巡检次数：${item['ACTUAL_PATROL_TIMES'] ?? '0'}') :
                  Text('已巡点位：${item['INSPECTED_POINTS'] ?? '0'}'),
                ],
              ),
            ),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Text('负责人：${item['USER_NAME'] ?? ''}'),
                  const SizedBox(height: 8),
                  Text('巡检周期：${item['PATROL_PERIOD_NAME'] ?? ''}'),

                ],
              ),
            ),
          ],
        ),
        if (isFinish)
        const SizedBox(height: 10,),
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(child: isFinish
                ? Text(
              '涉及管道区域：${item['PIPELINE_AREAS_NAMES'] ?? ''}',
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            )
                : const SizedBox(height: 0),)
          ],
        )
      ],
    );

  }
}
