import 'dart:io';
import 'package:flutter/material.dart';
import '../../../../../customWidget/ItemWidgetFactory.dart';
import '../../../../../customWidget/custom_button.dart';
import '../../../../../customWidget/date_picker_dialog.dart';
import '../../../../../customWidget/photo_picker_row.dart';
import '../../../../../tools/h_colors.dart';
import '../../../../../tools/tools.dart';

/// 隐患整改
class DannerRepair extends StatefulWidget {
  const DannerRepair({super.key});

  @override
  State<DannerRepair> createState() => _DannerRepairState();
}

class _DannerRepairState extends State<DannerRepair> {

  // 是否有整改方案
  bool _acceptedPrepare = false;

  // 是否有整改计划
  bool _acceptedPlan = false;
  final _standardController = TextEditingController();
  final _methodController = TextEditingController();
  final _fundController = TextEditingController();
  final _personController = TextEditingController();
  final _workTimeController = TextEditingController();
  final _timeController = TextEditingController();
  final _workController = TextEditingController();
  final _otherController = TextEditingController();

  var _selectData = DateTime.now();

  @override
  void dispose() {
    // 释放资源
    _standardController.dispose();
    _methodController.dispose();
    _fundController.dispose();
    _personController.dispose();
    _workTimeController.dispose();
    _timeController.dispose();
    _workController.dispose();
    _otherController.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(bottom: 10),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(5),
      ),
      child: Column(
        children: [
          ListItemFactory.createBuildSimpleSection("隐患整改"),
          Divider(height: 1),
          Container(
            height: 130,
            padding: EdgeInsets.all(15),
            child: Column(
              children: [
                Row(
                  children: [HhTextStyleUtils.mainTitle("隐患描述", fontSize: 15)],
                ),
                TextField(
                  keyboardType: TextInputType.multiline,
                  maxLines: null, // 不限制行数，输入多少文字就撑开多少行
                  style: TextStyle(fontSize: 15),
                  decoration: InputDecoration(
                    hintText: '请对隐患进行详细描述（必填项）',
                    border: InputBorder.none,
                  ),
                ),
              ],
            ),
          ),
          Divider(height: 1),
          GestureDetector(
            onTap: () {
              showDialog(
                context: context,
                builder:
                    (_) => HDatePickerDialog(
                  initialDate: DateTime.now(),
                  onCancel: () => Navigator.of(context).pop(),
                  onConfirm: (selected) {
                    print('选中日期: $selected');
                    Navigator.of(context).pop();
                    setState(() {
                      _selectData = selected;
                    });
                  },
                ),
              );
            },
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 15),
              child: ListItemFactory.createRowSpaceBetweenItem(
                leftText: "整改日期",
                rightText: "请选择",
                isRight: true,
              ),
            ),
          ),
          Divider(),
          RepairedPhotoSection(
            title: "整改后照片",
            maxCount: 4,
            mediaType: MediaType.image,
            onChanged: (files) {
              // 上传 files 到服务器
            },
            onAiIdentify: () {},
          ),

          Divider(),
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              CustomButton(
                onPressed: () {},
                text: "添加",
                backgroundColor: Colors.blue,
                borderRadius: 17,
                height: 34,
                padding: EdgeInsets.symmetric(horizontal: 20),
              ),
            ],
          ),
          _departmentItem(1),
          _departmentItem(2),
          Divider(),
          ListItemFactory.createYesNoSection(
            title: "是否有整改方案",
            yesLabel: "是",
            noLabel: "否",
            groupValue: _acceptedPrepare,
            onChanged: (val) {
              setState(() {
                _acceptedPrepare = val;
              });
            },
          ),
          _acceptedPrepare ? _acceptPrepare() : SizedBox(height: 1),
          Divider(),
          ListItemFactory.createYesNoSection(
            title: "是否有整改计划",
            yesLabel: "是",
            noLabel: "否",
            groupValue: _acceptedPlan,
            onChanged: (val) {
              setState(() {
                _acceptedPlan = val;
              });
            },
          ),
          _acceptedPlan ? _acceptPlan() : SizedBox(height: 1),
        ],
      ),
    );
  }
  /// 整改方案
  Widget _acceptPrepare() {
    final fields = [
      _buildReadOnlyRow("排查日期", "2025-1-2 11:22:30"),
      _buildReadOnlyRow("隐患清单", "-----"),
      ListItemFactory.createBuildMultilineInput("治理标准", "请输入治理标准", _standardController),
      ListItemFactory.createBuildMultilineInput("治理方法", "请输入治理方法", _methodController),
      ListItemFactory.createBuildMultilineInput("经费落实", "请输入经费落实", _fundController),
      ListItemFactory.createBuildMultilineInput("负责人员", "请输入负责人员", _personController),
      ListItemFactory.createBuildMultilineInput("工时安排", "请输入工时安排", _workTimeController),
      ListItemFactory.createBuildMultilineInput("时限要求", "请输入时限要求", _timeController),
      ListItemFactory.createBuildMultilineInput("工作要求", "请输入工作要求", _workController),
      ListItemFactory.createBuildMultilineInput("其他事项", "请输入其他事项", _otherController),
    ];

    return ListView.separated(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: fields.length,
      separatorBuilder:
          (_, __) => const Divider(height: 1, color: Colors.black12),
      itemBuilder:
          (_, index) => Padding(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        child: fields[index],
      ),
    );
  }

  Widget _buildReadOnlyRow(String left, String right) {
    return ListItemFactory.createRowSpaceBetweenItem(
      leftText: left,
      rightText: right,
    );
  }


  /// 验收部门和负责人选择的item
  Widget _departmentItem(int num) {
    return Padding(
      padding: const EdgeInsets.all(10),
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          Container(
            decoration: BoxDecoration(
              border: Border.all(color: Colors.black12, width: 1),
            ),
            child: _noAccepet_repair(false),
          ),

          // 当 num > 1 时，左上角显示删除按钮
          if (num > 1)
            Positioned(
              top: -20,
              left: -20,
              child: IconButton(
                padding: EdgeInsets.zero,
                constraints: const BoxConstraints(),
                icon: const Icon(Icons.cancel, color: Colors.red, size: 25),
                onPressed: () {
                  // 这里处理删除逻辑，比如：
                  // setState(() => _items.removeAt(num));
                },
              ),
            ),
        ],
      ),
    );
  }
  // #region 不整改
  Widget _noAccepet_repair(bool _accept) {
    return Column(
      children: [
        Container(
          padding: EdgeInsets.symmetric(horizontal: 10),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(5),
          ),
          child: ListItemFactory.createRowSpaceBetweenItem(
            leftText: "整改部门",
            rightText: "测试啊",
            isRight: true,
          ),
        ),
        Divider(
          height: 10,
          color: _accept ? h_backGroundColor() : Colors.transparent,
        ),
        Container(
          padding: EdgeInsets.symmetric(horizontal: 10),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(5),
          ),
          child: ListItemFactory.createRowSpaceBetweenItem(
            leftText: "整改负责人",
            rightText: "测试啊",
            isRight: true,
          ),
        ),
      ],
    );
  }

  /// 整改计划
  Widget _acceptPlan() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 10),
      child: MediaPickerRow(
        maxCount: 4,
        onChanged: (List<File> images) {
          // images 列表更新
        },
      ),
    );
  }
}
