import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:recording_tool/core/utils/date_time_formatter.dart';
import 'package:recording_tool/features/recording/widgets/record_content_transition.dart';

/// 左下角实时时钟与赛事场地信息。
class RecordingContextClockChipWidget extends StatefulWidget {
  const RecordingContextClockChipWidget({super.key, required this.address});

  final String address;

  @override
  State<RecordingContextClockChipWidget> createState() =>
      _RecordingContextClockChipWidgetState();
}

class _RecordingContextClockChipWidgetState
    extends State<RecordingContextClockChipWidget> {
  Timer? _clockTimer;

  static TextStyle get _textStyle => TextStyle(
    color: Colors.white,
    fontSize: 12.sp,
    height: 1.4,
    shadows: [Shadow(color: Colors.black54, blurRadius: 6.r)],
  );

  @override
  void initState() {
    super.initState();
    _clockTimer = Timer.periodic(const Duration(seconds: 1), (_) {
      if (mounted) setState(() {});
    });
  }

  @override
  void dispose() {
    _clockTimer?.cancel();
    _clockTimer = null;
    super.dispose();
  }

  String get _nowText =>
      DateTimeFormatter.format(DateTime.now(), pattern: 'yyyy-M-d-H:mm:ss');

  @override
  Widget build(BuildContext context) {
    return AnimatedSize(
      duration: RecordContentTransition.duration,
      curve: Curves.easeOutCubic,
      alignment: Alignment.topLeft,
      clipBehavior: Clip.none,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(_nowText, style: _textStyle),
          AnimatedSwitcher(
            duration: RecordContentTransition.duration,
            switchInCurve: Curves.easeOutCubic,
            switchOutCurve: Curves.easeInCubic,
            layoutBuilder: RecordContentTransition.bottomStackLayoutBuilder,
            transitionBuilder: RecordContentTransition.builder,
            child: widget.address.isNotEmpty
                ? Text(
                    widget.address,
                    key: ValueKey(widget.address),
                    style: _textStyle,
                  )
                : const SizedBox.shrink(
                    key: ValueKey('recording-address-empty'),
                  ),
          ),
        ],
      ),
    );
  }
}
