"""
UzorZen Core - Asosiy sahifa yaratish klassi (Takomillashtirilgan versiyasi)
Zamonaviy, responsive va professional web sahifalar yaratish uchun
"""

import os
import json
from jinja2 import Template
from .templates_base import BASE_HTML_TEMPLATE


class Page:
    """
    UzorZen asosiy sahifa yaratish klassi
    Zamonaviy, responsive va professional web sahifalar yaratish uchun
    """
    
    def __init__(self, title="UzorZen Sahifa", theme="default", language="uz"):
        """
        Sahifa yaratish
        
        Args:
            title (str): Sahifa sarlavhasi
            theme (str): Mavra (default, dark, modern, gradient)
            language (str): Til (uz, en)
        """
        self.title = title
        self.theme = theme
        self.language = language
        self.content = []
        self.styles = []
        self.scripts = []
        self.head_content = []
        self.meta_tags = {}
        
        # Enhanced Bootstrap 5 kutubxonalari
        self.bootstrap_css = """
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
        <link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">
        """
        
        self.bootstrap_js = """
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>
        """
        
        # Default meta tags
        self.add_meta_tag("description", "UzorZen - Zamonaviy web sahifalar generatori")
        self.add_meta_tag("author", "Yoqubov Javohir (RaKUZEN)")
        self.add_meta_tag("keywords", "UzorZen, web generator, Python, HTML, CSS, Bootstrap")
        
    def add_meta_tag(self, name, content):
        """Meta tag qo'shish"""
        self.meta_tags[name] = content
        
    def navbar(self, brand_name, links=None, user_menu=None, sticky=True, transparent=False):
        """
        Enhanced Navbar qismini qo'shish
        
        Args:
            brand_name (str): Brend nomi
            links (list): Navigatsiya linklari
            user_menu (dict): Foydalanuvchi menyusi
            sticky (bool): Yuqorida yopishqoq navbar
            transparent (bool): Shaffof navbar
        """
        if links is None:
            links = ["Bosh sahifa", "Biz haqimizda", "Bog'lanish"]
            
        navbar_class = "modern-navbar"
        if transparent:
            navbar_class += " bg-transparent"
        if sticky:
            navbar_class += " position-sticky"
            
        navbar_html = f"""
        <nav class="navbar navbar-expand-lg {navbar_class}" style="z-index: 1030;">
            <div class="container">
                <a class="navbar-brand" href="#">
                    <i class="bi bi-gem me-2"></i>{brand_name}
                </a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarNav">
                    <ul class="navbar-nav me-auto">
        """
        
        for i, link in enumerate(links):
            navbar_html += f'<li class="nav-item"><a class="nav-link" href="#section-{i+1}">{link}</a></li>'
            
        navbar_html += """
                    </ul>
        """
        
        if user_menu:
            navbar_html += f"""
                    <ul class="navbar-nav">
                        <li class="nav-item dropdown">
                            <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown">
                                <i class="bi bi-person-circle me-1"></i>{user_menu.get('name', 'Foydalanuvchi')}
                            </a>
                            <ul class="dropdown-menu">
            """
            for item in user_menu.get('items', []):
                navbar_html += f'<li><a class="dropdown-item" href="#">{item}</a></li>'
            navbar_html += """
                            </ul>
                        </li>
                    </ul>
            """
        
        navbar_html += """
                </div>
            </div>
        </nav>
        """
        
        self.content.append(navbar_html)
        
    def hero(self, title, subtitle="", background_image=None, buttons=None, particles=False, gradient=True):
        """
        Enhanced Hero sektsiyasini qo'shish
        
        Args:
            title (str): Asosiy sarlavha
            subtitle (str): Qo'shimcha matn
            background_image (str): Fon rasmi
            buttons (list): Tugmalar ro'yxati
            particles (bool): Zarrachalar effekti
            gradient (bool): Gradient fon
        """
        if buttons is None:
            buttons = [
                {"text": "Boshlash", "style": "btn-primary-modern", "href": "#"},
                {"text": "Ko'proq o'rganish", "style": "btn-outline-modern", "href": "#"}
            ]
            
        bg_style = f"background-image: url('{background_image}');" if background_image else ""
        
        particles_html = ""
        if particles:
            particles_html = """
            <div id="particles-js" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 1;"></div>
            """
            
        hero_html = f"""
        <section class="hero-section position-relative overflow-hidden" style="{bg_style}" data-aos="fade-up">
            {particles_html}
            <div class="container position-relative" style="z-index: 2;">
                <div class="row align-items-center min-vh-100">
                    <div class="col-lg-8 mx-auto text-center hero-content">
                        <div data-aos="zoom-in" data-aos-delay="200">
                            <h1 class="display-1 fw-bold text-white mb-4 typing-effect">{title}</h1>
                        </div>
                        {f'<p class="lead mb-5 text-white-75" data-aos="fade-up" data-aos-delay="400">{subtitle}</p>' if subtitle else ''}
                        <div class="d-flex flex-wrap justify-content-center gap-3" data-aos="fade-up" data-aos-delay="600">
        """
        
        for button in buttons:
            hero_html += f"""
                            <a href="{button['href']}" class="btn btn-modern {button['style']}">
                                {button['text']}
                            </a>
            """
        
        hero_html += """
                        </div>
                    </div>
                </div>
            </div>
        </section>
        """
        
        self.content.append(hero_html)
        
    def add_card(self, title, description, image=None, button=None, card_type="default", animation="fade-up"):
        """
        Enhanced Kartochka qo'shish
        
        Args:
            title (str): Kartochka sarlavhasi
            description (str): Tavsif
            image (str): Rasm yo'li
            button (dict): Tugma ma'lumotlari
            card_type (str): Kartochka turi (default, feature, service, product, modern)
            animation (str): Animatsiya turi
        """
        card_class = f"card modern-card h-100 {card_type}"
        
        image_html = f"""
        <div class="position-relative overflow-hidden" style="border-radius: var(--radius-xl) var(--radius-xl) 0 0;">
            <img src="{image}" class="card-img-top" alt="{title}" style="height: 200px; object-fit: cover;">
        </div>
        """ if image else ''
        
        button_html = ''
        if button:
            button_style = button.get('style', 'btn-primary-modern')
            button_text = button.get('text', 'Ko\'rish')
            button_href = button.get('href', '#')
            button_html = f"""
                <div class="mt-auto pt-3">
                    <a href="{button_href}" class="btn btn-modern {button_style} w-100">
                        {button_text}
                    </a>
                </div>
            """
            
        card_html = f"""
        <div class="col-lg-4 col-md-6 mb-5" data-aos="{animation}" data-aos-delay="200">
            <div class="{card_class}">
                {image_html}
                <div class="card-body d-flex flex-column p-4">
                    <h5 class="card-title fw-bold mb-3">{title}</h5>
                    <p class="card-text flex-grow-1">{description}</p>
                </div>
                {button_html}
            </div>
        </div>
        """
        
        self.content.append(card_html)
        
    def modal(self, modal_id, title, content, size="modal-lg", animation="zoom"):
        """
        Enhanced Modal oynani qo'shish
        
        Args:
            modal_id (str): Unikal ID
            title (str): Modal sarlavhasi
            content (str): Modal kontenti
            size (str): Modal hajmi (modal-sm, modal-lg, modal-xl)
            animation (str): Modal animatsiyasi
        """
        modal_html = f"""
        <div class="modal fade" id="{modal_id}" tabindex="-1">
            <div class="modal-dialog {size}">
                <div class="modal-content border-0 shadow-lg" style="border-radius: var(--radius-xl);">
                    <div class="modal-header border-0 pb-0">
                        <h5 class="modal-title fw-bold">{title}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body pt-3">
                        {content}
                    </div>
                    <div class="modal-footer border-0">
                        <button type="button" class="btn btn-outline-modern" data-bs-dismiss="modal">Yopish</button>
                        <button type="button" class="btn btn-primary-modern">Saqlash</button>
                    </div>
                </div>
            </div>
        </div>
        """
        
        self.content.append(modal_html)
        
    def gallery(self, images, columns=3, lightbox=True, captions=None):
        """
        Enhanced Gallery qo'shish
        
        Args:
            images (list): Rasm ro'yxati
            columns (int): Ustunlar soni
            lightbox (bool): Lightbox effekti
            captions (list): Rasm captionlari
        """
        col_class = f"col-lg-{12//columns} col-md-{12//(columns-1)} col-sm-6"
        
        gallery_html = """
        <section class="py-5">
            <div class="container">
                <div class="row g-4">
        """
        
        for i, image in enumerate(images):
            caption = captions[i] if captions and i < len(captions) else f"Rasm {i+1}"
            
            gallery_html += f"""
                    <div class="{col_class}" data-aos="fade-up" data-aos-delay="{i*100}">
                        <div class="gallery-item position-relative overflow-hidden rounded">
                            <img src="{image}" class="img-fluid rounded" alt="{caption}" style="height: 250px; width: 100%; object-fit: cover;">
                            <div class="gallery-overlay">
                                <div class="text-center text-white">
                                    <i class="bi bi-zoom-in fs-2 mb-2"></i>
                                    <p class="mb-0">{caption}</p>
                                </div>
                            </div>
                        </div>
                    </div>
            """
        
        gallery_html += """
                </div>
            </div>
        </section>
        """
        
        self.content.append(gallery_html)
        
    def counter_section(self, counters):
        """
        Counter sektsiyasini qo'shish
        
        Args:
            counters (list): Counter ma'lumotlari [{value, label, icon}]
        """
        counter_html = """
        <section class="py-5">
            <div class="container">
                <div class="row g-4">
        """
        
        for counter in counters:
            value = counter.get('value', 0)
            label = counter.get('label', '')
            icon = counter.get('icon', 'bi-graph-up')
            
            counter_html += f"""
                    <div class="col-lg-3 col-md-6 text-center" data-aos="zoom-in">
                        <div class="modern-card p-4">
                            <i class="bi {icon} fs-1 text-gradient mb-3"></i>
                            <h3 class="display-4 fw-bold counter" data-target="{value}">{value}</h3>
                            <p class="mb-0">{label}</p>
                        </div>
                    </div>
            """
        
        counter_html += """
                </div>
            </div>
        </section>
        """
        
        self.content.append(counter_html)
        
    def testimonial_section(self, testimonials):
        """
        Testimonial sektsiyasini qo'shish
        
        Args:
            testimonials (list): Testimonial ma'lumotlari [{quote, author, role, avatar}]
        """
        testimonial_html = """
        <section class="py-5">
            <div class="container">
                <div class="row justify-content-center">
                    <div class="col-lg-8">
                        <div class="text-center mb-5" data-aos="fade-up">
                            <h2 class="fw-bold">Mijozlarimiz Nimaga Deyishadi?</h2>
                        </div>
                        <div class="row g-4">
        """
        
        for testimonial in testimonials:
            quote = testimonial.get('quote', '')
            author = testimonial.get('author', '')
            role = testimonial.get('role', '')
            avatar = testimonial.get('avatar', 'https://via.placeholder.com/80x80')
            
            testimonial_html += f"""
                    <div class="col-md-6" data-aos="fade-up" data-aos-delay="200">
                        <div class="modern-card h-100">
                            <div class="text-center mb-3">
                                <img src="{avatar}" alt="{author}" class="rounded-circle" width="60" height="60">
                            </div>
                            <blockquote class="mb-3">"{quote}"</blockquote>
                            <div class="text-center">
                                <h6 class="mb-1 fw-bold">{author}</h6>
                                <small class="text-muted">{role}</small>
                            </div>
                        </div>
                    </div>
            """
        
        testimonial_html += """
                        </div>
                    </div>
                </div>
            </div>
        </section>
        """
        
        self.content.append(testimonial_html)
        
    def footer(self, text="", links=None, social_media=None, company_info=None):
        """
        Enhanced Footer qo'shish
        
        Args:
            text (str): Footer matni
            links (list): Foydali linklar
            social_media (dict): Ijtimoiy tarmoq linklari
            company_info (dict): Kompaniya ma'lumotlari
        """
        if links is None:
            links = ["Bosh sahifa", "Biz haqimizda", "Xizmatlar", "Bog'lanish"]
            
        if social_media is None:
            social_media = {
                "Telegram": "https://t.me/UzMaxBoy",
                "Instagram": "https://instagram.com/penzenuz",
                "GitHub": "https://github.com/rakuzen"
            }
            
        if company_info is None:
            company_info = {
                "address": "Toshkent, O'zbekiston",
                "phone": "+998 90 123 45 67",
                "email": "info@uzorzen.com"
            }
            
        footer_html = f"""
        <footer class="modern-footer py-5">
            <div class="container">
                <div class="row g-4">
                    <div class="col-lg-8">
                        <h5 class="text-gradient mb-4">UzorZen</h5>
                        <p class="mb-4">{text}</p>
                        <div class="row g-3">
        """
        
        # Company info
        if company_info.get('address'):
            footer_html += f"""
                            <div class="col-sm-6">
                                <div class="d-flex align-items-center">
                                    <i class="bi bi-geo-alt me-2"></i>
                                    <small>{company_info['address']}</small>
                                </div>
                            </div>
            """
        
        if company_info.get('phone'):
            footer_html += f"""
                            <div class="col-sm-6">
                                <div class="d-flex align-items-center">
                                    <i class="bi bi-telephone me-2"></i>
                                    <small>{company_info['phone']}</small>
                                </div>
                            </div>
            """
        
        if company_info.get('email'):
            footer_html += f"""
                            <div class="col-12">
                                <div class="d-flex align-items-center">
                                    <i class="bi bi-envelope me-2"></i>
                                    <small>{company_info['email']}</small>
                                </div>
                            </div>
            """
            
        footer_html += """
                        </div>
                    </div>
                    <div class="col-lg-4">
                        <h6 class="mb-4">Foydali Linklar</h6>
                        <div class="d-flex flex-wrap gap-2 mb-4">
        """
        
        for link in links:
            footer_html += f'<a href="#{link.lower().replace(" ", "-")}" class="text-white-50 text-decoration-none small">{link}</a>'
            
        footer_html += """
                        </div>
                        <h6 class="mb-4">Bizni Kuzating</h6>
                        <div class="d-flex gap-3">
        """
        
        for platform, url in social_media.items():
            icon_class = {
                "Telegram": "bi-telegram",
                "Instagram": "bi-instagram", 
                "GitHub": "bi-github",
                "Facebook": "bi-facebook",
                "LinkedIn": "bi-linkedin",
                "Twitter": "bi-twitter"
            }.get(platform, "bi-link")
            
            footer_html += f"""
                            <a href="{url}" class="social-icon" target="_blank" title="{platform}">
                                <i class="bi {icon_class}"></i>
                            </a>
            """
        
        footer_html += """
                        </div>
                    </div>
                </div>
                <hr class="my-5 border-secondary">
                <div class="row">
                    <div class="col-12 text-center">
                        <p class="mb-0 text-muted">
                            © 2025 UzorZen. Created by RaKUZEN | Yoqubov Javohir
                        </p>
                        <p class="mb-0 text-muted">
                            Telegram: @UzMaxBoy | Instagram: penzenuz
                        </p>
                    </div>
                </div>
            </div>
        </footer>
        """
        
        self.content.append(footer_html)
        
    def add_css(self, css_code, media_query=None):
        """
        Qo'shimcha CSS qo'shish
        
        Args:
            css_code (str): CSS kodi
            media_query (str): Media query (ixtiyoriy)
        """
        if media_query:
            css_code = f"@media {media_query} {{\n{css_code}\n}}"
        
        self.styles.append(css_code)
        
    def add_js(self, js_code):
        """
        Qo'shimcha JavaScript qo'shish
        """
        self.scripts.append(js_code)
        
    def add_head_content(self, html_content):
        """
        Head qismiga qo'shimcha kontent qo'shish
        """
        self.head_content.append(html_content)
        
    def add_particles_background(self, particle_config=None):
        """
        Zarrachalar fon qo'shish
        
        Args:
            particle_config (dict): Particle konfiguratsiyasi
        """
        if particle_config is None:
            particle_config = {
                "particles": {
                    "number": {"value": 80},
                    "size": {"value": 3},
                    "color": {"value": "#ffffff"},
                    "move": {"speed": 1}
                }
            }
            
        js_code = f"""
        // Particles.js
        particlesJS('particles-js', {json.dumps(particle_config, indent=8)});
        """
        self.scripts.append(js_code)
        
    def add_analytics(self, tracking_id):
        """
        Google Analytics qo'shish
        
        Args:
            tracking_id (str): GA tracking ID
        """
        analytics_code = f"""
        <!-- Google Analytics -->
        <script async src="https://www.googletagmanager.com/gtag/js?id={tracking_id}"></script>
        <script>
            window.dataLayer = window.dataLayer || [];
            function gtag(){{dataLayer.push(arguments);}}
            gtag('js', new Date());
            gtag('config', '{tracking_id}');
        </script>
        """
        self.head_content.append(analytics_code)
        
    def save(self, filename="index.html", include_bootstrap=True, minify=False):
        """
        Sahifani HTML fayliga saqlash
        
        Args:
            filename (str): Fayl nomi
            include_bootstrap (bool): Bootstrap 5 ni qo'shish
            minify (bool): HTML ni minify qilish
        """
        # Base HTML template
        template = Template(BASE_HTML_TEMPLATE)
        
        # CSS va JS kodlarini birlashtirish
        custom_css = "\n".join(self.styles)
        custom_js = "\n".join(self.scripts)
        head_content = "\n".join(self.head_content)
        
        # HTML kodlarini birlashtirish
        content_html = "\n".join(self.content)
        
        # Bootstrap kutubxonalari
        bootstrap_html = ""
        if include_bootstrap:
            bootstrap_html = self.bootstrap_css + self.bootstrap_js
            
        # Meta tags qo'shish
        meta_tags_html = ""
        for name, content in self.meta_tags.items():
            meta_tags_html += f'<meta name="{name}" content="{content}">\n            '
        
        # HTML faylni yaratish
        html_content = template.render(
            title=self.title,
            content=content_html,
            bootstrap_css=bootstrap_html,
            custom_css=custom_css,
            custom_js=custom_js,
            head_content=head_content,
            meta_tags=meta_tags_html,
            theme=self.theme
        )
        
        # Minify (simple minification)
        if minify:
            html_content = self.minify_html(html_content)
        
        # Faylni saqlash
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(html_content)
            
        return f"Zamonaviy sahifa muvaffaqiyatli saqlandi: {filename}"
        
    def minify_html(self, html):
        """HTML ni minify qilish"""
        # Remove extra whitespace and newlines
        lines = [line.strip() for line in html.split('\n') if line.strip()]
        return ' '.join(lines)
        
    def preview(self):
        """
        Sahifani brauzerda ko'rish uchun tayyorlash
        """
        filename = "preview_" + self.title.lower().replace(" ", "_") + ".html"
        return self.save(filename)
        
    def export_config(self, filename="uzorzen_config.json"):
        """
        Loyiha konfiguratsiyasini eksport qilish
        """
        config = {
            "title": self.title,
            "theme": self.theme,
            "language": self.language,
            "content_components": len(self.content),
            "custom_css_blocks": len(self.styles),
            "custom_js_blocks": len(self.scripts),
            "meta_tags": self.meta_tags,
            "created_at": "2025-11-21T18:04:54"
        }
        
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(config, f, indent=2, ensure_ascii=False)
            
        return f"Konfiguratsiya eksport qilindi: {filename}"