from rest_framework import serializers
from .definitions import SectionType

# ==========================================
# 1. ABSTRACT BASE
# ==========================================
class BaseSectionDataSerializer(serializers.Serializer):
    """Serializer parent qui nettoie les données nulles"""
    def to_representation(self, instance):
        data = super().to_representation(instance)
        return {k: v for k, v in data.items() if v is not None}


# ==========================================
# 2. HEROS
# ==========================================
class HeroSlideItemSerializer(serializers.Serializer):
    title = serializers.CharField(max_length=200, label="Titre H1")
    subtitle = serializers.CharField(max_length=300, required=False, allow_blank=True)
    tag = serializers.CharField(max_length=50, required=False, label="Tag (ex: Nouveau)")
    image = serializers.ImageField(required=False, label="Image de fond")
    video_url = serializers.URLField(required=False, label="Vidéo MP4 (Loop)")
    btn_primary_text = serializers.CharField(max_length=50, required=False)
    btn_primary_url = serializers.CharField(max_length=200, required=False)
    btn_secondary_text = serializers.CharField(max_length=50, required=False)
    btn_secondary_url = serializers.CharField(max_length=200, required=False)

class HeroSliderSerializer(BaseSectionDataSerializer):
    autoplay = serializers.BooleanField(default=True)
    interval = serializers.IntegerField(default=5000)
    slides = HeroSlideItemSerializer(many=True)

class HeroSimpleSerializer(BaseSectionDataSerializer):
    title = serializers.CharField(max_length=200)
    subtitle = serializers.CharField(required=False)
    background_color = serializers.CharField(required=False, help_text="Hex code ou classe CSS")

class HeroBlogSerializer(BaseSectionDataSerializer):
    """Peut être vide, car le frontend affichera le dernier article automatiquement"""
    custom_title = serializers.CharField(required=False, label="Titre alternatif")


# ==========================================
# 3. CONTENU RICHE & STRUCTURE
# ==========================================
class TextBlockSerializer(BaseSectionDataSerializer):
    content = serializers.CharField(style={'base_template': 'textarea.html'})
    align = serializers.ChoiceField(choices=['left', 'center', 'right'], default='center')

class TimelineItemSerializer(serializers.Serializer):
    year = serializers.CharField(max_length=20, label="Année/Date")
    title = serializers.CharField(max_length=100)
    description = serializers.CharField(max_length=300)

class TimelineSerializer(BaseSectionDataSerializer):
    items = TimelineItemSerializer(many=True)

class ValueItemSerializer(serializers.Serializer):
    title = serializers.CharField(max_length=100)
    description = serializers.CharField(max_length=200)
    icon = serializers.CharField(required=False, label="Classe Icone")

class ValuesGridSerializer(BaseSectionDataSerializer):
    items = ValueItemSerializer(many=True)

class AccordionItemSerializer(serializers.Serializer):
    question = serializers.CharField(max_length=200)
    answer = serializers.CharField(style={'base_template': 'textarea.html'})
    image = serializers.ImageField(required=False, label="Image contextuelle (Optionnel)")

class AccordionSerializer(BaseSectionDataSerializer):
    title = serializers.CharField(required=False)
    items = AccordionItemSerializer(many=True)


# ==========================================
# 4. PRÉSENTATION VISUELLE (FEATURES & PROCESS)
# ==========================================
class FeatureItemSerializer(serializers.Serializer):
    title = serializers.CharField(max_length=100)
    description = serializers.CharField(max_length=300)
    icon = serializers.CharField(required=False)
    image = serializers.ImageField(required=False)
    col_span = serializers.ChoiceField(choices=[1, 2], default=1, label="Largeur (Bento)")
    row_span = serializers.ChoiceField(choices=[1, 2], default=1, label="Hauteur (Bento)")

class FeaturesSerializer(BaseSectionDataSerializer):
    items = FeatureItemSerializer(many=True)

class ProcessStepSerializer(serializers.Serializer):
    step_number = serializers.CharField(max_length=10, label="Numéro (01)")
    title = serializers.CharField(max_length=100)
    description = serializers.CharField(max_length=300)
    image = serializers.ImageField(label="Illustration de l'étape")

class ProcessStepsSerializer(BaseSectionDataSerializer):
    """Sticky Scroll Process"""
    items = ProcessStepSerializer(many=True)

class ImageGallerySerializer(BaseSectionDataSerializer):
    images = serializers.ListField(
        child=serializers.ImageField(),
        allow_empty=False,
        label="Liste d'images"
    )

class PortfolioGridSerializer(BaseSectionDataSerializer):
    """Configuration de la grille projets"""
    title = serializers.CharField(required=False, label="Titre optionnel (ex: Nos Réalisations)")
    count = serializers.IntegerField(default=9, label="Nombre de projets à afficher")
    show_filters = serializers.BooleanField(default=True, label="Afficher les filtres par catégorie")

class ServicesListSerializer(BaseSectionDataSerializer):
    """Configuration de la liste des services"""
    layout = serializers.ChoiceField(choices=['grid', 'list'], default='grid', label="Disposition")
    show_icons = serializers.BooleanField(default=True, label="Afficher les icônes")
# ==========================================
# 5. ÉQUIPE & CONFIANCE
# ==========================================
class TeamMemberSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=100, label="Nom complet")
    role = serializers.CharField(max_length=100, label="Rôle / Poste")
    
    # Images
    photo_main = serializers.ImageField(label="Photo principale (Sérieuse)")
    photo_fun = serializers.ImageField(required=False, label="Photo au survol (Fun/Optionnel)")
    
    # Réseaux Sociaux & Liens (Tous optionnels)
    # allow_blank=True permet de laisser le champ vide "" dans le JSON sans provoquer d'erreur
    linkedin_url = serializers.CharField(required=False, allow_blank=True, label="Lien LinkedIn")
    facebook_url = serializers.CharField(required=False, allow_blank=True, label="Lien Facebook")
    twitter_url = serializers.CharField(required=False, allow_blank=True, label="Lien X (Twitter)")
    portfolio_url = serializers.CharField(required=False, allow_blank=True, label="Lien Portfolio / Site Web")

class TeamGridSerializer(BaseSectionDataSerializer):
    members = TeamMemberSerializer(many=True)

class LogoItemSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=100)
    image = serializers.ImageField()

class LogoCloudSerializer(BaseSectionDataSerializer):
    logos = LogoItemSerializer(many=True)

class StatItemSerializer(serializers.Serializer):
    value = serializers.CharField(max_length=50, label="Valeur (10k)")
    label = serializers.CharField(max_length=100)
    suffix = serializers.CharField(max_length=10, required=False)

class StatsSerializer(BaseSectionDataSerializer):
    style = serializers.ChoiceField(choices=['dark', 'light'], default='dark')
    items = StatItemSerializer(many=True)

class TestimonialItemSerializer(serializers.Serializer):
    author_name = serializers.CharField(max_length=100)
    author_role = serializers.CharField(max_length=100)
    quote = serializers.CharField(max_length=400)
    rating = serializers.IntegerField(min_value=1, max_value=5, default=5)
    avatar = serializers.ImageField(required=False)

class TestimonialsSerializer(BaseSectionDataSerializer):
    items = TestimonialItemSerializer(many=True)


# ==========================================
# 6. MARKETING (PRICING & CTA)
# ==========================================
class PricingPlanSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=50, label="Nom (ex: Pro)")
    price = serializers.CharField(max_length=50, label="Prix")
    features = serializers.ListField(child=serializers.CharField(), label="Liste fonctionnalités")
    is_recommended = serializers.BooleanField(default=False, label="Mettre en avant")
    btn_label = serializers.CharField(default="Choisir")

class PricingTableSerializer(BaseSectionDataSerializer):
    plans = PricingPlanSerializer(many=True)

class CTASerializer(BaseSectionDataSerializer):
    title = serializers.CharField()
    text = serializers.CharField(required=False)
    btn_text = serializers.CharField()
    btn_url = serializers.CharField()


# ==========================================
# 7. CONTACT & DYNAMIQUE
# ==========================================
class ContactSplitSerializer(BaseSectionDataSerializer):
    """Données d'affichage (pas le formulaire lui-même)"""
    title_info = serializers.CharField(default="Nos coordonnées")
    title_form = serializers.CharField(default="Envoyez-nous un message")
    email_contact = serializers.EmailField()
    phone_contact = serializers.CharField(required=False)
    address = serializers.CharField(required=False)

class LatestPostsSerializer(BaseSectionDataSerializer):
    count = serializers.IntegerField(default=3, label="Nombre d'articles à afficher")
    show_categories = serializers.BooleanField(default=True)


# ==========================================
# 8. FACTORY DU REGISTRE
# ==========================================
def get_serializer_class_for_type(section_type):
    MAPPING = {
        SectionType.HERO_SLIDER: HeroSliderSerializer,
        SectionType.HERO_SIMPLE: HeroSimpleSerializer,
        SectionType.HERO_BLOG: HeroBlogSerializer,
        
        SectionType.TEXT_BLOCK: TextBlockSerializer,
        SectionType.VALUES_GRID: ValuesGridSerializer,
        SectionType.ACCORDION: AccordionSerializer,
        SectionType.TIMELINE: TimelineSerializer,
        
        SectionType.FEATURES: FeaturesSerializer,
        SectionType.FEATURES_ALTERNATING: FeaturesSerializer, # On réutilise la même structure
        SectionType.PROCESS_STEPS: ProcessStepsSerializer,
        SectionType.IMAGE_GALLERY: ImageGallerySerializer,
        
        SectionType.TEAM_GRID: TeamGridSerializer,
        SectionType.LOGO_CLOUD: LogoCloudSerializer,
        SectionType.STATS: StatsSerializer,
        SectionType.TESTIMONIALS: TestimonialsSerializer,
        
        SectionType.PRICING_TABLE: PricingTableSerializer,
        SectionType.CTA: CTASerializer,
        
        SectionType.CONTACT_SPLIT: ContactSplitSerializer,
        SectionType.LATEST_POSTS: LatestPostsSerializer,
        SectionType.PORTFOLIO_GRID: PortfolioGridSerializer,
        SectionType.SERVICES_LIST: ServicesListSerializer,
    }
    return MAPPING.get(section_type, BaseSectionDataSerializer)