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

import '../application/get_policy_checks.dart';
import '../application/policy_controller.dart';
import '../domain/policy_repository.dart';
import 'widgets/policy_check_card.dart';
import 'widgets/policy_detail_panel.dart';

/// The main Policy page.
///
/// Displays a list of policy checks on the left and a detail panel on the
/// right. Users can select a check to view its full details.
class PolicyPage extends StatefulWidget {
  final PolicyRepository repository;

  /// Optional callback to navigate to a related operational page based on
  /// the policy check's category. Provided by the app layer.
  final void Function(String category)? onViewRelatedPage;

  /// Optional initial category filter to apply on first load
  /// (e.g. `'Product Compliance'`).
  final String? initialCategory;

  /// Optional initial search query to apply on first load.
  final String? initialQuery;

  /// Optional check ID to pre-select on first load (from a navigation handoff).
  final String? initialSelectedId;

  const PolicyPage({
    super.key,
    required this.repository,
    this.onViewRelatedPage,
    this.initialCategory,
    this.initialQuery,
    this.initialSelectedId,
  });

  @override
  State<PolicyPage> createState() => _PolicyPageState();
}

class _PolicyPageState extends State<PolicyPage> {
  late final PolicyController controller;

  @override
  void initState() {
    super.initState();
    controller = PolicyController(GetPolicyChecks(widget.repository));

    // Apply any initial category / query before loading.
    if (widget.initialCategory != null) {
      controller.activeCategory = widget.initialCategory;
    }
    if (widget.initialQuery != null && widget.initialQuery!.isNotEmpty) {
      controller.searchQuery = widget.initialQuery!;
    }

    controller.load().then((_) {
      // After data is loaded, try to pre-select by ID if requested.
      if (widget.initialSelectedId != null) {
        controller.selectById(widget.initialSelectedId!);
      }
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: controller,
      builder: (context, _) {
        if (controller.isLoading) {
          return const Center(child: CircularProgressIndicator());
        }

        if (controller.error != null) {
          return const Center(child: Text('Failed to load policy checks.'));
        }

        return LayoutBuilder(
          builder: (context, constraints) {
            // On narrow screens show only the list; on wide screens show
            // a master-detail layout.
            if (constraints.maxWidth < 800) {
              return _buildCheckList();
            }
            return Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(width: 400, child: _buildCheckList()),
                const SizedBox(width: KcSpacing.md),
                Expanded(child: _buildDetail()),
              ],
            );
          },
        );
      },
    );
  }

  Widget _buildCheckList() {
    return ListView.separated(
      itemCount: controller.checks.length,
      separatorBuilder: (_, _) => const SizedBox(height: KcSpacing.sm),
      itemBuilder: (context, index) {
        final check = controller.checks[index];
        return SizedBox(
          height: 160,
          child: PolicyCheckCard(
            check: check,
            isSelected: check.id == controller.selectedCheck?.id,
            onTap: () => controller.selectCheck(check),
          ),
        );
      },
    );
  }

  Widget _buildDetail() {
    final selected = controller.selectedCheck;
    if (selected == null) {
      return const Center(child: Text('Select a policy check to view details'));
    }
    return PolicyDetailPanel(check: selected, onViewRelatedPage: widget.onViewRelatedPage);
  }
}
