import 'package:core/core.dart';
import 'package:feature_inventory/feature_inventory.dart';
import 'package:feature_orders/feature_orders.dart';
import 'package:feature_policy/feature_policy.dart';
import 'package:flutter/material.dart';

import '../composition/mobile_app_services.dart';
import '../dashboard/application/dashboard_controller.dart';
import '../dashboard/application/get_dashboard_summary.dart';
import '../pages/dashboard_page.dart';
import '../pages/finance_placeholder_page.dart';
import '../pages/integrations_placeholder_page.dart';
import '../pages/mobile_publishing_page.dart';

/// The main shell for the mobile app.
///
/// Uses a [Scaffold] with a [NavigationBar] (Material 3 bottom navigation)
/// to provide top-level section navigation. This is the mobile equivalent
/// of `kell_web`'s [AppShell] which uses a [NavigationRail].
///
/// Unlike the web app which uses named routes, the mobile shell uses
/// index-based tab switching with a stateful body to preserve tab state.
class MobileShell extends StatefulWidget {
  const MobileShell({super.key});

  @override
  State<MobileShell> createState() => _MobileShellState();
}

class _MobileShellState extends State<MobileShell> {
  int _selectedIndex = 0;

  static const _titles = ['Dashboard', 'Inventory', 'Products', 'Orders', 'More'];

  @override
  Widget build(BuildContext context) {
    final config = KcAppScope.configOf<MobileAppServices>(context);

    return Scaffold(
      appBar: AppBar(
        title: Text(_titles[_selectedIndex]),
        actions: [
          _EnvironmentBadge(environment: config.environment),
          const SizedBox(width: 12),
        ],
      ),
      body: _buildBody(context),
      bottomNavigationBar: NavigationBar(
        selectedIndex: _selectedIndex,
        onDestinationSelected: (index) {
          setState(() => _selectedIndex = index);
        },
        destinations: const [
          NavigationDestination(
            icon: Icon(Icons.dashboard_outlined),
            selectedIcon: Icon(Icons.dashboard),
            label: 'Dashboard',
          ),
          NavigationDestination(
            icon: Icon(Icons.inventory_2_outlined),
            selectedIcon: Icon(Icons.inventory_2),
            label: 'Inventory',
          ),
          NavigationDestination(
            icon: Icon(Icons.sell_outlined),
            selectedIcon: Icon(Icons.sell),
            label: 'Products',
          ),
          NavigationDestination(
            icon: Icon(Icons.receipt_long_outlined),
            selectedIcon: Icon(Icons.receipt_long),
            label: 'Orders',
          ),
          NavigationDestination(
            icon: Icon(Icons.more_horiz),
            selectedIcon: Icon(Icons.more_horiz),
            label: 'More',
          ),
        ],
      ),
    );
  }

  Widget _buildBody(BuildContext context) {
    final services = KcAppScope.of<MobileAppServices>(context);

    switch (_selectedIndex) {
      case 0:
        return MobileDashboardPage(
          controller: DashboardController(
            GetDashboardSummary(
              inventoryRepository: services.inventoryRepository,
              productPublishingRepository: services.productPublishingRepository,
              ordersRepository: services.ordersRepository,
            ),
          ),
        );
      case 1:
        return InventoryPage(
          repository: services.inventoryRepository,
          onViewProduct: (_) {
            // Cross-feature nav: switch to Products tab.
            setState(() => _selectedIndex = 2);
          },
        );
      case 2:
        return MobilePublishingPage(repository: services.productPublishingRepository);
      case 3:
        return OrdersPage(
          repository: services.ordersRepository,
          onViewProduct: (_) {
            setState(() => _selectedIndex = 2);
          },
          onViewInventory: (_) {
            setState(() => _selectedIndex = 1);
          },
        );
      case 4:
        return const _MorePage();
      default:
        return const Center(child: Text('Unknown section'));
    }
  }
}

/// A simple "More" page that provides access to less frequently used sections.
class _MorePage extends StatelessWidget {
  const _MorePage();

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: [
        ListTile(
          leading: const Icon(Icons.attach_money),
          title: const Text('Finance'),
          trailing: const Icon(Icons.chevron_right),
          onTap: () {
            Navigator.of(context).push(
              MaterialPageRoute<void>(
                builder: (_) => Scaffold(
                  appBar: AppBar(title: const Text('Finance')),
                  body: const FinancePlaceholderPage(),
                ),
              ),
            );
          },
        ),
        ListTile(
          leading: const Icon(Icons.policy),
          title: const Text('Policy'),
          trailing: const Icon(Icons.chevron_right),
          onTap: () {
            final services = KcAppScope.of<MobileAppServices>(context);
            Navigator.of(context).push(
              MaterialPageRoute<void>(
                builder: (_) => Scaffold(
                  appBar: AppBar(title: const Text('Policy')),
                  body: PolicyPage(
                    repository: services.policyRepository,
                    onViewRelatedPage: (_) {},
                  ),
                ),
              ),
            );
          },
        ),
        ListTile(
          leading: const Icon(Icons.hub),
          title: const Text('Integrations'),
          trailing: const Icon(Icons.chevron_right),
          onTap: () {
            Navigator.of(context).push(
              MaterialPageRoute<void>(
                builder: (_) => Scaffold(
                  appBar: AppBar(title: const Text('Integrations')),
                  body: const IntegrationsPlaceholderPage(),
                ),
              ),
            );
          },
        ),
      ],
    );
  }
}

/// A small coloured chip displayed in the [AppBar] that shows the current
/// runtime environment (e.g. "FAKE" or "WP").
class _EnvironmentBadge extends StatelessWidget {
  final KcAppEnvironment environment;

  const _EnvironmentBadge({required this.environment});

  @override
  Widget build(BuildContext context) {
    final Color backgroundColor;
    final Color foregroundColor;

    switch (environment) {
      case KcAppEnvironment.fake:
        backgroundColor = Colors.orange.shade100;
        foregroundColor = Colors.orange.shade900;
      case KcAppEnvironment.wordpress:
        backgroundColor = Colors.green.shade100;
        foregroundColor = Colors.green.shade900;
    }

    return Center(
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
        decoration: BoxDecoration(color: backgroundColor, borderRadius: BorderRadius.circular(4)),
        child: Text(
          environment.label,
          style: Theme.of(context).textTheme.labelSmall?.copyWith(
            color: foregroundColor,
            fontWeight: FontWeight.bold,
            letterSpacing: 1.2,
          ),
        ),
      ),
    );
  }
}
