import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:qhd_prevention/customWidget/bottom_picker.dart';
import 'package:qhd_prevention/customWidget/bottom_picker_two.dart';
import 'package:qhd_prevention/customWidget/custom_button.dart';
import 'package:qhd_prevention/customWidget/department_picker_hidden_type.dart';
import 'package:qhd_prevention/customWidget/full_screen_video_page.dart';
import 'package:qhd_prevention/customWidget/picker/CupertinoDatePicker.dart';
import 'package:qhd_prevention/customWidget/single_image_viewer.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'package:qhd_prevention/pages/home/tap/item_list_widget.dart';
import 'package:qhd_prevention/tools/tools.dart';
import '../../../../customWidget/photo_picker_row.dart';
import '../../../../http/ApiService.dart';

/// 添加 修改 查看
enum SafeCheckEditType { add, edit, see }

class SafeCheckDrawerPage extends StatefulWidget {
  const SafeCheckDrawerPage({
    super.key,
    required this.editType,
    this.initialHidden,
    required this.toCheckUnitList,
  });

  final SafeCheckEditType editType;
  final List<dynamic> toCheckUnitList;

  /// 可选：传入已有的 hiddenForm（用于 edit / see）
  final Map<String, dynamic>? initialHidden;

  @override
  State<SafeCheckDrawerPage> createState() => _SafeCheckDrawerPageState();
}

class _SafeCheckDrawerPageState extends State<SafeCheckDrawerPage> {
  // Controllers
  final TextEditingController _descCtl = TextEditingController();
  final TextEditingController _partCtl = TextEditingController();
  final TextEditingController _rectifyCtl = TextEditingController();

  bool _isEdit = false;

  // Data lists
  List<dynamic> _hazardLevels = [];

  // Selected / transient state
  Map<String, dynamic> hiddenForm = {};

  bool _rectifyClickable = true; // 是否可切换整改方式

  @override
  void initState() {
    super.initState();
    _isEdit = widget.editType != SafeCheckEditType.see;
    _initHiddenForm();
    _loadHazardLevels();
  }

  void _initHiddenForm() {
    hiddenForm = {
      'ISRELEVANT': '2',
      'SOURCE': '5',
      'hiddenImgs': <Map<String, dynamic>>[],
      'zgImgs': <Map<String, dynamic>>[],
      'hiddenVideos': <Map<String, dynamic>>[],
      'RECTIFICATIONTYPE': '2',
    };

    // 如果传入了初始数据（编辑/查看），覆盖默认
    if (widget.initialHidden != null) {
      final Map<String, dynamic> m = Map<String, dynamic>.from(
        widget.initialHidden!,
      );
      // normalize lists to List<Map<String,dynamic>>
      m['hiddenImgs'] =
          (m['hiddenImgs'] as List<dynamic>?)
              ?.map(
                (e) =>
                    e is Map
                        ? Map<String, dynamic>.from(e)
                        : {'FILEPATH': e.toString()},
              )
              .toList() ??
          [];
      m['zgImgs'] =
          (m['zgImgs'] as List<dynamic>?)
              ?.map(
                (e) =>
                    e is Map
                        ? Map<String, dynamic>.from(e)
                        : {'FILEPATH': e.toString()},
              )
              .toList() ??
          [];
      m['hiddenVideos'] =
          (m['hiddenVideos'] as List<dynamic>?)
              ?.map(
                (e) =>
                    e is Map
                        ? Map<String, dynamic>.from(e)
                        : {'FILEPATH': e.toString()},
              )
              .toList() ??
          [];

      hiddenForm.addAll(m);
    }
    // init controllers and flags
    _descCtl.text = hiddenForm['HIDDENDESCR'] ?? '';
    _partCtl.text = hiddenForm['HIDDENPART'] ?? '';
    _rectifyCtl.text = hiddenForm['RECTIFYDESCR'] ?? '';

    // hidden level selected map is not stored directly; we can set HIDDENLEVEL_NAME/HIDDENLEVEL
  }

  @override
  void dispose() {
    _descCtl.dispose();
    _partCtl.dispose();
    _rectifyCtl.dispose();
    super.dispose();
  }

  Future<void> _loadHazardLevels() async {
    try {
      final res = await ApiService.getHazardLevel();
      if (res['result'] == 'success') {
        setState(() {
          final list = List<dynamic>.from(res['list'] ?? []);
          List rList = [];
          for (Map item in list) {
            if (item['NAME'] != '重大隐患' && item['NAME'] != '轻微隐患') {
              rList.add(item);
            }
          }
          _hazardLevels = rList;
        });
      }
    } catch (e) {
      // ignore
    }
  }

  Widget _section(Widget child) => Container(
    margin: const EdgeInsets.only(top: 10),
    color: Colors.white,
    padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10),
    child: child,
  );

  List<String> _getSelectedImages() {
    return (hiddenForm['hiddenImgs'] as List<Map<String, dynamic>>).map((e) {
      final p = '${e['FILEPATH']}';
      return p.contains('uploadFiles') ? '${ApiService.baseImgPath}$p' : p;
    }).toList();
  }

  List<String> _getSelectedVideos() {
    return (hiddenForm['hiddenVideos'] as List<Map<String, dynamic>>)
        .map((e) => '${ApiService.baseImgPath}${e['FILEPATH']}')
        .toList();
  }

  ///隐患发现时间
  Future<void> _chooseDatePicker() async {
    DateTime? picked = await BottomDateTimePicker.showDate(context);
    if (picked != null) {
      setState(() {
        hiddenForm['CREATTIME'] = DateFormat('yyyy-MM-dd HH:mm').format(picked);
      });
    }
    FocusHelper.clearFocus(context);

  }

  /// 隐患发现人
  Future<void> _pickDangerPerson() async {
    final choice = await BottomPicker.show<String>(
      context,
      items: [SessionService.instance.username as String],
      itemBuilder: (item) => Text(item, textAlign: TextAlign.center),
      initialIndex: 0,
    );
    FocusHelper.clearFocus(context);

    if (choice != null) {
      setState(() {
        hiddenForm['CREATOR_INDEX'] = 0;
        hiddenForm['CREATOR'] = SessionService.instance.loginUserId;
        hiddenForm['CREATOR_NAME'] = SessionService.instance.username;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Container(
        color: Colors.grey[100],
        child: Column(
          children: [
            // scroll content
            Expanded(
              child: SingleChildScrollView(
                padding: const EdgeInsets.only(bottom: 20),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    // photos
                    _section(
                      RepairedPhotoSection(
                        title: '隐患照片',
                        maxCount: 4,
                        mediaType: MediaType.image,
                        isShowAI: true,
                        isEdit: _isEdit,
                        isRequired: _isEdit,
                        initialMediaPaths: _getSelectedImages(),
                        onMediaTapped: (p) {
                          presentOpaque(
                            SingleImageViewer(imageUrl: p),
                            context,
                          );
                        },
                        onChanged:
                            (files) => setState(() {
                              hiddenForm['hiddenImgs'] =
                                  files
                                      .map((f) => {'FILEPATH': f.path})
                                      .toList();
                            }),
                        onAiIdentify: () {
                          final imgs = List<Map<String, dynamic>>.from(
                            hiddenForm['hiddenImgs'] ?? [],
                          );
                          if (imgs.isEmpty)
                            return ToastUtil.showNormal(context, '请先上传一张图片');
                          if (imgs.length > 1)
                            return ToastUtil.showNormal(
                              context,
                              '识别暂时只能上传一张图片',
                            );
                          final path = imgs.first['FILEPATH']?.toString() ?? '';
                          if (path.isNotEmpty) _identifyImage(path);
                        },
                      ),
                    ),

                    // videos
                    _section(
                      RepairedPhotoSection(
                        title: '隐患视频',
                        maxCount: 1,
                        onMediaTapped: (p) {
                          showDialog(
                            context: context,
                            barrierColor: Colors.black54,
                            builder: (_) => VideoPlayerPopup(videoUrl: p),
                          );
                        },
                        isEdit: _isEdit,
                        mediaType: MediaType.video,
                        initialMediaPaths: _getSelectedVideos(),
                        onChanged:
                            (files) => setState(() {
                              hiddenForm['hiddenVideos'] =
                                  files
                                      .map((f) => {'FILEPATH': f.path})
                                      .toList();
                            }),
                        onAiIdentify: () {},
                      ),
                    ),

                    // description
                    ItemListWidget.itemContainer(
                      ItemListWidget.multiLineTitleTextField(
                        label: '隐患描述',
                        isEditable: _isEdit,
                        text: hiddenForm['HIDDENDESCR'] ?? '',
                        controller: _descCtl,
                      ),
                      horizontal: 5,
                    ),

                    ItemListWidget.itemContainer(
                      ItemListWidget.multiLineTitleTextField(
                        label: '隐患部位',
                        isEditable: _isEdit,
                        text: hiddenForm['HIDDENPART'] ?? '',
                        controller: _partCtl,
                      ),
                      horizontal: 5,
                    ),
                    Container(
                      color: Colors.white,
                      padding: EdgeInsets.symmetric(horizontal: 3),
                      child: Column(
                        children: [
                          ItemListWidget.selectableLineTitleTextRightButton(
                            label: '隐患级别：',
                            isEditable: _isEdit,
                            text: hiddenForm['HIDDENLEVEL_NAME'] ?? '',
                            onTap: () {
                              _pickHazardLevel();
                            },
                          ),
                          SizedBox(height: 12),

                          ItemListWidget.selectableLineTitleTextRightButton(
                            label: '隐患类型：',
                            isEditable: _isEdit,
                            text: hiddenForm['HIDDENTYPE_NAME'] ?? '',
                            onTap: () {
                              _pickHazardType();
                            },
                          ),
                          SizedBox(height: 12),

                          ItemListWidget.selectableLineTitleTextRightButton(
                            label: '隐患发现时间：',
                            isEditable: _isEdit,
                            text: hiddenForm['CREATTIME'] ?? '',
                            onTap: () {
                              _chooseDatePicker();
                            },
                          ),
                          SizedBox(height: 12),
                          ItemListWidget.selectableLineTitleTextRightButton(
                            label: '隐患发现人：',
                            isEditable: _isEdit,
                            text: hiddenForm['CREATOR_NAME'] ?? '',
                            onTap: () {
                              _pickDangerPerson();
                            },
                          ),
                        ],
                      ),
                    ),

                    const SizedBox(height: 30),

                    // buttons
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 15),
                      child: Row(
                        children: [
                          Expanded(
                            child: CustomButton(
                              onPressed: cancelHidden,
                              text: '返回',
                              textStyle: TextStyle(color: Colors.black87),
                              backgroundColor: Colors.grey.shade300,
                            ),
                          ),
                          const SizedBox(width: 12),
                          if (_isEdit)
                            Expanded(
                              child: CustomButton(
                                onPressed: saveHidden,
                                text: '保存',
                                backgroundColor: Colors.blue,
                              ),
                            ),
                        ],
                      ),
                    ),
                    const SizedBox(height: 30),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // ----------------- Helpers -----------------
  Future<void> _pickHazardLevel() async {
    if (_hazardLevels.isEmpty) return ToastUtil.showNormal(context, '隐患级别数据为空');
    final choice = await BottomPickerTwo.show<String>(
      context,
      items: _hazardLevels,
      itemBuilder: (i) => Text(i['NAME'], textAlign: TextAlign.center),
      initialIndex: 0,
    );
    FocusHelper.clearFocus(context);
    if (choice == null) return;
    final found = _hazardLevels.firstWhere(
      (e) => e['NAME'] == choice,
      orElse: () => null,
    );
    if (found != null) {
      setState(() {
        hiddenForm['HIDDENLEVEL'] = found['BIANMA'] ?? found['id'] ?? '';
        hiddenForm['HIDDENLEVEL_NAME'] = found['NAME'] ?? '';
        hiddenForm['HIDDENLEVEL_INDEX'] = found['id'] ?? '0';
        _rectifyClickable =
            (found['DICTIONARIES_ID']?.toString() ?? '') !=
            '5ff9daf78e9a4fb1b40d77980656799d';
        if (!_rectifyClickable) {
          hiddenForm['RECTIFICATIONTYPE'] = '2';
        }
      });
    }
    FocusHelper.clearFocus(context);
  }

  Future<void> _pickHazardType() async {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      barrierColor: Colors.black54,
      backgroundColor: Colors.transparent,
      builder:
          (_) => DepartmentPickerHiddenType(
            onSelected: (result) {
              try {
                final Map m = Map.from(result);
                final ids = List<String>.from(m['id'] ?? []);
                final names = List<String>.from(m['name'] ?? []);
                setState(() {
                  hiddenForm['HIDDENTYPE'] = ids;
                  hiddenForm['HIDDENTYPE_NAME'] = names.join('/');

                });
                FocusHelper.clearFocus(context);

              } catch (_) {}
            },
          ),
    );
  }

  /// 保存隐患（这里只返回 hiddenForm 给上层调用者）
  void saveHidden() {
    // update hiddenForm from controllers before returning
    hiddenForm['HIDDENDESCR'] = _descCtl.text.trim();
    hiddenForm['HIDDENPART'] = _partCtl.text.trim();
    hiddenForm['RECTIFYDESCR'] = _rectifyCtl.text.trim();
    if ((hiddenForm['hiddenImgs'] as List).isEmpty) {
      return ToastUtil.showNormal(context, '请上传隐患图片');
    }
    // basic validation example
    if ((hiddenForm['HIDDENDESCR'] ?? '').toString().trim().isEmpty) {
      return ToastUtil.showNormal(context, '输入隐患描述');
    }
    if ((hiddenForm['HIDDENPART']?? '').toString().trim().isEmpty) {
      return ToastUtil.showNormal(context, '输入隐患部位');
    }
    if ((hiddenForm['HIDDENLEVEL'] ?? '').toString().trim().isEmpty) {
      return ToastUtil.showNormal(context, '请选择隐患级别');
    }
    if ((hiddenForm['HIDDENTYPE'] ?? '').toString().trim().isEmpty) {
      return ToastUtil.showNormal(context, '请选择隐患类型');
    }
    if ((hiddenForm['CREATTIME'] ?? '').toString().trim().isEmpty) {
      return ToastUtil.showNormal(context, '请选择隐患发现时间');
    }
    if ((hiddenForm['CREATOR'] ?? '').toString().trim().isEmpty) {
      return ToastUtil.showNormal(context, '请选择隐患发现人');
    }


    // 返回给调用方（抽屉关闭并返回数据）
    Navigator.of(context).pop(hiddenForm);
  }

  void cancelHidden() {
    Navigator.of(context).pop();
  }

  // 图片/视频查看与删除（简单实现）
  void viewImage(int index) {
    final imgs = List<Map<String, dynamic>>.from(
      hiddenForm['hiddenImgs'] ?? [],
    );
    if (index < 0 || index >= imgs.length) return;
    final path = imgs[index]['FILEPATH']?.toString() ?? '';

    presentOpaque(
      SingleImageViewer(imageUrl: ApiService.baseImgPath + path),
      context,
    );
  }

  void delImage(int index) {
    setState(() {
      final imgs = List<Map<String, dynamic>>.from(
        hiddenForm['hiddenImgs'] ?? [],
      );
      if (index >= 0 && index < imgs.length) {
        imgs.removeAt(index);
        hiddenForm['hiddenImgs'] = imgs;
      }
    });
  }

  void viewVideo(int index) {
    final vids = List<Map<String, dynamic>>.from(
      hiddenForm['hiddenVideos'] ?? [],
    );
    if (index < 0 || index >= vids.length) return;
    final path = vids[index]['FILEPATH']?.toString() ?? '';
    ToastUtil.showNormal(context, '查看视频：$path');
  }

  void delVideo(int index) {
    setState(() {
      final vids = List<Map<String, dynamic>>.from(
        hiddenForm['hiddenVideos'] ?? [],
      );
      if (index >= 0 && index < vids.length) {
        vids.removeAt(index);
        hiddenForm['hiddenVideos'] = vids;
      }
    });
  }

  Future<void> _identifyImage(String path) async {
    try {
      LoadingDialogHelper.show();
      final raw = await ApiService.identifyImg(path);
      if (raw['result'] == 'success') {
        final aiList = raw['aiHiddens'] ?? [];
        String desc = '';
        String rectify = '';
        for (final item in aiList) {
          try {
            final m = jsonDecode(item);
            desc =
                desc.isEmpty
                    ? (m['hiddenDescr'] ?? '')
                    : '$desc;${m['hiddenDescr'] ?? ''}';
            rectify =
                rectify.isEmpty
                    ? (m['rectificationSuggestions'] ?? '')
                    : '$rectify;${m['rectificationSuggestions'] ?? ''}';
          } catch (_) {}
        }
        setState(() {
          _descCtl.text = desc;
          _rectifyCtl.text = rectify;
          hiddenForm['HIDDENDESCR'] = desc;
          hiddenForm['RECTIFYDESCR'] = rectify;
          hiddenForm['RECTIFICATIONTYPE'] = '1';
        });
      } else {
        ToastUtil.showNormal(context, '识别失败');
      }
    } catch (e) {
      ToastUtil.showNormal(context, '识别异常：$e');
    } finally {
      LoadingDialogHelper.hide();
    }
  }



}
