import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:superport/models/license_model.dart';
import 'package:superport/screens/license/controllers/license_form_controller.dart';
import 'package:superport/screens/common/theme_tailwind.dart';
import 'package:superport/screens/common/custom_widgets.dart';
import 'package:superport/services/mock_data_service.dart';
import 'package:superport/utils/validators.dart';

// 유지보수 등록/수정 화면 (UI만 담당, 상태/로직 분리)
class MaintenanceFormScreen extends StatefulWidget {
  final int? maintenanceId;
  const MaintenanceFormScreen({Key? key, this.maintenanceId}) : super(key: key);

  @override
  _MaintenanceFormScreenState createState() => _MaintenanceFormScreenState();
}

class _MaintenanceFormScreenState extends State<MaintenanceFormScreen> {
  late final LicenseFormController _controller;
  // 방문주기 드롭다운 옵션
  final List<String> _visitCycleOptions = [
    '미방문',
    '장애시 지원',
    '월',
    '격월',
    '분기',
    '반기',
    '년',
  ];
  // 점검형태 라디오 옵션
  final List<String> _inspectionTypeOptions = ['방문', '원격'];
  String _selectedVisitCycle = '미방문';
  String _selectedInspectionType = '방문';
  int _durationMonths = 12;

  @override
  void initState() {
    super.initState();
    _controller = LicenseFormController(
      dataService: MockDataService(),
      licenseId: widget.maintenanceId,
    );
    if (widget.maintenanceId != null) {
      _controller.isEditMode = true;
    }
    if (_controller.isEditMode) {
      _controller.loadLicense();
      // TODO: 기존 데이터 로딩 시 _selectedVisitCycle, _selectedInspectionType, _durationMonths 값 세팅 필요
    }
  }

  @override
  Widget build(BuildContext context) {
    // 유지보수 명은 유지보수기간, 방문주기, 점검형태를 결합해서 표기
    final String maintenanceName =
        '${_durationMonths}개월,${_selectedVisitCycle},${_selectedInspectionType}';
    return Scaffold(
      appBar: AppBar(
        title: Text(_controller.isEditMode ? '유지보수 수정' : '유지보수 등록'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _controller.formKey,
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 유지보수 명 표기 (입력 불가, 자동 생성)
                Padding(
                  padding: const EdgeInsets.only(bottom: 16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Text(
                        '유지보수 명',
                        style: TextStyle(fontWeight: FontWeight.bold),
                      ),
                      const SizedBox(height: 4),
                      Container(
                        width: double.infinity,
                        padding: const EdgeInsets.symmetric(
                          vertical: 12,
                          horizontal: 8,
                        ),
                        decoration: BoxDecoration(
                          border: Border.all(color: Colors.grey.shade400),
                          borderRadius: BorderRadius.circular(4),
                          color: Colors.grey.shade100,
                        ),
                        child: Text(
                          maintenanceName,
                          style: const TextStyle(fontSize: 16),
                        ),
                      ),
                    ],
                  ),
                ),
                // 유지보수 기간 (개월)
                _buildTextField(
                  label: '유지보수 기간 (개월)',
                  initialValue: _durationMonths.toString(),
                  hintText: '유지보수 기간을 입력하세요',
                  suffixText: '개월',
                  keyboardType: TextInputType.number,
                  inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                  validator: (value) => validateNumber(value, '유지보수 기간'),
                  onChanged: (value) {
                    setState(() {
                      _durationMonths = int.tryParse(value ?? '') ?? 0;
                    });
                  },
                ),
                // 방문 주기 (드롭다운)
                Padding(
                  padding: const EdgeInsets.only(bottom: 16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Text(
                        '방문 주기',
                        style: TextStyle(fontWeight: FontWeight.bold),
                      ),
                      const SizedBox(height: 4),
                      DropdownButtonFormField<String>(
                        value: _selectedVisitCycle,
                        items:
                            _visitCycleOptions
                                .map(
                                  (option) => DropdownMenuItem(
                                    value: option,
                                    child: Text(option),
                                  ),
                                )
                                .toList(),
                        onChanged: (value) {
                          setState(() {
                            _selectedVisitCycle = value!;
                          });
                        },
                        decoration: const InputDecoration(
                          border: OutlineInputBorder(),
                          contentPadding: EdgeInsets.symmetric(
                            horizontal: 8,
                            vertical: 0,
                          ),
                        ),
                        validator:
                            (value) =>
                                value == null || value.isEmpty
                                    ? '방문 주기를 선택하세요'
                                    : null,
                      ),
                    ],
                  ),
                ),
                // 점검 형태 (라디오버튼)
                Padding(
                  padding: const EdgeInsets.only(bottom: 16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Text(
                        '점검 형태',
                        style: TextStyle(fontWeight: FontWeight.bold),
                      ),
                      const SizedBox(height: 4),
                      Row(
                        children:
                            _inspectionTypeOptions.map((type) {
                              return Row(
                                children: [
                                  Radio<String>(
                                    value: type,
                                    groupValue: _selectedInspectionType,
                                    onChanged: (value) {
                                      setState(() {
                                        _selectedInspectionType = value!;
                                      });
                                    },
                                  ),
                                  Text(type),
                                ],
                              );
                            }).toList(),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 24),
                // 저장 버튼
                SizedBox(
                  width: double.infinity,
                  child: ElevatedButton(
                    onPressed: () {
                      if (_controller.formKey.currentState!.validate()) {
                        _controller.formKey.currentState!.save();
                        // 유지보수 명 결합하여 저장
                        final String saveName =
                            '${_durationMonths}개월,${_selectedVisitCycle},${_selectedInspectionType}';
                        _controller.name = saveName;
                        _controller.durationMonths = _durationMonths;
                        _controller.visitCycle = _selectedVisitCycle;
                        // 점검형태 저장 로직 필요 시 추가
                        _controller.saveLicense().then((success) {
                          if (success) {
                            Navigator.pop(context, true);
                          }
                        });
                      }
                    },
                    style: AppThemeTailwind.primaryButtonStyle,
                    child: Padding(
                      padding: const EdgeInsets.all(12.0),
                      child: Text(
                        _controller.isEditMode ? '수정하기' : '등록하기',
                        style: const TextStyle(fontSize: 16),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 공통 텍스트 필드 위젯 (onSaved → onChanged로 변경)
  Widget _buildTextField({
    required String label,
    required String initialValue,
    required String hintText,
    String? suffixText,
    TextInputType? keyboardType,
    List<TextInputFormatter>? inputFormatters,
    required String? Function(String?) validator,
    required void Function(String?) onChanged,
  }) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(label, style: const TextStyle(fontWeight: FontWeight.bold)),
          const SizedBox(height: 4),
          TextFormField(
            initialValue: initialValue,
            decoration: InputDecoration(
              hintText: hintText,
              suffixText: suffixText,
            ),
            keyboardType: keyboardType,
            inputFormatters: inputFormatters,
            validator: validator,
            onChanged: onChanged,
          ),
        ],
      ),
    );
  }
}
