import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:provider/provider.dart';

import '../../Models/crmModels/GetSegmentOnTeamResponse.dart';
import '../../Models/crmModels/crmLeadDetailsEditAccountViewResponse.dart';
import '../../services/api_calling.dart';
import '../HomeScreenNotifier.dart';

class Editcrmaccountdetailsprovider extends ChangeNotifier {
  TextEditingController editCompanyNameController = TextEditingController();

  List<Teams> _teamsList = [];
  AccountDetails _accountDetails = AccountDetails();
  List<Segments> _segmentsList = [];
  Teams? _selectedTeams;
  Segments? _selectedSegments;

  String? _selectedSegmentId;
  String? _selectedSegmentValue;

  String? _selectedTeamId;
  String? _selectedTeamValue;

  bool _isLoading = true;
  String? _companyNameError;
  String? _selectedTeamError;
  String? _selectedSegmentError;

  bool get isLoading => _isLoading;
  String? get companyNameError => _companyNameError;
  String? get selectedTeamError => _selectedTeamError;
  String? get selectedSegmentError => _selectedSegmentError;

  List<Teams> get teamsList => _teamsList;
  List<Segments> get segmentsList => _segmentsList;

  // IMPORTANT: Return null if the selected object is not present in the current list.
  // This prevents DropdownButton2 from receiving a value that is not part of items.
  Teams? get selectedTeams {
    if (_selectedTeams == null) return null;
    if (!_teamsList.contains(_selectedTeams)) return null;
    return _selectedTeams;
  }

  Segments? get selectedSegments {
    if (_selectedSegments == null) return null;
    if (!_segmentsList.contains(_selectedSegments)) return null;
    return _selectedSegments;
  }

  AccountDetails get accountsDetails => _accountDetails;

  String? get selectedTeamId => _selectedTeamId;
  String? get selectedTeamValue => _selectedTeamValue;
  String? get selectedSegmentId => _selectedSegmentId;
  String? get selectedSegmentValue => _selectedSegmentValue;

  set isLoading(bool value) {
    _isLoading = value;
    notifyListeners();
  }

  set companyNameError(String? value) {
    _companyNameError = value;
    notifyListeners();
  }

  set selectedTeamError(String? value) {
    _selectedTeamError = value;
    notifyListeners();
  }

  set selectedSegmentError(String? value) {
    _selectedSegmentError = value;
    notifyListeners();
  }

  set selectedTeams(Teams? value) {
    _selectedTeams = value;
    if (value != null) {
      _selectedTeamId = value.id;
      _selectedTeamValue = value.name;
    } else {
      _selectedTeamId = null;
      _selectedTeamValue = null;
    }
    notifyListeners();
  }

  set selectedSegments(Segments? value) {
    _selectedSegments = value;
    if (value != null) {
      _selectedSegmentId = value.id;
      _selectedSegmentValue = value.name;
    } else {
      _selectedSegmentId = null;
      _selectedSegmentValue = null;
    }
    notifyListeners();
  }

  set selectedTeamId(String? value) {
    _selectedTeamId = value;
    notifyListeners();
  }

  set selectedTeamValue(String? value) {
    _selectedTeamValue = value;
    notifyListeners();
  }

  set selectedSegmentId(String? value) {
    _selectedSegmentId = value;
    notifyListeners();
  }

  set selectedSegmentValue(String? value) {
    _selectedSegmentValue = value;
    notifyListeners();
  }

  Future<void> crmLeadDetailsEditAccountAPIFunction(
      context,
      leadID,
      mode,
      ) async {
    try {
      var HomeProv = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.crmLeadDetailsEditAccountViewAPI(
        HomeProv.empId,
        HomeProv.session,
        leadID,
        mode,
      );
      _isLoading = true;
      notifyListeners();
      if (data != null) {
        if (data.error == "0") {
          _teamsList = data.teams ?? [];
          _accountDetails = data.accountDetails ?? AccountDetails();

          // If current selected team/segment are not in the new lists, clear them
          if (_selectedTeams != null && !_teamsList.contains(_selectedTeams)) {
            _selectedTeams = null;
            _selectedTeamId = null;
            _selectedTeamValue = null;
          }
          if (_selectedSegments != null && !_segmentsList.contains(_selectedSegments)) {
            _selectedSegments = null;
            _selectedSegmentId = null;
            _selectedSegmentValue = null;
          }

          _isLoading = false;
          notifyListeners();
        } else {
          _isLoading = false;
          notifyListeners();
        }
      } else {
        _isLoading = false;
        notifyListeners();
      }
    } catch (e) {
      _isLoading = false;
      notifyListeners();
    }
  }

  Future<void> crmLeadListSegmentOnTeamAPIFunction(
      context,
      mode,
      teamID,
      ) async {
    try {
      var prov = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.crmLeadListSegmentOnTeamAPI(
        prov.empId,
        prov.session,
        teamID,
      );
      if (data != null) {
        if (data.error == "0") {
          _segmentsList = data.segments ?? [];

          // clear selectedSegments if it's not part of new list
          if (_selectedSegments != null && !_segmentsList.contains(_selectedSegments)) {
            _selectedSegments = null;
            _selectedSegmentId = null;
            _selectedSegmentValue = null;
          }

          notifyListeners();
        }
      }
    } catch (e) {}
  }

  // Fixed: check string emptiness properly (IDs are strings in your model)
  bool get isFormValid {
    final nameOk = editCompanyNameController.text.trim().isNotEmpty;
    final teamOk = _selectedTeamId != null && _selectedTeamId!.isNotEmpty;
    final segmentOk = _selectedSegmentId != null && _selectedSegmentId!.isNotEmpty;
    return nameOk && teamOk && segmentOk;
  }

  Future<void> crmLeadDetailsEditAccountSubmitAPIFunction(
      context,
      accountId,
      segmentId,
      teamId,
      ) async {
    try {
      if (!validateForm(context)) {
        return;
      }

      _isLoading = true;
      notifyListeners();

      var HomeProv = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.crmLeadDetailsEditAccountSubmitAPI(
        HomeProv.empId,
        HomeProv.session,
        accountId,
        segmentId,
        teamId,
        editCompanyNameController.text,
      );

      if (data != null) {
        if (data.error == "0") {
          Navigator.pop(context, true);
          resetValue();
          _isLoading = false;
          notifyListeners();
        } else {
          _isLoading = false;
          notifyListeners();
        }
      } else {
        _isLoading = false;
        notifyListeners();
      }
    } catch (e) {
      _isLoading = false;
      notifyListeners();
    }
  }

  bool validateForm(BuildContext context) {
    // Reset all errors
    _companyNameError = null;
    _selectedTeamError = null;
    _selectedSegmentError = null;

    bool isValid = true;

    // Team checks
    if (_selectedTeams == null || _selectedTeamId == null || _selectedTeamId!.isEmpty) {
      _selectedTeamError = "Please select a team";
      isValid = false;
    }

    // Segment checks
    if (_selectedSegments == null || _selectedSegmentId == null || _selectedSegmentId!.isEmpty) {
      _selectedSegmentError = "Please select a segment";
      isValid = false;
    }

    // Company name check
    if (editCompanyNameController.text.trim().isEmpty) {
      _companyNameError = "Please enter Company name";
      isValid = false;
    }

    notifyListeners();
    return isValid;
  }

  onChangedCompanyName(value) {
    // Clear the company name error when user types
    if (value != null && value.toString().trim().isNotEmpty) {
      _companyNameError = null;
    } else {
      _companyNameError = "Name is required";
    }
    notifyListeners();
  }

  void resetValue() {
    _isLoading = false;
    editCompanyNameController.clear();
    _selectedSegments = null;
    _selectedTeams = null;
    _selectedTeamId = null;
    _selectedSegmentId = null;
    _selectedTeamValue = null;
    _selectedSegmentValue = null;
    _selectedTeamError = null;
    _selectedSegmentError = null;
    _companyNameError = null;
  }

  void checkDropDownValues() {
    if (!_segmentsList.contains(_selectedSegments) && _selectedSegments != null) {
      _selectedTeamId = null;
      _selectedTeamValue = null;
    }
    if (!_teamsList.contains(_selectedTeams) && _selectedTeams != null) {
      _selectedSegmentId = null;
      _selectedSegmentValue = null;
    }
  }
}
