import 'package:flutter/material.dart';
import 'package:qhdkfq_regulatory_flutter/home/action/action_task_page.dart';
import 'package:qhdkfq_regulatory_flutter/home/help/danger_detail_page.dart';
import 'package:qhdkfq_regulatory_flutter/home/help/danger_edit_page.dart';
import 'package:qhdkfq_regulatory_flutter/home/help/help_detail_page.dart';
import 'package:qhdkfq_regulatory_flutter/home/help/help_record_page.dart';
import 'package:qhdkfq_regulatory_flutter/home/home_page.dart';
import 'package:qhdkfq_regulatory_flutter/home/work_list_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 'package:qhdkfq_regulatory_flutter/tools/tools.dart';

import '../mock/mock_data.dart';
import '../tools/date_tool.dart';
import 'adaptive_list_item.dart';
import 'department_picker.dart';

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

  final int selectTabIndex = 0;
  final HomeCategroyType type;

  @override
  State<HomeCategroyListPage> createState() => _HomeCategroyListPageState();
}

class _HomeCategroyListPageState extends State<HomeCategroyListPage>
    with SingleTickerProviderStateMixin {
  final _searchController = TextEditingController();

  // 已选择的分类 id
  String? _selectedCategoryId;

  /// 选择的部门
  final String _chooseDepartment = "请选择部门";
  final String _chooseDataStr = getCurrentYearMonth();

  /// 选择的tab
  int _selectedTab = 0;

  /// 选择的radio
  late int _selectRadioIndex = 0;

  /// 是否是本人
  late bool _isMySelf = true;

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

  /// 模拟企业数据
  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; // 初始显示所有数据
    _tabController = TabController(
      length: widget.type.tabLists.length,
      vsync: this,
    );
    _tabController.addListener(() {
      if (!_tabController.indexIsChanging) {
        setState(() {
          _selectedTab = _tabController.index;
        });
      }
    });
  }

  List<Tab> _tabbarItemList(List<String> tabTitles) {
    return tabTitles.map((title) {
      return Tab(text: title);
    }).toList();
  }

  /// 列表
  Widget _listViewWidget() {
    final bool isAllowSelect = (widget.type == HomeCategroyType.enterpriseInfo && _selectedTab == 2) ||
        (widget.type == HomeCategroyType.keySafety && _selectedTab == 1);
    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: GestureDetector(
            onTap: () {
              if (isAllowSelect) {
                pushPage(WorkListPage(type: widget.type), context);
              }
              /// 不能直接点击的item不处理
            },
            child: Padding(
              padding: const EdgeInsets.all(15),
              child: AdaptiveListItem(
                title: enterprise['name'],
                items: _getEnterpriseProperties(enterprise),
                actions: _listItemButtons(),
                type: widget.type,
                selectTabIndex: _selectedTab,
              ),
            ),
          ),
        );
      },
    );
  }


  List<Widget> _listItemButtons() {
    List<Widget> buttons = [];
    if (widget.type == HomeCategroyType.supervisionSupport) {
      if (_selectedTab == 0) { // 监管帮扶管理
        buttons = [
          CustomButton(
            height: 40,
            text: "查看",
            backgroundColor: Colors.blue,
            padding: EdgeInsets.symmetric(horizontal: 30),
            onPressed: () {
              pushPage(HelpRecordPage(), context);
            },
          ),
          CustomButton(
            height: 40,
            text: "监管帮扶",
            backgroundColor: Colors.blue,
            padding: EdgeInsets.symmetric(horizontal: 30),
            onPressed: () {
              pushPage(DangerEditPage(HelpEditType.help), context);
            },
          ),
        ];
      }else{ // 监管帮扶隐患管理
        buttons = [
          CustomButton(
            height: 40,
            text: "复查",
            backgroundColor: Colors.blue,
            padding: EdgeInsets.symmetric(horizontal: 30),
            onPressed: () {
              pushPage(DangerDetailPage(DangerDetailType.repeat), context);
            },
          ),
          CustomButton(
            height: 40,
            text: "查看",
            backgroundColor: Colors.blue,
            padding: EdgeInsets.symmetric(horizontal: 30),
            onPressed: () {
              pushPage(DangerDetailPage(DangerDetailType.detail), context);
            },
          ),
          CustomButton(
            height: 40,
            text: "删除",
            backgroundColor: Colors.red,
            padding: EdgeInsets.symmetric(horizontal: 30),
            onPressed: () {
              // TODO ---
            },
          ),
        ];
      }

    }else if (widget.type == HomeCategroyType.specialInspection) { // 专项检查
      if (_selectedTab == 0) { // 监管帮扶管理
        buttons = [
          CustomButton(
            height: 40,
            text: "查看",
            backgroundColor: Colors.blue,
            padding: EdgeInsets.symmetric(horizontal: 30),
            onPressed: () {
              pushPage(ActionTaskPage(), context);
            },
          ),
          CustomButton(
            height: 40,
            text: "检查情况",
            backgroundColor: Colors.blue,
            padding: EdgeInsets.symmetric(horizontal: 30),
            onPressed: () {
              pushPage(ActionTaskPage(), context);
            },
          ),
        ];
      }else{ // 监管帮扶隐患管理
        buttons = [
          CustomButton(
            height: 40,
            text: "复查",
            backgroundColor: Colors.blue,
            padding: EdgeInsets.symmetric(horizontal: 30),
            onPressed: () {
              // pushPage(DangerDetailPage(DangerDetailType.repeat), context);
            },
          ),
          CustomButton(
            height: 40,
            text: "查看",
            backgroundColor: Colors.blue,
            padding: EdgeInsets.symmetric(horizontal: 30),
            onPressed: () {
              // pushPage(DangerDetailPage(DangerDetailType.detail), context);
            },
          ),
          CustomButton(
            height: 40,
            text: "删除",
            backgroundColor: Colors.red,
            padding: EdgeInsets.symmetric(horizontal: 30),
            onPressed: () {
              // TODO ---
            },
          ),
        ];
      }
    }
    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']},
        ];
    }
  }

  /// 选择部门这一行
  Widget _chooseDepartmentWidget() {
    return Row(
      spacing: 15,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        // 左侧部门选择区域
        _departmentWidget(1),
        // 不同类型显示不同
        if (widget.type == HomeCategroyType.enterpriseInfo &&
            _radioTitles.isNotEmpty)
          Padding(
            padding: EdgeInsets.only(left: 10),
            child: _buildDynamicRadioRow(
              options: _radioTitles,
              selectedValue: _selectRadioIndex,
              onChanged: (newValue) {
                setState(() => _selectRadioIndex = newValue!);
              },
            ),
          ),
        if (widget.type == HomeCategroyType.dualPrevention && _selectedTab == 2)
          // 左侧日期选择区域
          _departmentWidget(2),
      ],
    );
  }

  /// 选择部门单个组件
  Widget _departmentWidget(int type) {
    return Expanded(
      child: GestureDetector(
        onTap: () {
          if (type == 1) {
            showModalBottomSheet(
              context: context,
              isScrollControlled: true,
              barrierColor: Colors.black54,
              backgroundColor: Colors.transparent,
              builder:
                  (ctx) => DepartmentPicker(
                    data: mockCategories,
                    onSelected: (selectedId) {
                      setState(() {
                        _selectedCategoryId = selectedId;
                      });
                    },
                  ),
            );
          } else {}
        },
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
          decoration: BoxDecoration(
            color: h_backGroundColor(),
            borderRadius: BorderRadius.circular(4),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                child: Text(
                  type == 1 ? _chooseDepartment : _chooseDataStr,
                  overflow: TextOverflow.ellipsis,
                  style: const TextStyle(fontSize: 14, color: Colors.black),
                ),
              ),
              const Icon(
                Icons.keyboard_arrow_down,
                color: Colors.black54,
                size: 20,
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 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) {
    if (widget.type == HomeCategroyType.enterpriseInfo) {
      if (_selectedTab == 0) {
        _radioTitles = ["全部", "已划分", "未划分"];
      } else if (_selectedTab == 1) {
        _radioTitles = ["全部", "已通过", "已打回"];
      } else {
        _radioTitles = []; // 其他tab不需要显示radio
      }
    } else if (widget.type == HomeCategroyType.supervisionSupport ||
        widget.type == HomeCategroyType.specialInspection) {
      if (_selectedTab == 1) {
        _radioTitles = ["全部", "待整改", "待复查", "已复查"];
      }
    } else {
      _radioTitles = [];
    }

    return Scaffold(
      backgroundColor: h_backGroundColor(),
      appBar: MyAppbar(title: widget.type.title),
      body: SafeArea(
        child: Column(
          children: [
            if (widget.type.tabLists.isNotEmpty)
              Container(
                color: Colors.white,
                child: TabBar(
                  controller: _tabController,
                  labelStyle: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w300,
                  ),
                  indicator: UnderlineTabIndicator(
                    borderSide: BorderSide(width: 3.0, color: Colors.blue),
                    insets: EdgeInsets.symmetric(horizontal: 15.0),
                  ),
                  labelColor: Colors.blue,
                  unselectedLabelColor: Colors.black,
                  tabs: _tabbarItemList(widget.type.tabLists),
                  onTap: (index) {
                    setState(() {
                      _selectedTab = index;
                    });
                  },
                ),
              ),
            const SizedBox(height: 5),
            Container(
              padding: const EdgeInsets.all(10),
              color: Colors.white,
              child: Column(
                spacing: 10,
                children: [
                  _searchBar(),
                  if (widget.type == HomeCategroyType.enterpriseInfo ||
                      widget.type == HomeCategroyType.dualPrevention ||
                      widget.type == HomeCategroyType.keySafety)
                    _chooseDepartmentWidget(),
                  if ((widget.type == HomeCategroyType.supervisionSupport ||
                          widget.type == HomeCategroyType.specialInspection) &&
                      _selectedTab == 1)
                    Column(
                      spacing: 10,
                      crossAxisAlignment: CrossAxisAlignment.start,

                      children: [
                        Padding(
                          padding: EdgeInsets.only(left: 3),
                          child: _buildDynamicRadioRow(
                            options: _radioTitles,
                            selectedValue: _selectRadioIndex,
                            onChanged: (newValue) {
                              setState(() => _selectRadioIndex = newValue!);
                            },
                          ),
                        ),
                        Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Checkbox(
                              activeColor: Colors.blue,
                              value: _isMySelf,
                              materialTapTargetSize:
                                  MaterialTapTargetSize.shrinkWrap,
                              visualDensity: const VisualDensity(
                                horizontal: -4,
                                vertical: 0,
                              ),
                              onChanged: (bool? newValue) {
                                setState(() {
                                  _isMySelf = newValue ?? false;
                                });
                              },
                            ),
                            const SizedBox(width: 4),
                            Text("只看自己"),
                          ],
                        ),
                      ],
                    ),
                ],
              ),
            ),
            const SizedBox(height: 5),
            Expanded(child: _listViewWidget()),
          ],
        ),
      ),
    );
  }
}
