import 'package:flutter/material.dart';
import 'package:injectable/injectable.dart';

import '../../../models/company_model.dart';
import '../../../domain/usecases/company/get_companies_usecase.dart';
import '../../../domain/usecases/company/get_company_detail_usecase.dart';
import '../../../domain/usecases/company/create_company_usecase.dart';
import '../../../domain/usecases/company/update_company_usecase.dart';
import '../../../domain/usecases/company/delete_company_usecase.dart';
import '../../../domain/usecases/company/restore_company_usecase.dart';
import '../../../core/constants/app_constants.dart';

@injectable
class CompanyController with ChangeNotifier {
  final GetCompaniesUseCase _getCompaniesUseCase;
  final GetCompanyDetailUseCase _getCompanyDetailUseCase;
  final CreateCompanyUseCase _createCompanyUseCase;
  final UpdateCompanyUseCase _updateCompanyUseCase;
  final DeleteCompanyUseCase _deleteCompanyUseCase;
  final RestoreCompanyUseCase _restoreCompanyUseCase;

  // 상태 관리
  bool _isLoading = false;
  String? _error;
  List<Company> _companies = [];
  Company? _selectedCompany;
  
  // 페이지네이션
  int _currentPage = 1;
  int _totalPages = 0;
  int _totalItems = 0;
  final int _pageSize = AppConstants.companyPageSize;
  
  // 필터
  String? _searchQuery;
  bool _includeDeleted = false;

  CompanyController(
    this._getCompaniesUseCase,
    this._getCompanyDetailUseCase,
    this._createCompanyUseCase,
    this._updateCompanyUseCase,
    this._deleteCompanyUseCase,
    this._restoreCompanyUseCase,
  );

  // Getters
  bool get isLoading => _isLoading;
  String? get error => _error;
  bool get hasError => _error != null;
  List<Company> get companies => _companies;
  Company? get selectedCompany => _selectedCompany;
  int get currentPage => _currentPage;
  int get totalPages => _totalPages;
  int get totalItems => _totalItems;
  int get pageSize => _pageSize;
  String? get searchQuery => _searchQuery;
  bool get includeDeleted => _includeDeleted;

  void _setLoading(bool loading) {
    _isLoading = loading;
    notifyListeners();
  }

  void _setError(String? error) {
    _error = error;
    notifyListeners();
  }

  void clearError() {
    _error = null;
    notifyListeners();
  }

  /// 회사 목록 조회
  Future<void> loadCompanies({
    int page = 1,
    int perPage = AppConstants.companyPageSize,
    String? search,
    bool includeDeleted = false,
    bool refresh = false,
  }) async {
    try {
      if (refresh) {
        _companies.clear();
        _currentPage = 1;
        notifyListeners();
      }

      _setLoading(true);
      
      final params = GetCompaniesParams(
        page: page,
        perPage: perPage,
        search: search,
        isActive: includeDeleted ? null : true,
      );
      
      final response = await _getCompaniesUseCase(params);
      
      response.fold(
        (failure) => _setError('회사 목록을 불러오는데 실패했습니다: ${failure.message}'),
        (data) {
          _companies = data.items;
          _currentPage = page;
          _totalPages = data.totalPages;
          _totalItems = data.totalElements;
          _searchQuery = search;
          _includeDeleted = includeDeleted;
          clearError();
        },
      );
    } catch (e) {
      _setError('회사 목록을 불러오는데 실패했습니다: $e');
    } finally {
      _setLoading(false);
    }
  }

  /// 회사 상세 조회
  Future<void> loadCompany(int id) async {
    try {
      _setLoading(true);
      
      final params = GetCompanyDetailParams(id: id);
      final response = await _getCompanyDetailUseCase(params);
      
      response.fold(
        (failure) => _setError('회사 정보를 불러오는데 실패했습니다: ${failure.message}'),
        (company) {
          _selectedCompany = company;
          clearError();
        },
      );
    } catch (e) {
      _setError('회사 정보를 불러오는데 실패했습니다: $e');
    } finally {
      _setLoading(false);
    }
  }

  /// 회사 생성
  Future<bool> createCompany(Company company) async {
    try {
      _setLoading(true);
      
      final params = CreateCompanyParams(company: company);
      final response = await _createCompanyUseCase(params);
      
      return response.fold(
        (failure) {
          _setError('회사 생성에 실패했습니다: ${failure.message}');
          return false;
        },
        (company) {
          // 목록 새로고침
          loadCompanies(refresh: true);
          clearError();
          return true;
        },
      );
    } catch (e) {
      _setError('회사 생성에 실패했습니다: $e');
      return false;
    } finally {
      _setLoading(false);
    }
  }

  /// 회사 수정
  Future<bool> updateCompany(int id, Company company) async {
    try {
      _setLoading(true);
      
      final params = UpdateCompanyParams(id: id, company: company);
      final response = await _updateCompanyUseCase(params);
      
      return response.fold(
        (failure) {
          _setError('회사 수정에 실패했습니다: ${failure.message}');
          return false;
        },
        (company) {
          // 목록 새로고침
          loadCompanies(refresh: true);
          clearError();
          return true;
        },
      );
    } catch (e) {
      _setError('회사 수정에 실패했습니다: $e');
      return false;
    } finally {
      _setLoading(false);
    }
  }

  /// 회사 삭제 (Soft Delete)
  Future<bool> deleteCompany(int id) async {
    try {
      _setLoading(true);
      
      final params = DeleteCompanyParams(id: id);
      final response = await _deleteCompanyUseCase(params);
      
      return response.fold(
        (failure) {
          _setError('회사 삭제에 실패했습니다: ${failure.message}');
          return false;
        },
        (_) {
          // 목록 새로고침
          loadCompanies(refresh: true);
          clearError();
          return true;
        },
      );
    } catch (e) {
      _setError('회사 삭제에 실패했습니다: $e');
      return false;
    } finally {
      _setLoading(false);
    }
  }

  /// 회사 복구
  Future<bool> restoreCompany(int id) async {
    try {
      _setLoading(true);
      
      final response = await _restoreCompanyUseCase(id);
      
      return response.fold(
        (failure) {
          _setError('회사 복구에 실패했습니다: ${failure.message}');
          return false;
        },
        (company) {
          // 목록 새로고침
          loadCompanies(refresh: true);
          clearError();
          return true;
        },
      );
    } catch (e) {
      _setError('회사 복구에 실패했습니다: $e');
      return false;
    } finally {
      _setLoading(false);
    }
  }

  /// 페이지 변경
  Future<void> goToPage(int page) async {
    if (page < 1 || page > _totalPages || page == _currentPage) return;
    
    await loadCompanies(
      page: page,
      search: _searchQuery,
      includeDeleted: _includeDeleted,
    );
  }

  /// 검색 설정
  void setSearch(String? search) {
    _searchQuery = search;
    loadCompanies(
      search: search,
      includeDeleted: _includeDeleted,
      refresh: true,
    );
  }

  /// 삭제된 항목 포함 여부 토글
  void toggleIncludeDeleted() {
    _includeDeleted = !_includeDeleted;
    loadCompanies(
      search: _searchQuery,
      includeDeleted: _includeDeleted,
      refresh: true,
    );
  }

  /// 새로고침
  Future<void> refresh() async {
    await loadCompanies(
      page: 1,
      search: _searchQuery,
      includeDeleted: _includeDeleted,
      refresh: true,
    );
  }

  /// 선택된 회사 초기화
  void clearSelectedCompany() {
    _selectedCompany = null;
    notifyListeners();
  }
}