import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:recording_tool/features/recording/widgets/record_content_transition.dart';
import 'package:recording_tool/gen/assets.gen.dart';
import 'package:recording_tool/shared/widgets/app_toast.dart';

/// 录制页顶部：Logo、粘贴赛事、赛事标题
class RecordHeaderWidget extends StatelessWidget {
  const RecordHeaderWidget({
    super.key,
    required this.hasValidClipboardInfo,
    this.eventTitle,
    required this.isRecording,
    required this.onPasteEventInfo,
    required this.onClearEventInfo,
  });

  final bool hasValidClipboardInfo;
  final String? eventTitle;
  final bool isRecording;
  final Future<void> Function() onPasteEventInfo;
  final VoidCallback onClearEventInfo;

  bool get _showPasteButtons => !hasValidClipboardInfo && !isRecording;

  bool get _showEventTitle => hasValidClipboardInfo;

  Widget _buildAnimatedHeaderContent() {
    if (_showEventTitle) {
      return _HeaderEventTitleRow(
        key: ValueKey('title-${eventTitle ?? ''}'),
        title: eventTitle ?? '',
        isRecording: isRecording,
        onClearEventInfo: onClearEventInfo,
      );
    }

    return const SizedBox.shrink(key: ValueKey('header-empty'));
  }

  void _mockCopyEventInfo() {
    const strTemp =
        '{"title":"蔡依婷vs夏志豪 空中格斗赛 初中组","address":"黑龙江省鹤岗市11111","filename":"蔡依婷_夏志豪_测试循环赛-7_空中格斗赛"}';
    Clipboard.setData(const ClipboardData(text: strTemp));
    AppToast.show('模拟复制赛事信息成功');
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      bottom: false,
      child: SizedBox(
        height: 56.h,
        width: double.maxFinite,
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 12.w),
          child: Row(
            children: [
              Image.asset(
                Assets.images.imageLogo.path,
                width: 24.r,
                height: 24.r,
                fit: BoxFit.contain,
              ),
              Expanded(
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    AnimatedSwitcher(
                      duration: RecordContentTransition.duration,
                      switchInCurve: Curves.easeOutCubic,
                      switchOutCurve: Curves.easeInCubic,
                      layoutBuilder: RecordContentTransition.stackLayoutBuilder,
                      transitionBuilder: RecordContentTransition.builder,
                      child: _buildAnimatedHeaderContent(),
                    ),
                    if (_showPasteButtons)
                      Align(
                        alignment: Alignment.centerRight,
                        child: _HeaderPasteActions(
                          onMockCopy: _mockCopyEventInfo,
                          onPasteEventInfo: onPasteEventInfo,
                        ),
                      ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _HeaderEventTitleRow extends StatelessWidget {
  const _HeaderEventTitleRow({
    super.key,
    required this.title,
    required this.isRecording,
    required this.onClearEventInfo,
  });

  final String title;
  final bool isRecording;
  final VoidCallback onClearEventInfo;

  static TextStyle get _overlayTextStyle => TextStyle(
    color: Colors.white,
    shadows: [Shadow(color: Colors.black54, blurRadius: 6.r)],
  );

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Expanded(
          child: AnimatedSwitcher(
            duration: RecordContentTransition.duration,
            switchInCurve: Curves.easeOutCubic,
            switchOutCurve: Curves.easeInCubic,
            transitionBuilder: RecordContentTransition.builder,
            child: Text(
              title,
              key: ValueKey(title),
              style: _overlayTextStyle.copyWith(
                fontSize: 12.sp,
                fontWeight: FontWeight.w600,
              ),
              textAlign: TextAlign.center,
              maxLines: 3,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ),
        !isRecording
            ? IconButton(
                key: const ValueKey('clear-event-info'),
                onPressed: onClearEventInfo,
                icon: Assets.images.imageDelete.image(
                  width: 15.r,
                  height: 15.r,
                  fit: BoxFit.contain,
                  excludeFromSemantics: true,
                ),
                padding: EdgeInsets.zero,
                constraints: BoxConstraints(minWidth: 40.r, minHeight: 40.r),
                alignment: Alignment.centerRight,
                tooltip: '删除',
              )
            : const SizedBox.shrink(key: ValueKey('clear-event-info-hidden')),
      ],
    );
  }
}

class _HeaderPasteActions extends StatelessWidget {
  const _HeaderPasteActions({
    required this.onMockCopy,
    required this.onPasteEventInfo,
  });

  final VoidCallback onMockCopy;
  final Future<void> Function() onPasteEventInfo;

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        _HeaderActionButton(label: 'mock', onPressed: onMockCopy),
        _HeaderActionButton(
          label: '粘贴选手信息',
          onPressed: () => onPasteEventInfo(),
          icon: Assets.images.imageCopy.image(
            width: 10.r,
            height: 10.r,
            fit: BoxFit.contain,
            excludeFromSemantics: true,
          ),
        ),
      ],
    );
  }
}

class _HeaderActionButton extends StatelessWidget {
  const _HeaderActionButton({
    required this.label,
    required this.onPressed,
    this.icon,
  });

  final String label;
  final VoidCallback onPressed;
  final Widget? icon;

  @override
  Widget build(BuildContext context) {
    return TextButton.icon(
      onPressed: onPressed,
      icon: icon ?? Icon(Icons.content_paste, size: 10.r),
      label: Text(label),

      style: TextButton.styleFrom(
        minimumSize: Size.zero, // 取消 40dp 最小高度
        tapTargetSize: MaterialTapTargetSize.shrinkWrap, // 取消额外点击热区
        foregroundColor: Colors.white,
        backgroundColor: Colors.black.withValues(alpha: 0.5),
        textStyle: TextStyle(fontSize: 10.sp),
        padding: EdgeInsets.symmetric(horizontal: 7.r, vertical: 4.r),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(25.r),
          side: const BorderSide(color: Colors.white30),
        ),
      ),
    );
  }
}
