import 'package:equatable/equatable.dart';
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:flux/features/master_data/store/models/store_model.dart';

// L'Enum magico e blindato per il sistema
enum SystemRole {
  admin,
  manager,
  user;

  // Helper per convertire dal DB a Dart in sicurezza
  static SystemRole fromString(String? value) {
    return SystemRole.values.firstWhere(
      (e) => e.name == value,
      orElse: () => SystemRole.user, // Fallback paranoico al livello più basso
    );
  }
}

class StaffMemberModel extends Equatable {
  final String? id;
  final String companyId;
  final String userId;
  final String name;
  final String? email;
  final String? phoneNumber;
  final String? jobTitle;
  final SystemRole systemRole;
  final bool isActive;
  final bool hasJoined;
  final List<String> assignedStoreIds;
  final List<StoreModel> assignedStores;

  const StaffMemberModel({
    this.id,
    required this.companyId,
    required this.userId,
    required this.name,
    this.email,
    this.phoneNumber,
    this.jobTitle,
    this.systemRole = SystemRole.user,
    this.isActive = true,
    this.hasJoined = false,
    this.assignedStoreIds = const [],
    this.assignedStores = const [],
  });

  StaffMemberModel copyWith({
    String? id,
    String? companyId,
    String? userId,
    String? name,
    String? surname,
    String? email,
    String? phoneNumber,
    String? jobTitle,
    SystemRole? systemRole,
    bool? isActive,
    bool? hasJoined,
    List<String>? assignedStoreIds,
    List<StoreModel>? assignedStores,
  }) {
    return StaffMemberModel(
      id: id ?? this.id,
      companyId: companyId ?? this.companyId,
      userId: userId ?? this.userId,
      name: name ?? this.name,
      email: email ?? this.email,
      phoneNumber: phoneNumber ?? this.phoneNumber,
      jobTitle: jobTitle ?? this.jobTitle,
      systemRole: systemRole ?? this.systemRole,
      isActive: isActive ?? this.isActive,
      hasJoined: hasJoined ?? this.hasJoined,
      assignedStoreIds: assignedStoreIds ?? this.assignedStoreIds,
      assignedStores: assignedStores ?? this.assignedStores,
    );
  }

  factory StaffMemberModel.empty() {
    return const StaffMemberModel(
      companyId: '',
      userId: '',
      name: '',
      email: '',
      phoneNumber: '',
      jobTitle: '',
    );
  }

  factory StaffMemberModel.fromMap(Map<String, dynamic> map) {
    // 1. Gestiamo l'array nullo di Supabase trasformandolo in lista vuota
    final List<String> parsedAssignedStoreIds =
        map['assigned_store_ids'] != null
        ? List<String>.from(map['assigned_store_ids'])
        : [];

    // 2. Mappiamo il JOIN degli store, se presente
    List<StoreModel> storeList = [];

    // Gestione del JSON proveniente dal Join nidificato (es. task_assignments -> staff_members)
    if (map['store_assignments'] != null) {
      storeList = (map['store_assignments'] as List)
          .map((a) => a[Tables.stores])
          .where((s) => s != null)
          .map((s) => StoreModel.fromMap(s))
          .toList();
    }

    return StaffMemberModel(
      id: map['id'] as String?,
      companyId: map['company_id'] ?? '',
      userId: map['user_id'] ?? '',
      name: map['name'] ?? '',
      email: map['email'] as String?,
      phoneNumber: map['phone_number'] as String?,
      jobTitle: map['job_title'] as String?,
      systemRole: SystemRole.fromString(map['system_role']),
      isActive: map['is_active'] ?? true,
      hasJoined: map['has_joined'] ?? false,
      assignedStoreIds: parsedAssignedStoreIds,
      assignedStores: storeList,
    );
  }

  Map<String, dynamic> toMap() {
    return {
      if (id != null) 'id': id,
      'company_id': companyId,
      'user_id': userId,
      'name': name,
      if (email != null) 'email': email,
      if (phoneNumber != null) 'phone_number': phoneNumber,
      if (jobTitle != null) 'job_title': jobTitle,
      'system_role': systemRole.name, // Trasforma SystemRole.admin in 'admin'
      'is_active': isActive,
      'has_joined': hasJoined,
    };
  }

  @override
  List<Object?> get props => [
    id,
    companyId,
    userId,
    name,
    email,
    phoneNumber,
    jobTitle,
    systemRole,
    isActive,
    hasJoined,
    assignedStoreIds,
    assignedStores,
  ];
}
