import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'package:qhd_prevention/http/ApiService.dart';
import 'package:qhd_prevention/pages/home/EquipmentInspection/immediately_inspection.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/tools/tools.dart';

import 'equiment_detail_list_page.dart';

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

  @override
  State<EquipmentInspectionListPage> createState() =>
      _EquipmentInspectionListPageState();
}

class _EquipmentInspectionListPageState
    extends State<EquipmentInspectionListPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  int _currentTabIndex = 0;
  List<EquipItem> _equipList = [];
  List<String> _periodList = ['每日', '每周', '每旬', '每月'];
  int _currentPage = 1;
  int _totalPage = 0;
  bool _isLoading = false;
  bool _noMoreData = false;
  ScrollController _scrollController = ScrollController();

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

    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _loadMoreData();
      }
    });

    _fetchData();
  }

  void _handleTabSelection() {
    if (_tabController.indexIsChanging) {
      setState(() {
        _currentTabIndex = _tabController.index;
        _resetPageData();
        _fetchData();
      });
    }
  }

  void _resetPageData() {
    setState(() {
      _currentPage = 1;
      _equipList.clear();
      _noMoreData = false;
    });
  }

  Future<void> _fetchData() async {
    if (_isLoading) return;

    setState(() {
      _isLoading = true;
    });

    try {
      await Future.delayed(Duration(seconds: 1));

      final result = await ApiService.getEquipmentInspectionList(
        _currentPage,
        _currentTabIndex,
      );
      if (result['result'] == 'success') {
        // final List<dynamic> newItems = result['varList'] ?? [];
        // final data = json.decode(response.body);
        final newItems =
            (result['varList'] as List)
                .map((item) => EquipItem.fromJson(item))
                .toList();

        setState(() {
          _equipList.addAll(newItems);
          _totalPage = result['page']['totalPage'];
          _noMoreData = _currentPage >= _totalPage;
          _currentPage++;
        });
      }
    } catch (e) {
      print('Error fetching data: $e');
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  void _loadMoreData() {
    if (_isLoading || _noMoreData) return;
    _fetchData();
  }

  Future<void> _goToAdd(EquipItem item) async {
    // Navigator.push(
    //   context,
    //   MaterialPageRoute(
    //     builder: (context) => InspectionAddPage(equipmentId: item.id),
    //   ),
    // );
     await Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => ImmediatelyInspection(item.id)),
    );
     _resetPageData();
     _fetchData();
    // pushPage(ImmediatelyInspection(item.id), context);
  }

  void _goToRecordList(EquipItem item) {
    // Navigator.push(
    //   context,
    //   MaterialPageRoute(
    //     builder: (context) => InspectionRecordPage(equipmentId: item.id),
    //   ),
    // );
    pushPage(EquimentDetailListPage(item.id), context);

  }

  String _handleIsChecked(EquipItem item) {
    final now = DateTime.now();
    final nextInspection = DateFormat(
      'yyyy-MM-dd hh:mm',
    ).parse(item.periodStartDate);

    if (nextInspection.isAfter(now)) {
      return "已检查";
    } else {
      return "未检查";
    }
  }

  Widget _buildFirstTab() {
    // 按周期分组
    Map<String, List<EquipItem>> groupedItems = {};
    for (var period in _periodList) {
      groupedItems[period] =
          _equipList.where((item) => item.periodName == period).toList();
    }

    return ListView.builder(
      controller: _scrollController,
      itemCount: _equipList.length,
      itemBuilder: (context, index) {
        final period = _periodList[index];
        final items = groupedItems[period] ?? [];

        return Container(
          color: Colors.white,
          child: ExpansionTile(
            title: Text(
              period,
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
            ),
            children: items.map((item) => _buildEquipItem(item)).toList(),
          ),
        );
      },
    );
  }

  Widget _buildSecondTab() {
    return ListView.builder(
      controller: _scrollController,
      itemCount: _equipList.length + 1,
      itemBuilder: (context, index) {
        if (index == _equipList.length) {
          return _buildLoader();
        }
        return _equipList.isNotEmpty
            ? _buildEquipItem(_equipList[index])
            : null;
      },
    );
  }

  Widget _buildEquipItem(EquipItem item) {
    return Card(
      color: Colors.white,
      margin: EdgeInsets.all(8),
      child: Padding(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '设备名称：${item.equipmentName}',
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 8),
            Text(
              '设备类型：${item.equipmentTypeName}',
              style: TextStyle(color: Colors.grey[600]),
            ),
            SizedBox(height: 8),
            Text(
              '巡检周期：${item.periodName}',
              style: TextStyle(color: Colors.grey[600]),
            ),
            SizedBox(height: 12),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                if (_currentTabIndex == 0)
                  Text(
                    _handleIsChecked(item),
                    style: TextStyle(color: Colors.orange),
                  )
                else
                  Text('巡检次数: ${item.inspectionCount}'),
                ElevatedButton(
                  onPressed:
                      () =>
                          _currentTabIndex == 0
                              ? _goToAdd(item)
                              : _goToRecordList(item),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.orange,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(20),
                    ),
                  ),
                  child: Text(
                    _currentTabIndex == 0 ? '立即巡检' : '巡检记录',
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildLoader() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 16),
      alignment: Alignment.center,
      child:
          _isLoading
              ? CircularProgressIndicator()
              : Text(
                _noMoreData ? '--已经没有更多了--' : '',
                style: TextStyle(color: Colors.grey),
              ),
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset('assets/images/null.png', width: 200, height: 200),
          SizedBox(height: 16),
          Text('暂无数据', style: TextStyle(fontSize: 18, color: Colors.grey)),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppbar(title: "我的任务"),

      body: Column(
        children: [
          // 将 TabBar 放在 body 顶部
          Container(
            color: Colors.white, // 白色背景
            child: TabBar(
              controller: _tabController,
              labelStyle: TextStyle(fontSize: 16),
              indicator: UnderlineTabIndicator(
                borderSide: BorderSide(width: 3.0, color: Colors.blue),
                insets: EdgeInsets.symmetric(horizontal: 100.0),
              ),
              labelColor: Colors.blue,
              unselectedLabelColor: Colors.grey,
              tabs: const [Tab(text: '开始巡检'), Tab(text: '巡检记录')],
            ),
          ),

          // 内容区域（可滚动）
          Expanded(
            child: TabBarView(
              controller: _tabController,
              children: [
                // 第一个选项卡
                _equipList.isEmpty ? _buildEmptyState() : _buildFirstTab(),

                // 第二个选项卡
                _equipList.isEmpty ? _buildEmptyState() : _buildSecondTab(),
              ],
            ),
          ),
        ],
      ),
    );
  }

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

class EquipItem {
  final String id;
  final String equipmentName;
  final String equipmentTypeName;
  final String periodName;
  final String periodStartDate;
  final int inspectionCount;

  EquipItem({
    required this.id,
    required this.equipmentName,
    required this.equipmentTypeName,
    required this.periodName,
    required this.periodStartDate,
    required this.inspectionCount,
  });

  factory EquipItem.fromJson(Map<String, dynamic> json) {
    return EquipItem(
      id: json['SPECIALEQUIPMENT_ID'] ?? '',
      equipmentName: json['EQUIPMENTNAME'] ?? '',
      equipmentTypeName: json['EQUIPMENTTYPENAME'] ?? '',
      periodName: json['PERIOD_NAME'] ?? '',
      periodStartDate: json['PERIOD_START_DATE'] ?? '',
      inspectionCount: json['XJCOUNT'] ?? 0,
    );
  }
}




