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

import '../dashboard/application/dashboard_controller.dart';
import '../dashboard/domain/dashboard_summary.dart';
import '../navigation/app_navigation.dart';
import '../routing/app_routes.dart';

/// The main dashboard page showing aggregated summary data.
///
/// Displays KPI cards (total products, in-stock, low-stock, draft, orders,
/// pending, active, revenue) and a quick-actions section. Data is loaded
/// from the [DashboardController] which aggregates across repositories.
class DashboardPage extends StatefulWidget {
  final DashboardController controller;

  const DashboardPage({super.key, required this.controller});

  @override
  State<DashboardPage> createState() => _DashboardPageState();
}

class _DashboardPageState extends State<DashboardPage> {
  @override
  void initState() {
    super.initState();
    widget.controller.addListener(_onControllerChanged);
    // Kick off the initial load.
    widget.controller.load();
  }

  @override
  void didUpdateWidget(DashboardPage oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.controller != widget.controller) {
      oldWidget.controller.removeListener(_onControllerChanged);
      widget.controller.addListener(_onControllerChanged);
      widget.controller.load();
    }
  }

  @override
  void dispose() {
    widget.controller.removeListener(_onControllerChanged);
    super.dispose();
  }

  void _onControllerChanged() => setState(() {});

  @override
  Widget build(BuildContext context) {
    final controller = widget.controller;

    if (controller.isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (controller.error != null) {
      return Center(
        child: Text('Failed to load dashboard data.', style: Theme.of(context).textTheme.bodyLarge),
      );
    }

    final summary = controller.summary;

    return ListView(
      children: [
        const KcSectionHeader(title: 'Overview'),
        const SizedBox(height: KcSpacing.sm),
        _buildSummaryGrid(context, summary),
        const SizedBox(height: KcSpacing.xl),
        KcSectionHeader(
          title: 'Quick Actions',
          action: TextButton(
            onPressed: () => Navigator.of(context).pushReplacementNamed(AppRoutes.inventory),
            child: const Text('Go to Inventory'),
          ),
        ),
        const SizedBox(height: KcSpacing.sm),
        _buildQuickActions(context),
        const SizedBox(height: KcSpacing.xl),
        const KcSectionHeader(title: 'Recent Activity'),
        const SizedBox(height: KcSpacing.sm),
        const KcEmptyState(
          icon: Icons.history,
          message:
              'No recent activity yet.\nActivity will appear here once orders and updates are tracked.',
        ),
      ],
    );
  }

  // ── Summary cards grid ─────────────────────────────────────────────────

  Widget _buildSummaryGrid(BuildContext context, DashboardSummary summary) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final width = constraints.maxWidth;

        int crossAxisCount = 2;
        if (width >= 900) {
          crossAxisCount = 4;
        } else if (width >= 600) {
          crossAxisCount = 2;
        }

        final cards = [
          KcSummaryCard(
            icon: Icons.inventory_2,
            iconColor: KcColors.denimBlue,
            label: 'Total Products',
            value: '${summary.totalProducts}',
            onTap: () => AppNavigation.dashboardToInventory(context),
          ),
          KcSummaryCard(
            icon: Icons.check_circle_outline,
            iconColor: KcColors.success,
            label: 'In Stock',
            value: '${summary.inStock}',
            onTap: () => AppNavigation.dashboardToInventory(context, filter: 'inStock'),
          ),
          KcSummaryCard(
            icon: Icons.warning_amber_rounded,
            iconColor: KcColors.warning,
            label: 'Low Stock',
            value: '${summary.lowStock}',
            onTap: () => AppNavigation.dashboardToInventory(context, filter: 'lowStock'),
          ),
          KcSummaryCard(
            icon: Icons.edit_note,
            iconColor: KcColors.neutral,
            label: 'Draft',
            value: '${summary.draftProducts}',
            onTap: () => AppNavigation.dashboardToProducts(context, filter: 'draft'),
          ),
          KcSummaryCard(
            icon: Icons.receipt_long,
            iconColor: KcColors.denimBlue,
            label: 'Total Orders',
            value: '${summary.totalOrders}',
            onTap: () => AppNavigation.dashboardToOrders(context),
          ),
          KcSummaryCard(
            icon: Icons.hourglass_empty,
            iconColor: KcColors.warning,
            label: 'Pending Orders',
            value: '${summary.pendingOrders}',
            onTap: () => AppNavigation.dashboardToOrders(context, filter: 'pending'),
          ),
          KcSummaryCard(
            icon: Icons.local_shipping_outlined,
            iconColor: KcColors.success,
            label: 'Active Orders',
            value: '${summary.activeOrders}',
            onTap: () => AppNavigation.dashboardToOrders(context, filter: 'active'),
          ),
          KcSummaryCard(
            icon: Icons.attach_money,
            iconColor: KcColors.success,
            label: 'Revenue',
            value: '\$${summary.deliveredRevenue.toStringAsFixed(2)}',
            onTap: () => AppNavigation.dashboardToFinance(context),
          ),
        ];

        return GridView.count(
          crossAxisCount: crossAxisCount,
          crossAxisSpacing: KcSpacing.md,
          mainAxisSpacing: KcSpacing.md,
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          childAspectRatio: 1.8,
          children: cards,
        );
      },
    );
  }

  // ── Quick actions ──────────────────────────────────────────────────────

  Widget _buildQuickActions(BuildContext context) {
    return KcCard(
      child: Wrap(
        spacing: KcSpacing.sm,
        runSpacing: KcSpacing.sm,
        children: [
          _QuickActionChip(
            icon: Icons.add,
            label: 'New Product',
            onPressed: () => Navigator.of(context).pushReplacementNamed(AppRoutes.products),
          ),
          _QuickActionChip(
            icon: Icons.inventory_2_outlined,
            label: 'View Inventory',
            onPressed: () => Navigator.of(context).pushReplacementNamed(AppRoutes.inventory),
          ),
          _QuickActionChip(
            icon: Icons.receipt_long_outlined,
            label: 'View Orders',
            onPressed: () => Navigator.of(context).pushReplacementNamed(AppRoutes.orders),
          ),
        ],
      ),
    );
  }
}

// ── Private helper widget ──────────────────────────────────────────────────

class _QuickActionChip extends StatelessWidget {
  final IconData icon;
  final String label;
  final VoidCallback onPressed;

  const _QuickActionChip({required this.icon, required this.label, required this.onPressed});

  @override
  Widget build(BuildContext context) {
    return ActionChip(avatar: Icon(icon, size: 18), label: Text(label), onPressed: onPressed);
  }
}
