import 'package:ef/ef.dart';
import 'package:flutter/material.dart';
import 'package:flutterflow_ui/flutterflow_ui.dart';
import 'package:vbvs_app/common/color/appConstants.dart';
import 'package:vbvs_app/common/util/FitTool.dart';
import 'package:vbvs_app/common/util/MyUtils.dart';
import 'package:vbvs_app/component/tool/CustomCard.dart';
import 'package:vbvs_app/controller/device/body_device_controller.dart';
import 'package:vbvs_app/controller/device/device_type_controller.dart';
import 'package:vbvs_app/controller/repair/repair_controller.dart';
import 'package:vbvs_app/controller/theme_controller/ThemeController.dart';
import 'package:vbvs_app/pages/repair/component/RepairModelReadOnlyWidget.dart';

class RepairDetailPage extends StatefulWidget {
  final dynamic data;

  const RepairDetailPage({super.key, required this.data});

  @override
  State<RepairDetailPage> createState() => _RepairDetailPageState();
}

class _RepairDetailPageState extends State<RepairDetailPage> {
  final ThemeController themeController = Get.find();
  final DeviceTypeController deviceTypeController = Get.find();
  final RepairController repairController = Get.find();
  final BodyDeviceController bodyDeviceController = Get.find();

  List<Map<String, dynamic>> devices = [];
  final List<GlobalKey> repairItemKeys = [];
  final GlobalKey contactKey = GlobalKey();
  final GlobalKey phoneKey = GlobalKey();

  late final TextEditingController _contactController;
  late final TextEditingController _phoneController;

  @override
  void initState() {
    super.initState();
    devices = List<Map<String, dynamic>>.from(widget.data['device'] ?? []);
    _updateRepairItemKeys();

    _contactController = TextEditingController(
      text: widget.data['contacts']?['name'] ?? '',
    );
    _phoneController = TextEditingController(
      text: widget.data['contacts']?['phone'] ?? '',
    );
  }

  void _updateRepairItemKeys() {
    repairItemKeys
      ..clear()
      ..addAll(List.generate(devices.length, (_) => GlobalKey()));
  }

  @override
  void dispose() {
    _contactController.dispose();
    _phoneController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, bodysize) => GestureDetector(
        onTap: () => FocusScope.of(context).unfocus(),
        child: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/img/bgNoImg.png'),
              fit: BoxFit.fill,
            ),
          ),
          child: Scaffold(
            backgroundColor: Colors.transparent,
            appBar: AppBar(
              backgroundColor: themeController.currentColor.sc17,
              automaticallyImplyLeading: false,
              iconTheme: IconThemeData(
                color: themeController.currentColor.sc3,
              ),
              titleSpacing: 0,
              title: Container(
                width: double.infinity,
                height: 180.rpx,
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    Text(
                      '设备报修'.tr,
                      style: TextStyle(
                        fontFamily: 'Readex Pro',
                        color: themeController.currentColor.sc3,
                        letterSpacing: 0,
                        fontSize: 30.rpx,
                      ),
                    ),
                    Positioned(
                      left: 0,
                      // child: returnIconButtom,
                      child: returnIconButtomAddCallback(() {}),
                    ),
                  ],
                ),
              ),
              centerTitle: false,
            ),
            body: SafeArea(
              top: true,
              child: Padding(
                padding:
                    EdgeInsetsDirectional.fromSTEB(30.rpx, 29.rpx, 30.rpx, 0),
                child: SingleChildScrollView(
                  child: Column(
                    mainAxisSize: MainAxisSize.max,
                    children: [
                      Row(
                        children: [
                          CustomCard(
                            borderRadius:
                                AppConstants().button_container_radius,
                            onTap: () {},
                            colors: [
                              themeController.currentColor.sc1,
                              themeController.currentColor.sc2,
                            ],
                            child: Container(
                              width: (MediaQuery.sizeOf(context).width * 0.284)
                                  .rpx,
                              constraints: BoxConstraints(
                                minWidth: 213.rpx,
                                minHeight: 91.rpx,
                              ),
                              child: Align(
                                alignment: AlignmentDirectional(0, 0),
                                child: Text(
                                  "${widget.data['type']}",
                                  style: TextStyle(
                                    letterSpacing: 0.0,
                                    color: themeController.currentColor.sc3,
                                    fontSize:
                                        AppConstants().normal_text_fontSize,
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),

                      /// 设备列表
                      Column(
                        children: List.generate(devices.length, (index) {
                          final item = devices[index];
                          return RepairModelReadOnlyWidget(
                            widgetKey: repairItemKeys[index],
                            model: item,
                            onTap: () {},
                            length: devices.length,
                            showDelete: false,
                          );
                        }).divide(SizedBox(height: 25.rpx)),
                      ),

                      /// 联系方式区域
                      Container(
                        width: double.infinity,
                        decoration: BoxDecoration(
                          color: themeController.currentColor.sc5,
                          borderRadius: BorderRadius.circular(
                              AppConstants().normal_container_radius),
                        ),
                        child: Padding(
                          padding: EdgeInsetsDirectional.fromSTEB(
                              30.rpx, 30.rpx, 30.rpx, 30.rpx),
                          child: Column(
                            mainAxisSize: MainAxisSize.max,
                            children: [
                              _buildParamRow(
                                context,
                                "联系人".tr,
                                "名称输入提示".tr,
                                (value) => repairController.name.value = value,
                                key: contactKey,
                                controller: _contactController,
                              ),
                              _buildParamRow(
                                context,
                                "手机号".tr,
                                "手机号输入提示".tr,
                                (value) => repairController.phone.value = value,
                                key: phoneKey,
                                controller: _phoneController,
                              ),
                            ].divide(SizedBox(height: 30.rpx)),
                          ),
                        ),
                      ),
                    ]
                        .divide(SizedBox(height: 25.rpx))
                        .addToEnd(SizedBox(height: 25.rpx)),
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildParamRow(
    BuildContext context,
    String text,
    String hinttext,
    void Function(String)? onChanged, {
    Key? key,
    required TextEditingController controller,
  }) {
    return Row(
      key: key,
      mainAxisSize: MainAxisSize.max,
      children: [
        Container(
          width: 110.rpx,
          child: Text(
            text,
            style: TextStyle(
              fontSize: 26.rpx,
              letterSpacing: 0.0,
              color: themeController.currentColor.sc3,
            ),
            overflow: TextOverflow.ellipsis,
            softWrap: false,
            maxLines: 1,
          ),
        ),
        Expanded(
          child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10.rpx),
              color: Colors.transparent,
            ),
            child: TextFormField(
              readOnly: true,
              controller: controller,
              autofocus: false,
              decoration: InputDecoration(
                isDense: true,
                hintText: hinttext,
                hintStyle: TextStyle(
                  letterSpacing: 0.0,
                  fontSize: AppConstants().normal_text_fontSize,
                  color: themeController.currentColor.sc4,
                ),
                enabledBorder: OutlineInputBorder(
                  borderSide:
                      BorderSide(color: Colors.transparent, width: 1.rpx),
                  borderRadius: BorderRadius.circular(
                      AppConstants().normal_container_radius),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide:
                      BorderSide(color: Colors.transparent, width: 1.rpx),
                  borderRadius: BorderRadius.circular(8.rpx),
                ),
                filled: true,
                fillColor: themeController.currentColor.sc15,
              ),
              style: TextStyle(
                letterSpacing: 0.0,
                color: themeController.currentColor.sc4,
                fontSize: AppConstants().normal_text_fontSize,
              ),
              cursorColor: themeController.currentColor.sc3,
              onChanged: onChanged,
            ),
          ),
        ),
      ].divide(SizedBox(width: 24.rpx)),
    );
  }
}
