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

import 'provider_location_model.dart';
import 'provider_role.dart';

class ProviderModel extends Equatable {
  final String? id;
  final String companyId;
  final String name; // Nome "commerciale" per riconoscerlo velocemente
  final bool isActive;
  final String? colorHex;

  // Dati fiscali e legali
  final String? businessName; // Ragione Sociale
  final String? vatNumber; // P.IVA
  final String? fiscalCode; // C.F.
  final String? sdiCode; // Codice Univoco (SDI)
  final String? emailPec;
  final String? legalAddress;
  final String? legalCity;
  final String? legalZip;
  final String? legalProvince;

  // Ruoli e Sedi (Relazioni)
  final List<ProviderRole> roles;
  final List<ProviderLocationModel>? locations;

  const ProviderModel({
    this.id,
    required this.companyId,
    required this.name,
    this.isActive = true,
    this.colorHex,
    this.businessName,
    this.vatNumber,
    this.fiscalCode,
    this.sdiCode,
    this.emailPec,
    this.legalAddress,
    this.legalCity,
    this.legalZip,
    this.legalProvince,
    this.roles = const [],
    this.locations,
  });

  // 🥷 IL GETTER MAGICO: Converte l'esadecimale in un Color di Flutter
  Color get displayColor {
    if (colorHex == null || colorHex!.isEmpty) {
      return Colors.blueGrey; // Colore di default
    }

    // Rimuove l'eventuale '#' e aggiunge 'FF' per l'opacità (Alpha)
    final hex = colorHex!.replaceAll('#', '');
    return Color(int.parse('FF$hex', radix: 16));
  }

  factory ProviderModel.empty({required String companyId}) {
    return ProviderModel(
      companyId: companyId,
      name: '',
      isActive: true,
      roles: const [],
    );
  }

  ProviderModel copyWith({
    String? id,
    String? companyId,
    String? name,
    bool? isActive,
    String? Function()? colorHex,
    String? businessName,
    String? vatNumber,
    String? fiscalCode,
    String? sdiCode,
    String? emailPec,
    String? legalAddress,
    String? legalCity,
    String? legalZip,
    String? legalProvince,
    List<ProviderRole>? roles,
    List<ProviderLocationModel>? locations,
  }) {
    return ProviderModel(
      id: id ?? this.id,
      companyId: companyId ?? this.companyId,
      name: name ?? this.name,
      isActive: isActive ?? this.isActive,
      colorHex: colorHex != null ? colorHex() : this.colorHex,
      businessName: businessName ?? this.businessName,
      vatNumber: vatNumber ?? this.vatNumber,
      fiscalCode: fiscalCode ?? this.fiscalCode,
      sdiCode: sdiCode ?? this.sdiCode,
      emailPec: emailPec ?? this.emailPec,
      legalAddress: legalAddress ?? this.legalAddress,
      legalCity: legalCity ?? this.legalCity,
      legalZip: legalZip ?? this.legalZip,
      legalProvince: legalProvince ?? this.legalProvince,
      roles: roles ?? this.roles,
      locations: locations ?? this.locations,
    );
  }

  factory ProviderModel.fromMap(Map<String, dynamic> map) {
    // Parsing sicuro dell'array testuale di Supabase per trasformarlo in Enum
    List<ProviderRole> parsedRoles = [];
    if (map['roles'] != null) {
      final List<dynamic> rawRoles = map['roles'];
      for (var r in rawRoles) {
        final role = ProviderRole.fromString(r as String);
        if (role != null) parsedRoles.add(role);
      }
    }

    // Parsing della JOIN per le locations, se presenti nella query
    List<ProviderLocationModel>? parsedLocations;
    if (map['provider_locations'] != null) {
      parsedLocations = (map['provider_locations'] as List<dynamic>)
          .map(
            (item) =>
                ProviderLocationModel.fromMap(item as Map<String, dynamic>),
          )
          .toList();
    }

    return ProviderModel(
      id: map['id'] as String,
      companyId: map['company_id'] as String,
      name: map['name'] as String,
      isActive: map['is_active'] as bool? ?? true,
      colorHex: map['color_hex'] as String?,
      businessName: map['business_name'] as String?,
      vatNumber: map['vat_number'] as String?,
      fiscalCode: map['fiscal_code'] as String?,
      sdiCode: map['sdi_code'] as String?,
      emailPec: map['email_pec'] as String?,
      legalAddress: map['legal_address'] as String?,
      legalCity: map['legal_city'] as String?,
      legalZip: map['legal_zip'] as String?,
      legalProvince: map['legal_province'] as String?,
      roles: parsedRoles,
      locations: parsedLocations,
    );
  }

  Map<String, dynamic> toMap() {
    Map<String, dynamic> baseMap = {
      if (id != null && id!.trim().isNotEmpty) 'id': id,
      'company_id': companyId,
      'name': name,
      'is_active': isActive,
      'color_hex': colorHex,
      'business_name': businessName,
      'vat_number': vatNumber,
      'fiscal_code': fiscalCode,
      'sdi_code': sdiCode,
      'email_pec': emailPec,
      'legal_address': legalAddress,
      'legal_city': legalCity,
      'legal_zip': legalZip,
      'legal_province': legalProvince,
      // Trasformiamo gli Enum di nuovo in stringhe per Supabase
      'roles': roles.map((e) => e.name).toList(),
    };
    return baseMap;
  }

  @override
  List<Object?> get props => [
    id,
    companyId,
    name,
    isActive,
    colorHex,
    businessName,
    vatNumber,
    fiscalCode,
    sdiCode,
    emailPec,
    legalAddress,
    legalCity,
    legalZip,
    legalProvince,
    roles,
    locations,
  ];
}
