import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:superport/models/warehouse_location_model.dart';
import 'package:superport/models/address_model.dart';
import 'package:superport/services/warehouse_service.dart';
import 'package:superport/services/mock_data_service.dart';

/// 입고지 폼 상태 및 저장/수정 로직을 담당하는 컨트롤러
class WarehouseLocationFormController extends ChangeNotifier {
  final bool useApi;
  final MockDataService? mockDataService;
  late final WarehouseService _warehouseService;
  
  /// 폼 키
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  /// 입고지명 입력 컨트롤러
  final TextEditingController nameController = TextEditingController();

  /// 비고 입력 컨트롤러
  final TextEditingController remarkController = TextEditingController();

  /// 주소 정보
  Address _address = const Address();

  /// 저장 중 여부
  bool _isSaving = false;

  /// 수정 모드 여부
  bool _isEditMode = false;

  /// 입고지 id (수정 모드)
  int? _id;

  /// 로딩 상태
  bool _isLoading = false;

  /// 에러 메시지
  String? _error;

  /// 원본 창고 위치 (수정 모드)
  WarehouseLocation? _originalLocation;

  WarehouseLocationFormController({
    this.useApi = true,
    this.mockDataService,
    int? locationId,
  }) {
    if (useApi && GetIt.instance.isRegistered<WarehouseService>()) {
      _warehouseService = GetIt.instance<WarehouseService>();
    }
    
    if (locationId != null) {
      initialize(locationId);
    }
  }

  // Getters
  Address get address => _address;
  bool get isSaving => _isSaving;
  bool get isEditMode => _isEditMode;
  int? get id => _id;
  bool get isLoading => _isLoading;
  String? get error => _error;
  WarehouseLocation? get originalLocation => _originalLocation;

  /// 기존 데이터 세팅 (수정 모드)
  Future<void> initialize(int locationId) async {
    _id = locationId;
    _isEditMode = true;
    _isLoading = true;
    _error = null;
    notifyListeners();

    try {
      if (useApi && GetIt.instance.isRegistered<WarehouseService>()) {
        _originalLocation = await _warehouseService.getWarehouseLocationById(locationId);
      } else {
        _originalLocation = mockDataService?.getWarehouseLocationById(locationId);
      }

      if (_originalLocation != null) {
        nameController.text = _originalLocation!.name;
        _address = _originalLocation!.address;
        remarkController.text = _originalLocation!.remark ?? '';
      }
    } catch (e) {
      _error = e.toString();
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// 주소 변경 처리
  void updateAddress(Address newAddress) {
    _address = newAddress;
    notifyListeners();
  }

  /// 저장 처리 (추가/수정)
  Future<bool> save() async {
    if (!formKey.currentState!.validate()) return false;
    
    _isSaving = true;
    _error = null;
    notifyListeners();

    try {
      final location = WarehouseLocation(
        id: _isEditMode ? _id! : 0,
        name: nameController.text.trim(),
        address: _address,
        remark: remarkController.text.trim().isEmpty ? null : remarkController.text.trim(),
      );

      if (useApi && GetIt.instance.isRegistered<WarehouseService>()) {
        if (_isEditMode) {
          await _warehouseService.updateWarehouseLocation(location);
        } else {
          await _warehouseService.createWarehouseLocation(location);
        }
      } else {
        if (_isEditMode) {
          mockDataService?.updateWarehouseLocation(location);
        } else {
          mockDataService?.addWarehouseLocation(location);
        }
      }

      return true;
    } catch (e) {
      _error = e.toString();
      notifyListeners();
      return false;
    } finally {
      _isSaving = false;
      notifyListeners();
    }
  }

  /// 폼 초기화
  void resetForm() {
    nameController.clear();
    remarkController.clear();
    _address = const Address();
    _error = null;
    formKey.currentState?.reset();
    notifyListeners();
  }

  /// 유효성 검사
  String? validateName(String? value) {
    if (value == null || value.isEmpty) {
      return '입고지명을 입력해주세요';
    }
    if (value.length < 2) {
      return '입고지명은 2자 이상이어야 합니다';
    }
    return null;
  }

  String? validateAddress() {
    if (_address.isEmpty) {
      return '주소를 입력해주세요';
    }
    return null;
  }

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