import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:superport/models/license_model.dart';
import 'package:superport/services/license_service.dart';
import 'package:superport/services/mock_data_service.dart';

// 라이센스 폼의 상태 및 비즈니스 로직을 담당하는 컨트롤러
class LicenseFormController extends ChangeNotifier {
  final bool useApi;
  final MockDataService? mockDataService;
  late final LicenseService _licenseService;
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  bool _isEditMode = false;
  int? _licenseId;
  License? _originalLicense;
  bool _isLoading = false;
  String? _error;
  bool _isSaving = false;

  // 폼 필드 값
  String _name = '';
  int _companyId = 1;
  int _durationMonths = 12; // 기본값: 12개월
  String _visitCycle = '미방문'; // 기본값: 미방문

  // isEditMode setter
  set isEditMode(bool value) {
    _isEditMode = value;
    notifyListeners();
  }
  
  // name setter
  set name(String value) {
    _name = value;
    notifyListeners();
  }
  
  // durationMonths setter
  set durationMonths(int value) {
    _durationMonths = value;
    notifyListeners();
  }
  
  // visitCycle setter
  set visitCycle(String value) {
    _visitCycle = value;
    notifyListeners();
  }

  LicenseFormController({
    this.useApi = false,
    MockDataService? dataService,
    int? licenseId,
  }) : mockDataService = dataService ?? MockDataService() {
    if (useApi && GetIt.instance.isRegistered<LicenseService>()) {
      _licenseService = GetIt.instance<LicenseService>();
    }
    
    if (licenseId != null) {
      _licenseId = licenseId;
      _isEditMode = true;
      loadLicense();
    }
  }

  // Getters
  bool get isEditMode => _isEditMode;
  int? get licenseId => _licenseId;
  License? get originalLicense => _originalLicense;
  bool get isLoading => _isLoading;
  String? get error => _error;
  bool get isSaving => _isSaving;
  String get name => _name;
  int get companyId => _companyId;
  int get durationMonths => _durationMonths;
  String get visitCycle => _visitCycle;

  // Setters
  void setName(String value) {
    _name = value;
    notifyListeners();
  }

  void setCompanyId(int value) {
    _companyId = value;
    notifyListeners();
  }

  void setDurationMonths(int value) {
    _durationMonths = value;
    notifyListeners();
  }

  void setVisitCycle(String value) {
    _visitCycle = value;
    notifyListeners();
  }

  // 라이센스 정보 로드 (수정 모드)
  Future<void> loadLicense() async {
    if (_licenseId == null) return;

    _isLoading = true;
    _error = null;
    notifyListeners();

    try {
      if (useApi && GetIt.instance.isRegistered<LicenseService>()) {
        _originalLicense = await _licenseService.getLicenseById(_licenseId!);
      } else {
        _originalLicense = mockDataService?.getLicenseById(_licenseId!);
      }

      if (_originalLicense != null) {
        _name = _originalLicense!.productName ?? '';
        _companyId = _originalLicense!.companyId ?? 1;
        // durationMonths와 visitCycle은 License 모델에 없으므로 기본값 유지
        // _durationMonths = _originalLicense!.durationMonths;
        // _visitCycle = _originalLicense!.visitCycle;
      }
    } catch (e) {
      _error = e.toString();
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 라이센스 저장
  Future<bool> saveLicense() async {
    if (formKey.currentState?.validate() != true) return false;
    
    formKey.currentState?.save();
    
    _isSaving = true;
    _error = null;
    notifyListeners();

    try {
      final license = License(
        id: _isEditMode ? _licenseId : null,
        licenseKey: 'LIC-${DateTime.now().millisecondsSinceEpoch}',
        productName: _name,
        companyId: _companyId,
        // durationMonths와 visitCycle은 License 모델에 없음
        // 대신 expiryDate를 설정
        purchaseDate: DateTime.now(),
        expiryDate: DateTime.now().add(Duration(days: _durationMonths * 30)),
        remark: '방문주기: $_visitCycle',
      );

      if (useApi && GetIt.instance.isRegistered<LicenseService>()) {
        if (_isEditMode) {
          await _licenseService.updateLicense(license);
        } else {
          await _licenseService.createLicense(license);
        }
      } else {
        if (_isEditMode) {
          mockDataService?.updateLicense(license);
        } else {
          mockDataService?.addLicense(license);
        }
      }

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

  // 폼 초기화
  void resetForm() {
    _name = '';
    _companyId = 1;
    _durationMonths = 12;
    _visitCycle = '미방문';
    _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? validateDuration(String? value) {
    if (value == null || value.isEmpty) {
      return '계약 기간을 입력해주세요';
    }
    final duration = int.tryParse(value);
    if (duration == null || duration < 1) {
      return '유효한 계약 기간을 입력해주세요';
    }
    return null;
  }

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