"""Navigation Generator for Material 3 Navigation Components.

Generates Material 3 navigation components with responsive design and
accessibility compliance.
"""

from pathlib import Path
from typing import Dict, List, Tuple, Any
from dataclasses import dataclass
import json

from ..models.project_context import ProjectContext
from ..validators.component_validator import ComponentValidator
from ..dependencies.container import FileSystem


@dataclass
class NavigationConfig:
    """Configuration for navigation component."""

    navigation_type: str  # "drawer", "rail", "bottom", "top"
    app_name: str
    app_logo: str
    navigation_items: List[Dict[str, Any]]
    user_menu: List[Dict[str, Any]]
    responsive_config: Dict[str, Any]
    theme_config: Dict[str, Any]
    accessibility_config: Dict[str, Any]


@dataclass
class NavigationSpec:
    """Complete specification for navigation component."""

    config: NavigationConfig
    layout_yaml: Dict[str, Any]
    route_integration: Dict[str, Any]
    responsive_breakpoints: Dict[str, Any]
    accessibility_features: List[Dict[str, Any]]


class NavigationGenerator:
    """Generate Material 3 navigation components."""

    def __init__(self, file_system: FileSystem) -> None:
        self.file_system: FileSystem = file_system
        self.validator: ComponentValidator = ComponentValidator()

    def create_navigation(
        self,
        config: NavigationConfig,
        project_context: ProjectContext,
        output_path: str,
    ) -> Tuple[bool, str]:
        """Create Material 3 navigation component."""
        try:
            # Generate navigation specification
            nav_spec = self._create_navigation_spec(config, project_context)

            # Generate layout YAML
            self._generate_layout_yaml(nav_spec, output_path)

            # Generate route integration
            self._generate_route_integration(nav_spec, output_path)

            # Generate responsive configuration
            self._generate_responsive_config(nav_spec, output_path)

            # Generate accessibility features
            self._generate_accessibility_features(nav_spec, output_path)

            # Generate navigation controller
            self._generate_navigation_controller(nav_spec, output_path)

            return (
                True,
                f"Navigation component '{config.navigation_type}' created successfully",
            )

        except Exception as e:
            return False, f"Error creating navigation: {str(e)}"

    def _create_navigation_spec(
        self, config: NavigationConfig, project_context: ProjectContext
    ) -> NavigationSpec:
        """Create complete navigation specification."""

        # Generate layout YAML based on navigation type
        layout_yaml = self._generate_layout_yaml_config(config, project_context)

        # Create route integration
        route_integration = self._create_route_integration(config, project_context)

        # Create responsive breakpoints
        responsive_breakpoints = self._create_responsive_breakpoints(config)

        # Create accessibility features
        accessibility_features = self._create_accessibility_features(config)

        return NavigationSpec(
            config=config,
            layout_yaml=layout_yaml,
            route_integration=route_integration,
            responsive_breakpoints=responsive_breakpoints,
            accessibility_features=accessibility_features,
        )

    def _generate_layout_yaml_config(
        self, config: NavigationConfig, project_context: ProjectContext
    ) -> Dict[str, Any]:
        """Generate layout YAML configuration."""

        if config.navigation_type == "drawer":
            return self._generate_drawer_layout(config, project_context)
        elif config.navigation_type == "rail":
            return self._generate_rail_layout(config, project_context)
        elif config.navigation_type == "bottom":
            return self._generate_bottom_navigation(config, project_context)
        elif config.navigation_type == "top":
            return self._generate_top_navigation(config, project_context)
        else:
            raise ValueError(f"Unsupported navigation type: {config.navigation_type}")

    def _generate_drawer_layout(
        self, config: NavigationConfig, project_context: ProjectContext
    ) -> Dict[str, Any]:
        """Generate NavigationDrawer layout."""

        return {
            "container": {
                "type": "NavigationDrawerLayout",
                "properties": {
                    "drawer_width": config.responsive_config.get(
                        "drawer_width", "280px"
                    ),
                    "temporary": config.responsive_config.get("temporary", False),
                    "role": "navigation-drawer",
                },
                "components": [
                    {
                        "name": "nav_drawer",
                        "type": "NavigationDrawer",
                        "properties": {"role": "navigation-drawer", "elevation": "1"},
                        "components": [
                            {
                                "name": "drawer_header",
                                "type": "LinearPanel",
                                "properties": {
                                    "align": "center",
                                    "spacing": "medium",
                                    "padding": "20px",
                                    "role": "drawer-header",
                                },
                                "components": [
                                    {
                                        "name": "app_logo",
                                        "type": "Image",
                                        "properties": {
                                            "source": config.app_logo,
                                            "height": "48px",
                                            "width": "48px",
                                            "role": "app-logo",
                                        },
                                    },
                                    {
                                        "name": "app_title",
                                        "type": "Label",
                                        "properties": {
                                            "text": config.app_name,
                                            "font_size": "20px",
                                            "font_weight": "bold",
                                            "role": "headline-small",
                                        },
                                    },
                                ],
                            },
                            {
                                "name": "nav_divider",
                                "type": "Divider",
                                "properties": {"role": "navigation-divider"},
                            },
                            {
                                "name": "navigation_list",
                                "type": "LinkPanel",
                                "properties": {
                                    "role": "navigation-list",
                                    "spacing": "none",
                                },
                                "components": self._generate_navigation_items(
                                    config.navigation_items
                                ),
                            },
                            {
                                "name": "user_section",
                                "type": "LinearPanel",
                                "properties": {
                                    "spacing": "small",
                                    "padding": "16px",
                                    "role": "user-section",
                                },
                                "components": self._generate_user_menu_items(
                                    config.user_menu
                                ),
                            },
                        ],
                    },
                    {
                        "name": "app_bar",
                        "type": "AppBar",
                        "properties": {
                            "title": config.app_name,
                            "role": "app-bar",
                            "elevation": "2",
                        },
                        "components": [
                            {
                                "name": "menu_button",
                                "type": "Button",
                                "properties": {
                                    "icon": "fa:bars",
                                    "role": "text-button",
                                    "tooltip": "Open navigation",
                                },
                                "event_bindings": {"click": "menu_button_click"},
                            }
                        ],
                    },
                    {
                        "name": "main_content",
                        "type": "ColumnPanel",
                        "properties": {"role": "main-content", "padding": "20px"},
                    },
                ],
            }
        }

    def _generate_rail_layout(
        self, config: NavigationConfig, project_context: ProjectContext
    ) -> Dict[str, Any]:
        """Generate NavigationRail layout."""

        return {
            "container": {
                "type": "NavigationRailLayout",
                "properties": {
                    "rail_width": config.responsive_config.get("rail_width", "80px"),
                    "expanded": config.responsive_config.get("expanded", False),
                    "role": "navigation-rail",
                },
                "components": [
                    {
                        "name": "nav_rail",
                        "type": "NavigationRail",
                        "properties": {"role": "navigation-rail", "elevation": "1"},
                        "components": [
                            {
                                "name": "rail_header",
                                "type": "LinearPanel",
                                "properties": {
                                    "align": "center",
                                    "spacing": "medium",
                                    "padding": "16px",
                                    "role": "rail-header",
                                },
                                "components": [
                                    {
                                        "name": "app_logo_small",
                                        "type": "Image",
                                        "properties": {
                                            "source": config.app_logo,
                                            "height": "32px",
                                            "width": "32px",
                                            "role": "app-logo",
                                        },
                                    }
                                ],
                            },
                            {
                                "name": "rail_navigation",
                                "type": "LinkPanel",
                                "properties": {
                                    "role": "navigation-list",
                                    "spacing": "none",
                                    "vertical": True,
                                },
                                "components": self._generate_rail_navigation_items(
                                    config.navigation_items
                                ),
                            },
                        ],
                    },
                    {
                        "name": "app_bar",
                        "type": "AppBar",
                        "properties": {
                            "title": config.app_name,
                            "role": "app-bar",
                            "elevation": "2",
                        },
                        "components": [
                            {
                                "name": "rail_toggle",
                                "type": "Button",
                                "properties": {
                                    "icon": "fa:bars",
                                    "role": "text-button",
                                    "tooltip": "Toggle navigation",
                                },
                                "event_bindings": {"click": "rail_toggle_click"},
                            }
                        ],
                    },
                    {
                        "name": "main_content",
                        "type": "ColumnPanel",
                        "properties": {"role": "main-content", "padding": "20px"},
                    },
                ],
            }
        }

    def _generate_bottom_navigation(
        self, config: NavigationConfig, project_context: ProjectContext
    ) -> Dict[str, Any]:
        """Generate bottom navigation layout."""

        return {
            "container": {
                "type": "ColumnPanel",
                "properties": {"role": "bottom-nav-layout"},
                "components": [
                    {
                        "name": "app_bar",
                        "type": "AppBar",
                        "properties": {
                            "title": config.app_name,
                            "role": "app-bar",
                            "elevation": "2",
                        },
                    },
                    {
                        "name": "main_content",
                        "type": "ColumnPanel",
                        "properties": {"role": "main-content", "padding": "20px"},
                    },
                    {
                        "name": "bottom_navigation",
                        "type": "LinearPanel",
                        "properties": {
                            "align": "space_around",
                            "spacing": "none",
                            "role": "bottom-navigation",
                            "position": "fixed",
                            "bottom": "0",
                            "left": "0",
                            "right": "0",
                            "background": config.theme_config.get("surface", "#FFFFFF"),
                            "elevation": "8",
                        },
                        "components": self._generate_bottom_nav_items(
                            config.navigation_items
                        ),
                    },
                ],
            }
        }

    def _generate_top_navigation(
        self, config: NavigationConfig, project_context: ProjectContext
    ) -> Dict[str, Any]:
        """Generate top navigation layout."""

        return {
            "container": {
                "type": "ColumnPanel",
                "properties": {"role": "top-nav-layout"},
                "components": [
                    {
                        "name": "top_navigation",
                        "type": "LinearPanel",
                        "properties": {
                            "align": "space_between",
                            "spacing": "medium",
                            "padding": "16px",
                            "role": "top-navigation",
                            "background": config.theme_config.get("surface", "#FFFFFF"),
                            "elevation": "2",
                        },
                        "components": [
                            {
                                "name": "nav_brand",
                                "type": "LinearPanel",
                                "properties": {"align": "center", "spacing": "small"},
                                "components": [
                                    {
                                        "name": "app_logo_nav",
                                        "type": "Image",
                                        "properties": {
                                            "source": config.app_logo,
                                            "height": "32px",
                                            "width": "32px",
                                            "role": "app-logo",
                                        },
                                    },
                                    {
                                        "name": "app_title_nav",
                                        "type": "Label",
                                        "properties": {
                                            "text": config.app_name,
                                            "font_size": "18px",
                                            "font_weight": "bold",
                                            "role": "title-large",
                                        },
                                    },
                                ],
                            },
                            {
                                "name": "nav_links",
                                "type": "LinkPanel",
                                "properties": {
                                    "role": "navigation-list",
                                    "spacing": "medium",
                                },
                                "components": self._generate_top_nav_items(
                                    config.navigation_items
                                ),
                            },
                            {
                                "name": "nav_actions",
                                "type": "LinearPanel",
                                "properties": {"align": "right", "spacing": "small"},
                                "components": self._generate_user_menu_items(
                                    config.user_menu
                                ),
                            },
                        ],
                    },
                    {
                        "name": "main_content",
                        "type": "ColumnPanel",
                        "properties": {"role": "main-content", "padding": "20px"},
                    },
                ],
            }
        }

    def _generate_navigation_items(
        self, navigation_items: List[Dict[str, Any]]
    ) -> List[Dict[str, Any]]:
        """Generate navigation items for drawer/rail."""

        items = []
        for item in navigation_items:
            nav_item = {
                "name": f"nav_{item['id']}",
                "type": "Link",
                "properties": {
                    "text": item["text"],
                    "icon": item.get("icon", "fa:circle"),
                    "url": item["url"],
                    "role": "navigation-item",
                    "tooltip": item.get("tooltip", item["text"]),
                },
            }

            if item.get("badge"):
                nav_item["properties"]["badge"] = item["badge"]

            if item.get("active"):
                nav_item["properties"]["bold"] = True

            items.append(nav_item)

        return items

    def _generate_rail_navigation_items(
        self, navigation_items: List[Dict[str, Any]]
    ) -> List[Dict[str, Any]]:
        """Generate navigation items for rail (compact)."""

        items = []
        for item in navigation_items:
            nav_item = {
                "name": f"rail_{item['id']}",
                "type": "Link",
                "properties": {
                    "icon": item.get("icon", "fa:circle"),
                    "url": item["url"],
                    "role": "navigation-item",
                    "tooltip": item.get("tooltip", item["text"]),
                    "show_text": False,
                },
            }

            if item.get("badge"):
                nav_item["properties"]["badge"] = item["badge"]

            if item.get("active"):
                nav_item["properties"]["bold"] = True

            items.append(nav_item)

        return items

    def _generate_bottom_nav_items(
        self, navigation_items: List[Dict[str, Any]]
    ) -> List[Dict[str, Any]]:
        """Generate bottom navigation items."""

        items = []
        for item in navigation_items[:5]:  # Limit to 5 items for bottom nav
            nav_item = {
                "name": f"bottom_{item['id']}",
                "type": "Link",
                "properties": {
                    "icon": item.get("icon", "fa:circle"),
                    "url": item["url"],
                    "role": "navigation-item",
                    "tooltip": item.get("tooltip", item["text"]),
                    "show_text": True,
                    "size": "small",
                },
            }

            if item.get("badge"):
                nav_item["properties"]["badge"] = item["badge"]

            if item.get("active"):
                nav_item["properties"]["bold"] = True

            items.append(nav_item)

        return items

    def _generate_top_nav_items(
        self, navigation_items: List[Dict[str, Any]]
    ) -> List[Dict[str, Any]]:
        """Generate top navigation items."""

        items = []
        for item in navigation_items:
            nav_item = {
                "name": f"top_{item['id']}",
                "type": "Link",
                "properties": {
                    "text": item["text"],
                    "url": item["url"],
                    "role": "navigation-item",
                    "tooltip": item.get("tooltip", item["text"]),
                },
            }

            if item.get("active"):
                nav_item["properties"]["bold"] = True

            items.append(nav_item)

        return items

    def _generate_user_menu_items(
        self, user_menu: List[Dict[str, Any]]
    ) -> List[Dict[str, Any]]:
        """Generate user menu items."""

        items = []
        for item in user_menu:
            menu_item = {
                "name": f"user_{item['id']}",
                "type": "Link",
                "properties": {
                    "text": item["text"],
                    "icon": item.get("icon", "fa:user"),
                    "url": item["url"],
                    "role": "user-menu-item",
                    "tooltip": item.get("tooltip", item["text"]),
                },
            }

            if item.get("divider"):
                items.append(
                    {
                        "name": f"divider_{item['id']}",
                        "type": "Divider",
                        "properties": {"role": "menu-divider"},
                    }
                )

            items.append(menu_item)

        return items

    def _create_route_integration(
        self, config: NavigationConfig, project_context: ProjectContext
    ) -> Dict[str, Any]:
        """Create route integration configuration."""

        return {
            "navigation_type": config.navigation_type,
            "route_mappings": {
                item["id"]: {
                    "url": item["url"],
                    "component": item.get("component"),
                    "guard": item.get("guard"),
                    "title": item["text"],
                }
                for item in config.navigation_items
            },
            "user_menu_mappings": {
                item["id"]: {
                    "url": item["url"],
                    "action": item.get("action"),
                    "title": item["text"],
                }
                for item in config.user_menu
            },
            "navigation_events": [
                "navigation_item_click",
                "user_menu_click",
                "navigation_toggle",
            ],
        }

    def _create_responsive_breakpoints(
        self, config: NavigationConfig
    ) -> Dict[str, Any]:
        """Create responsive breakpoints configuration."""

        return {
            "breakpoints": {
                "mobile": "0px",
                "tablet": "768px",
                "desktop": "1024px",
                "large": "1440px",
            },
            "navigation_behavior": {
                "mobile": "bottom"
                if config.navigation_type == "drawer"
                else config.navigation_type,
                "tablet": config.navigation_type,
                "desktop": config.navigation_type,
                "large": config.navigation_type,
            },
            "transitions": {
                "enabled": True,
                "duration": "300ms",
                "easing": "ease-in-out",
            },
        }

    def _create_accessibility_features(
        self, config: NavigationConfig
    ) -> List[Dict[str, Any]]:
        """Create accessibility features configuration."""

        return [
            {
                "feature": "keyboard_navigation",
                "enabled": True,
                "description": "Full keyboard navigation support",
                "implementation": {
                    "tab_index": True,
                    "arrow_keys": True,
                    "escape_key": True,
                    "focus_management": True,
                },
            },
            {
                "feature": "screen_reader",
                "enabled": True,
                "description": "Screen reader compatibility",
                "implementation": {
                    "aria_labels": True,
                    "aria_describedby": True,
                    "role_attributes": True,
                    "live_regions": True,
                },
            },
            {
                "feature": "high_contrast",
                "enabled": True,
                "description": "High contrast mode support",
                "implementation": {
                    "color_adjustments": True,
                    "focus_indicators": True,
                    "text_scaling": True,
                },
            },
            {
                "feature": "reduced_motion",
                "enabled": True,
                "description": "Reduced motion support",
                "implementation": {
                    "respect_prefers_reduced_motion": True,
                    "disable_animations": True,
                    "instant_transitions": True,
                },
            },
        ]

    def _generate_layout_yaml(self, nav_spec: NavigationSpec, output_path: str) -> None:
        """Generate layout YAML file."""

        base_path = Path(output_path)
        layout_name = f"{nav_spec.config.navigation_type.title()}Navigation"

        # Convert to YAML string
        yaml_content = self._build_yaml_from_dict(nav_spec.layout_yaml)

        self.file_system.write_text(
            str(base_path / f"{layout_name}.yaml"), yaml_content
        )

    def _generate_route_integration(
        self, nav_spec: NavigationSpec, output_path: str
    ) -> None:
        """Generate route integration file."""

        base_path = Path(output_path)

        route_integration_code = f'''"""Navigation Route Integration for {nav_spec.config.navigation_type} navigation."""

import anvil
from anvil import routing
from anvil.reactive import signal, reactive_class

@reactive_class
class NavigationController:
    """Controller for {nav_spec.config.navigation_type} navigation."""
    
    def __init__(self):
        self.is_open = signal(False)
        self.current_route = signal("/")
        self.user_menu_open = signal(False)
        
        # Route mappings
        self.route_mappings = {nav_spec.route_integration["route_mappings"]}
        self.user_menu_mappings = {nav_spec.route_integration["user_menu_mappings"]}
    
    def toggle_navigation(self):
        """Toggle navigation drawer/rail."""
        self.is_open.set(not self.is_open.get())
    
    def open_navigation(self):
        """Open navigation."""
        self.is_open.set(True)
    
    def close_navigation(self):
        """Close navigation."""
        self.is_open.set(False)
    
    def navigate_to(self, route_id: str):
        """Navigate to route by ID."""
        if route_id in self.route_mappings:
            route_info = self.route_mappings[route_id]
            routing.go(route_info["url"])
            self.current_route.set(route_info["url"])
    
    def handle_user_menu_action(self, action_id: str):
        """Handle user menu action."""
        if action_id in self.user_menu_mappings:
            action_info = self.user_menu_mappings[action_id]
            if action_info.get("action"):
                # Execute action
                pass
    
    def is_current_route(self, route_id: str) -> bool:
        """Check if route is currently active."""
        if route_id in self.route_mappings:
            return self.current_route.get() == self.route_mappings[route_id]["url"]
        return False
    
    def get_route_badge(self, route_id: str) -> str:
        """Get badge count for route."""
        # TODO: Implement badge logic
        return ""
    
    def update_navigation_state(self):
        """Update navigation state based on current route."""
        current_url = routing.get_url()
        self.current_route.set(current_url)
        
        # Update navigation item states
        for route_id, route_info in self.route_mappings.items():
            is_active = current_url == route_info["url"]
            # Update UI components accordingly
            pass

# Global navigation controller
navigation_controller = NavigationController()
'''

        self.file_system.write_text(
            str(base_path / "navigation_controller.py"), route_integration_code
        )

    def _generate_responsive_config(
        self, nav_spec: NavigationSpec, output_path: str
    ) -> None:
        """Generate responsive configuration file."""

        base_path = Path(output_path)

        responsive_config = nav_spec.responsive_breakpoints
        responsive_config["navigation_type"] = nav_spec.config.navigation_type
        responsive_config["generated_at"] = "2024-01-01T00:00:00Z"

        self.file_system.write_text(
            str(base_path / "responsive_config.json"),
            json.dumps(responsive_config, indent=2, default=str),
        )

    def _generate_accessibility_features(
        self, nav_spec: NavigationSpec, output_path: str
    ) -> None:
        """Generate accessibility features file."""

        base_path = Path(output_path)

        accessibility_config = {
            "navigation_type": nav_spec.config.navigation_type,
            "features": nav_spec.accessibility_features,
            "generated_at": "2024-01-01T00:00:00Z",
        }

        self.file_system.write_text(
            str(base_path / "accessibility_config.json"),
            json.dumps(accessibility_config, indent=2, default=str),
        )

    def _generate_navigation_controller(
        self, nav_spec: NavigationSpec, output_path: str
    ) -> None:
        """Generate navigation controller with event handlers."""

        base_path = Path(output_path)

        controller_code = f'''"""Navigation Controller Event Handlers."""

import anvil
from anvil import routing
from .navigation_controller import navigation_controller

class NavigationEventHandler:
    """Handle navigation events."""
    
    def __init__(self):
        self.controller = navigation_controller
    
    def handle_navigation_click(self, route_id: str, **event_args):
        """Handle navigation item click."""
        self.controller.navigate_to(route_id)
    
    def handle_user_menu_click(self, action_id: str, **event_args):
        """Handle user menu click."""
        self.controller.handle_user_menu_action(action_id)
    
    def handle_menu_toggle(self, **event_args):
        """Handle menu toggle."""
        self.controller.toggle_navigation()
    
    def handle_route_change(self, **event_args):
        """Handle route change event."""
        self.controller.update_navigation_state()
    
    def handle_keyboard_navigation(self, key: str, **event_args):
        """Handle keyboard navigation."""
        if key == "Escape":
            self.controller.close_navigation()
        elif key == "Enter":
            # Activate focused item
            pass
        elif key in ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"]:
            # Navigate between items
            pass
    
    def handle_accessibility_toggle(self, feature: str, enabled: bool, **event_args):
        """Handle accessibility feature toggle."""
        # Implement accessibility feature toggles
        pass

# Global event handler
nav_event_handler = NavigationEventHandler()

# Register event handlers
def register_navigation_handlers():
    """Register navigation event handlers."""
    # Register with routing system
    routing.add_route_change_handler(nav_event_handler.handle_route_change)
    
    # Register keyboard handlers
    anvil.register_key_handler("Escape", nav_event_handler.handle_keyboard_navigation)
    anvil.register_key_handler("Enter", nav_event_handler.handle_keyboard_navigation)
    anvil.register_key_handler("ArrowUp", nav_event_handler.handle_keyboard_navigation)
    anvil.register_key_handler("ArrowDown", nav_event_handler.handle_keyboard_navigation)
    anvil.register_key_handler("ArrowLeft", nav_event_handler.handle_keyboard_navigation)
    anvil.register_key_handler("ArrowRight", nav_event_handler.handle_keyboard_navigation)
'''

        self.file_system.write_text(
            str(base_path / "navigation_events.py"), controller_code
        )

    def _build_yaml_from_dict(self, data: Dict[str, Any]) -> str:
        """Build YAML string from dictionary with proper formatting."""
        import yaml

        return yaml.dump(data, default_flow_style=False, indent=2, sort_keys=False)
