import 'package:flutter/material.dart';
import 'package:qhdkfq_regulatory_flutter/home/home_page.dart';
import 'package:qhdkfq_regulatory_flutter/tools/custom_button.dart';
import 'package:qhdkfq_regulatory_flutter/tools/h_colors.dart';
import 'package:qhdkfq_regulatory_flutter/tools/my_appbar.dart';
import 'adaptive_list_item.dart';

class WorkListPage extends StatefulWidget {
  const WorkListPage({super.key, required this.type});

  final int selectTabIndex = 0;
  final HomeCategroyType type;

  @override
  State<WorkListPage> createState() => _WorkListPageState();
}

class _WorkListPageState extends State<WorkListPage> {
  final _searchController = TextEditingController();
  var _navTitle = "";

  /// 当前显示的企业数据（过滤后）
  List<Map<String, dynamic>> _displayData = [];

  /// 模拟企业数据
  final List<Map<String, dynamic>> _enterpriseData = List.generate(15, (index) {
    return {
      'id': index,
      'name': '${['化工', '制造', '能源', '食品', '建筑'][index % 5]}企业${index + 1}',
      'creditCode': '9137${10000 + index}',
      'industry': ['化工', '制造', '能源', '食品', '建筑'][index % 5],
      'scale': ['大型', '中型', '小型'][index % 3],
      'safetyLevel': ['A', 'B', 'C'][index % 3],
      'lastCheck': '2025-0${6 + index % 3}-${10 + index % 20}',
      'riskCount': index % 4,
      'hiddenDangerCount': index % 5,
      'isDivided': index % 3 == 0,
    };
  });

  @override
  void initState() {
    super.initState();
    _displayData = _enterpriseData; // 初始显示所有数据
    switch(widget.type) {
      case HomeCategroyType.enterpriseInfo:
        _navTitle = "持证人员信息列表";
      case HomeCategroyType.dualPrevention:
        // TODO: Handle this case.
        throw UnimplementedError();
      case HomeCategroyType.keySafety:
        _navTitle = "危险作业";
      case HomeCategroyType.supervisionSupport:
        // TODO: Handle this case.
        throw UnimplementedError();
      case HomeCategroyType.specialInspection:
        // TODO: Handle this case.
        throw UnimplementedError();
      case HomeCategroyType.disasterReduction:
        // TODO: Handle this case.
      case HomeCategroyType.supervisionRecord:
        throw UnimplementedError();
    }

  }

  @override
  /// 列表
  Widget _listViewWidget() {
    return ListView.builder(
      itemCount: _displayData.length,
      itemBuilder: (context, index) {
        final enterprise = _displayData[index];
        return Card(
          color: Colors.white,
          margin: const EdgeInsets.symmetric(horizontal: 0, vertical: 6),
          elevation: 0.5,
          shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
          child: Padding(
            padding: const EdgeInsets.all(15),
            child: AdaptiveListItem(
              title: enterprise['name'],
              items: _getEnterpriseProperties(enterprise),
              actions: _listItemButtons(),
              selectTabIndex: 0,
              type: widget.type,
            ),
          ),
        );
      },
    );
  }

  List<Widget> _listItemButtons() {
    List<Widget> buttons = [];
    if (widget.type == HomeCategroyType.supervisionSupport) {}
    return buttons;
  }

  /// 测试数据
  List<Map<String, String>> _getEnterpriseProperties(
    Map<String, dynamic> enterprise,
  ) {
    switch (widget.type) {
      case HomeCategroyType.enterpriseInfo:
        return [
          {"title": "统一信用代码", "value": enterprise['creditCode']},
          {"title": "所属行业", "value": enterprise['industry']},
          {"title": "企业规模", "value": enterprise['scale']},
          {"title": "安全等级", "value": enterprise['safetyLevel']},
          {"title": "最近检查", "value": enterprise['lastCheck']},
        ];
      case HomeCategroyType.dualPrevention:
        return [
          {"title": "风险点数量", "value": "${enterprise['riskCount']}个"},
          {"title": "隐患数量", "value": "${enterprise['hiddenDangerCount']}个"},
          {"title": "最近检查", "value": enterprise['lastCheck']},
          {"title": "安全等级", "value": enterprise['safetyLevel']},
        ];
      case HomeCategroyType.keySafety:
        return [
          {"title": "重点区域", "value": "生产车间${enterprise['id'] % 5 + 1}"},
          {
            "title": "责任人",
            "value": "张${['三', '四', '五', '六', '七'][enterprise['id'] % 5]}",
          },
          {"title": "上次检查", "value": enterprise['lastCheck']},
          {"title": "状态", "value": enterprise['riskCount'] > 2 ? "需整改" : "正常"},
        ];
      case HomeCategroyType.supervisionSupport:
        return [
          {
            "title": "帮扶类型",
            "value": ["技术指导", "安全培训", "设备支持"][enterprise['id'] % 3],
          },
          {
            "title": "负责人",
            "value": "王${['工', '主任', '经理'][enterprise['id'] % 3]}",
          },
          {"title": "开始日期", "value": "2025-06-${10 + enterprise['id'] % 20}"},
          {
            "title": "状态",
            "value": ["进行中", "已完成", "待开始"][enterprise['id'] % 3],
          },
        ];
      case HomeCategroyType.specialInspection:
        return [
          {
            "title": "检查类型",
            "value": ["常规", "突击", "专项"][enterprise['id'] % 3],
          },
          {
            "title": "检查结果",
            "value": ["合格", "需整改", "不合格"][enterprise['id'] % 3],
          },
          {"title": "检查日期", "value": enterprise['lastCheck']},
          {
            "title": "检查人",
            "value": "李${['工', '主任', '专员'][enterprise['id'] % 3]}",
          },
        ];
      case HomeCategroyType.disasterReduction:
        return [
          {"title": "防灾设施", "value": "${enterprise['id'] % 5 + 3}项"},
          {"title": "上次演练", "value": "2025-05-${20 + enterprise['id'] % 10}"},
          {
            "title": "应急预案",
            "value": ["已备案", "待更新", "完善中"][enterprise['id'] % 3],
          },
          {
            "title": "责任人",
            "value": "赵${['主管', '经理', '专员'][enterprise['id'] % 3]}",
          },
        ];
      default:
        return [
          {"title": "统一信用代码", "value": enterprise['creditCode']},
          {"title": "所属行业", "value": enterprise['industry']},
        ];
    }
  }

  /// radio显示
  Row _buildDynamicRadioRow({
    required List<String> options, // 选项文本数组
    required int? selectedValue, // 当前选中的值（索引）
    required ValueChanged<int?> onChanged, // 选项变更回调
  }) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        for (int i = 0; i < options.length; i++) ...[
          _buildRadioOption(
            isSelected: selectedValue == i,
            label: options[i],
            value: i, // 使用索引作为值
            onChanged: onChanged,
          ),
          if (i < options.length - 1) const SizedBox(width: 5), // 最后一个选项后不加间距
        ],
      ],
    );
  }

  /// 自定义Radio
  Widget _buildRadioOption({
    required bool isSelected,
    required String label,
    required int value,
    required ValueChanged<int?> onChanged,
  }) {
    return InkWell(
      onTap: () => onChanged(value),
      splashColor: Colors.blue,
      borderRadius: BorderRadius.circular(20),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 自定义单选按钮 - 带对勾样式
          SizedBox(
            child:
                isSelected
                    ? const Icon(
                      Icons.check_circle,
                      size: 20,
                      color: Colors.blue,
                    )
                    : const Icon(
                      Icons.circle_outlined,
                      size: 20,
                      color: Colors.grey,
                    ),
          ),
          SizedBox(width: 5),
          Text(
            label,
            style: TextStyle(
              fontSize: 12,
              color: isSelected ? Colors.blue : Colors.grey[700],
              fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
            ),
          ),
          SizedBox(width: 10),
        ],
      ),
    );
  }

  // 搜索框
  Widget _searchBar() {
    const double searchBarHeight = 40.0;
    const double borderRadius = searchBarHeight / 2;

    return Row(
      children: [
        Expanded(
          child: SizedBox(
            height: searchBarHeight,
            child: TextField(
              controller: _searchController,
              decoration: InputDecoration(
                filled: true,
                fillColor: const Color(0xFFF5F5F5),
                prefixIcon: const Icon(Icons.search_rounded, size: 20),
                hintText: "请输入关键字",
                hintStyle: const TextStyle(fontSize: 14),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(borderRadius),
                  borderSide: BorderSide.none,
                ),
                isDense: true,
                contentPadding: const EdgeInsets.symmetric(vertical: 0),
              ),
              onChanged: (val) {
                // 搜索过滤
                setState(() {
                  if (val.isEmpty) {
                    _displayData = _enterpriseData;
                  } else {
                    _displayData =
                        _enterpriseData.where((e) {
                          return e['name'].contains(val) ||
                              e['creditCode'].contains(val);
                        }).toList();
                  }
                });
              },
              onSubmitted: (val) {
                // 提交搜索
              },
            ),
          ),
        ),
        // const SizedBox(width: 10),
        SizedBox(
          height: searchBarHeight,
          child: TextButton(
            onPressed: () {
              // 搜索操作
              setState(() {
                if (_searchController.text.isEmpty) {
                  _displayData = _enterpriseData;
                } else {
                  _displayData =
                      _enterpriseData.where((e) {
                        return e['name'].contains(_searchController.text) ||
                            e['creditCode'].contains(_searchController.text);
                      }).toList();
                }
              });
            },
            style: TextButton.styleFrom(
              padding: const EdgeInsets.symmetric(horizontal: 10),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(borderRadius),
              ),
            ),
            child: const Text(
              "搜索",
              style: TextStyle(color: Colors.blue, fontSize: 14),
            ),
          ),
        ),
      ],
    );
  }

  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: h_backGroundColor(),
      appBar: MyAppbar(title: _navTitle),
      body: SafeArea(
        child: Column(
          children: [
            const SizedBox(height: 5),
            Container(
              padding: const EdgeInsets.all(10),
              color: Colors.white,
              child: Column(spacing: 10, children: [_searchBar()]),
            ),
            const SizedBox(height: 5),
            Expanded(child: _listViewWidget()),
          ],
        ),
      ),
    );
  }
}
