// SPDX-FileCopyrightText: 2026 FocusFlow contributors
// SPDX-License-Identifier: AGPL-3.0-only

/// Renders Backlog board columns for the FocusFlow Flutter UI.
library;

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

import '../../theme/backlog_board_visual_tokens.dart';
import '../../theme/focus_flow_tokens.dart';
import 'backlog_task_card.dart';

/// Callback invoked when a Backlog task should become the selected task.
typedef BacklogTaskSelected = void Function(String taskId);

/// Callback invoked when the user requests a new task for a bucket.
typedef BacklogBucketAddRequested = void Function(BacklogBoardBucket bucket);

/// Board column containing a Backlog bucket header, task cards, and footer.
class BacklogBoardColumn extends StatelessWidget {
  /// Creates a Backlog board column.
  const BacklogBoardColumn({
    required this.column,
    required this.selectedTaskId,
    required this.onTaskSelected,
    required this.onAddTask,
    super.key,
  });

  /// Column read model supplied by scheduler core.
  final BacklogBoardColumnReadModel column;

  /// Currently selected task id, if any.
  final String? selectedTaskId;

  /// Selection callback for task cards.
  final BacklogTaskSelected onTaskSelected;

  /// Add-task callback shared by header and footer controls.
  final BacklogBucketAddRequested onAddTask;

  /// Builds the widget subtree for this component.
  /// The method translates the current widget configuration and state into Flutter UI without mutating scheduler domain data.
  @override
  Widget build(BuildContext context) {
    final accent = BacklogBoardVisualTokens.accentTokenColor(
      column.accentToken,
      fallbackBucket: column.bucket,
    );
    return DecoratedBox(
      decoration: BoxDecoration(
        color: FocusFlowTokens.panelBackground,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: accent.withValues(alpha: 0.64)),
        boxShadow: [
          BoxShadow(
            color: accent.withValues(alpha: 0.06),
            blurRadius: 28,
            spreadRadius: -10,
          ),
        ],
      ),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            BacklogColumnHeader(
              column: column,
              accent: accent,
              onAddTask: () {
                onAddTask(column.bucket);
              },
            ),
            const SizedBox(height: 14),
            Expanded(
              child: column.items.isEmpty
                  ? _EmptyColumnHint(accent: accent)
                  : ListView.separated(
                      padding: EdgeInsets.zero,
                      itemCount: column.items.length,
                      separatorBuilder: (context, index) =>
                          const SizedBox(height: 8),
                      itemBuilder: (context, index) {
                        final item = column.items[index];
                        return BacklogTaskCard(
                          item: item,
                          selected: item.taskId == selectedTaskId,
                          onTap: () {
                            onTaskSelected(item.taskId);
                          },
                        );
                      },
                    ),
            ),
            const SizedBox(height: 9),
            Align(
              alignment: Alignment.centerLeft,
              child: TextButton.icon(
                onPressed: () {
                  onAddTask(column.bucket);
                },
                icon: Icon(Icons.add, color: accent, size: 18),
                label: Text('Add task', style: TextStyle(color: accent)),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

/// Header for a Backlog board column.
class BacklogColumnHeader extends StatelessWidget {
  /// Creates a Backlog column header.
  const BacklogColumnHeader({
    required this.column,
    required this.accent,
    required this.onAddTask,
    super.key,
  });

  /// Column read model that supplies title, subtitle, bucket, and count.
  final BacklogBoardColumnReadModel column;

  /// Accent color resolved from the column token.
  final Color accent;

  /// Callback invoked by the header add button.
  final VoidCallback onAddTask;

  /// Builds the widget subtree for this component.
  /// The method translates the current widget configuration and state into Flutter UI without mutating scheduler domain data.
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Row(
          children: [
            Icon(
              BacklogBoardVisualTokens.bucketIcon(column.bucket),
              color: accent,
              size: 22,
            ),
            const SizedBox(width: 9),
            Expanded(
              child: Text(
                column.title,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: const TextStyle(
                  color: FocusFlowTokens.textPrimary,
                  fontSize: 14.5,
                  fontWeight: FontWeight.w800,
                ),
              ),
            ),
            const SizedBox(width: 8),
            _ColumnCountPill(label: '${column.count}', color: accent),
            const SizedBox(width: 4),
            IconButton(
              onPressed: onAddTask,
              icon: const Icon(Icons.add),
              color: FocusFlowTokens.textMuted,
              tooltip: 'Add task',
              iconSize: 18,
              visualDensity: VisualDensity.compact,
            ),
          ],
        ),
        const SizedBox(height: 7),
        Padding(
          padding: const EdgeInsets.only(left: 32),
          child: Text(
            column.subtitle,
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
            style: const TextStyle(
              color: FocusFlowTokens.textMuted,
              fontSize: 11,
              height: 1.25,
            ),
          ),
        ),
      ],
    );
  }
}

/// Small count pill used by Backlog column headers.
class _ColumnCountPill extends StatelessWidget {
  /// Creates a column count pill.
  const _ColumnCountPill({required this.label, required this.color});

  /// Count label.
  final String label;

  /// Accent color for the pill.
  final Color color;

  /// Builds the widget subtree for this component.
  /// The method translates the current widget configuration and state into Flutter UI without mutating scheduler domain data.
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.16),
        borderRadius: BorderRadius.circular(7),
      ),
      child: Text(
        label,
        style: TextStyle(
          color: color,
          fontSize: 11,
          fontWeight: FontWeight.w800,
        ),
      ),
    );
  }
}

/// Placeholder content for an empty board column.
class _EmptyColumnHint extends StatelessWidget {
  /// Creates an empty-column hint.
  const _EmptyColumnHint({required this.accent});

  /// Accent color for the empty state icon.
  final Color accent;

  /// Builds the widget subtree for this component.
  /// The method translates the current widget configuration and state into Flutter UI without mutating scheduler domain data.
  @override
  Widget build(BuildContext context) {
    return Center(
      child: DecoratedBox(
        decoration: BoxDecoration(
          color: FocusFlowTokens.elevatedPanel.withValues(alpha: 0.42),
          borderRadius: BorderRadius.circular(8),
          border: Border.all(
            color: FocusFlowTokens.subtleBorder.withValues(alpha: 0.62),
          ),
        ),
        child: Padding(
          padding: const EdgeInsets.all(14),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(Icons.inbox_outlined, color: accent, size: 22),
              const SizedBox(height: 8),
              const Text(
                'No tasks here',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: FocusFlowTokens.textMuted,
                  fontSize: 12,
                  fontWeight: FontWeight.w700,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
