import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import '../../core/theme/app_spacing.dart';

/// 现代底部抽屉模板 - 基于 modernization-v2.md 规范
///
/// 使用方法：
/// ```dart
/// ModernBottomSheet.show(
///   context: context,
///   title: '选择币种',
///   child: YourContentWidget(),
/// );
/// ```
class ModernBottomSheet extends StatelessWidget {
  final String? title;
  final Widget? titleWidget;
  final Widget child;
  final double? height;
  final bool showDragHandle;
  final bool showCloseButton;
  final VoidCallback? onClose;

  const ModernBottomSheet({
    super.key,
    this.title,
    this.titleWidget,
    required this.child,
    this.height,
    this.showDragHandle = true,
    this.showCloseButton = false,
    this.onClose,
  });

  /// 显示底部抽屉
  static Future<T?> show<T>({
    required BuildContext context,
    String? title,
    Widget? titleWidget,
    required Widget child,
    double? height,
    bool showDragHandle = true,
    bool showCloseButton = false,
    bool isScrollControlled = true,
    bool isDismissible = true,
    bool enableDrag = true,
  }) {
    return showModalBottomSheet<T>(
      context: context,
      isScrollControlled: isScrollControlled,
      isDismissible: isDismissible,
      enableDrag: enableDrag,
      backgroundColor: Colors.transparent,
      builder: (context) => ModernBottomSheet(
        title: title,
        titleWidget: titleWidget,
        child: child,
        height: height,
        showDragHandle: showDragHandle,
        showCloseButton: showCloseButton,
      ),
    );
  }

  /// 显示操作列表
  static Future<T?> showActions<T>({
    required BuildContext context,
    String? title,
    required List<ModernSheetAction> actions,
  }) {
    return show(
      context: context,
      title: title,
      child: _ActionList(actions: actions),
    );
  }

  /// 显示确认操作
  static Future<bool> confirmAction({
    required BuildContext context,
    required String title,
    String? description,
    String confirmText = '确认',
    String cancelText = '取消',
    bool isDestructive = false,
  }) async {
    final result = await show<int>(
      context: context,
      title: title,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          if (description != null) ...[
            Text(
              description,
              style: Theme.of(context).textTheme.bodyMedium,
            ),
            const SizedBox(height: AppSpacing.lg),
          ],
          Row(
            children: [
              Expanded(
                child: ShadButton.outline(
                  onPressed: () => Navigator.of(context).pop(0),
                  child: Text(cancelText),
                ),
              ),
              const SizedBox(width: AppSpacing.md),
              Expanded(
                child: ShadButton(
                  backgroundColor: isDestructive
                    ? ShadTheme.of(context).colorScheme.destructive
                    : null,
                  onPressed: () => Navigator.of(context).pop(1),
                  child: Text(confirmText),
                ),
              ),
            ],
          ),
        ],
      ),
    );
    return result == 1;
  }

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    final bottomPadding = MediaQuery.of(context).padding.bottom;

    return Container(
      decoration: BoxDecoration(
        color: theme.colorScheme.card,
        borderRadius: const BorderRadius.vertical(
          top: Radius.circular(AppRadius.xxl),
        ),
      ),
      constraints: height != null
          ? BoxConstraints(maxHeight: height!)
          : null,
      child: SingleChildScrollView(
        child: Padding(
          padding: EdgeInsets.only(
            left: AppSpacing.lg,
            right: AppSpacing.lg,
            top: AppSpacing.md,
            bottom: bottomPadding + AppSpacing.lg,
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 拖动指示器
              if (showDragHandle) _buildDragHandle(theme),
              // 标题行
              if (title != null || titleWidget != null || showCloseButton)
                _buildHeader(context, theme),
              // 内容
              child,
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildDragHandle(ShadThemeData theme) {
    return Center(
      child: Container(
        width: 40,
        height: 4,
        margin: const EdgeInsets.only(bottom: AppSpacing.md),
        decoration: BoxDecoration(
          color: theme.colorScheme.muted,
          borderRadius: BorderRadius.circular(2),
        ),
      ),
    );
  }

  Widget _buildHeader(BuildContext context, ShadThemeData theme) {
    return Padding(
      padding: const EdgeInsets.only(bottom: AppSpacing.md),
      child: Row(
        children: [
          // 标题
          Expanded(
            child: titleWidget ?? Text(
              title!,
              style: theme.textTheme.h3.copyWith(
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
          // 关闭按钮
          if (showCloseButton)
            GestureDetector(
              onTap: () {
                Navigator.of(context).pop();
                onClose?.call();
              },
              child: Icon(
                LucideIcons.x,
                size: 20,
                color: theme.colorScheme.mutedForeground,
              ),
            ),
        ],
      ),
    );
  }
}

/// 操作列表
class _ActionList extends StatelessWidget {
  final List<ModernSheetAction> actions;

  const _ActionList({required this.actions});

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);

    return Column(
      children: actions.asMap().entries.map((entry) {
        final index = entry.key;
        final action = entry.value;

        return Column(
          children: [
            if (index > 0 && actions[index - 1].isDivider)
              Divider(color: theme.colorScheme.border, height: 1),
            _ActionTile(action: action),
          ],
        );
      }).toList(),
    );
  }
}

/// 操作项
class _ActionTile extends StatelessWidget {
  final ModernSheetAction action;

  const _ActionTile({required this.action});

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);

    return InkWell(
      onTap: () {
        Navigator.of(context).pop(action.returnValue);
        action.onPressed?.call();
      },
      child: Container(
        width: double.infinity,
        padding: const EdgeInsets.symmetric(
          horizontal: AppSpacing.md,
          vertical: AppSpacing.md,
        ),
        child: Row(
          children: [
            if (action.icon != null) ...[
              Icon(
                action.icon,
                size: 20,
                color: action.isDestructive
                    ? theme.colorScheme.destructive
                    : theme.colorScheme.foreground,
              ),
              const SizedBox(width: AppSpacing.md),
            ],
            Expanded(
              child: Text(
                action.label,
                style: TextStyle(
                  fontSize: 16,
                  color: action.isDestructive
                      ? theme.colorScheme.destructive
                      : theme.colorScheme.foreground,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

/// 底部抽屉操作配置
class ModernSheetAction {
  final String label;
  final IconData? icon;
  final dynamic returnValue;
  final bool isDestructive;
  final bool isDivider;
  final VoidCallback? onPressed;

  const ModernSheetAction({
    required this.label,
    this.icon,
    this.returnValue,
    this.isDestructive = false,
    this.isDivider = false,
    this.onPressed,
  });
}
