import 'package:flutter/material.dart';
import 'package:superport/models/address_model.dart';
import 'package:superport/screens/common/widgets/address_input.dart';
import 'package:superport/screens/common/widgets/remark_input.dart';
import 'package:superport/screens/common/theme_tailwind.dart';
import 'controllers/warehouse_location_form_controller.dart';

/// 입고지 추가/수정 폼 화면 (SRP 적용, 상태/로직 분리)
class WarehouseLocationFormScreen extends StatefulWidget {
  final int? id; // 수정 모드 지원을 위한 id 파라미터
  const WarehouseLocationFormScreen({Key? key, this.id}) : super(key: key);

  @override
  State<WarehouseLocationFormScreen> createState() =>
      _WarehouseLocationFormScreenState();
}

class _WarehouseLocationFormScreenState
    extends State<WarehouseLocationFormScreen> {
  /// 폼 컨트롤러 (상태 및 저장/수정 로직 위임)
  late final WarehouseLocationFormController _controller;

  @override
  void initState() {
    super.initState();
    // 컨트롤러 생성 및 초기화
    _controller = WarehouseLocationFormController();
    if (widget.id != null) {
      _controller.initialize(widget.id!);
    }
  }

  @override
  void dispose() {
    // 컨트롤러 해제
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_controller.isEditMode ? '입고지 수정' : '입고지 추가'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.of(context).maybePop(),
        ),
      ),
      body: SafeArea(
        child: Form(
          key: _controller.formKey,
          child: SingleChildScrollView(
            padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 32),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 입고지명 입력
                TextFormField(
                  controller: _controller.nameController,
                  decoration: const InputDecoration(
                    labelText: '입고지명',
                    hintText: '입고지명을 입력하세요',
                  ),
                  validator: (value) {
                    if (value == null || value.trim().isEmpty) {
                      return '입고지명을 입력하세요';
                    }
                    return null;
                  },
                ),
                const SizedBox(height: 24),
                // 주소 입력 (공통 위젯)
                AddressInput(
                  initialZipCode: _controller.address.zipCode,
                  initialRegion: _controller.address.region,
                  initialDetailAddress: _controller.address.detailAddress,
                  isRequired: true,
                  onAddressChanged: (zip, region, detail) {
                    setState(() {
                      _controller.updateAddress(
                        Address(
                          zipCode: zip,
                          region: region,
                          detailAddress: detail,
                        ),
                      );
                    });
                  },
                ),
                const SizedBox(height: 24),
                // 비고 입력
                RemarkInput(controller: _controller.remarkController),
                const SizedBox(height: 80), // 하단 버튼 여백 확보
              ],
            ),
          ),
        ),
      ),
      bottomNavigationBar: Padding(
        padding: const EdgeInsets.fromLTRB(24, 0, 24, 24),
        child: SizedBox(
          width: double.infinity,
          height: 48,
          child: ElevatedButton(
            onPressed:
                _controller.isSaving
                    ? null
                    : () async {
                      setState(() {}); // 저장 중 상태 갱신
                      final success = await _controller.save();
                      setState(() {}); // 저장 완료 후 상태 갱신
                      
                      if (success) {
                        // 성공 메시지 표시
                        if (mounted) {
                          ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(
                              content: Text(_controller.isEditMode ? '입고지가 수정되었습니다' : '입고지가 추가되었습니다'),
                              backgroundColor: AppThemeTailwind.success,
                            ),
                          );
                          // 리스트 화면으로 돌아가기
                          Navigator.of(context).pop(true);
                        }
                      } else {
                        // 실패 메시지 표시
                        if (mounted) {
                          ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(
                              content: Text(_controller.error ?? '저장에 실패했습니다'),
                              backgroundColor: AppThemeTailwind.danger,
                            ),
                          );
                        }
                      }
                    },
            style: ElevatedButton.styleFrom(
              backgroundColor: AppThemeTailwind.primary,
              minimumSize: const Size.fromHeight(48),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8),
              ),
            ),
            child:
                _controller.isSaving
                    ? const SizedBox(
                      width: 18,
                      height: 18,
                      child: CircularProgressIndicator(strokeWidth: 2),
                    )
                    : const Text(
                      '저장',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
          ),
        ),
      ),
    );
  }
}
