import 'dart:async';
import 'package:flutter/material.dart';
import 'package:lucide_icons/lucide_icons.dart';
import '../../theme/app_colors.dart';

class SakeDetailMemo extends StatefulWidget {
  final String? initialMemo;
  final ValueChanged<String> onUpdate;

  const SakeDetailMemo({
    super.key,
    required this.initialMemo,
    required this.onUpdate,
  });

  @override
  State<SakeDetailMemo> createState() => _SakeDetailMemoState();
}

class _SakeDetailMemoState extends State<SakeDetailMemo> {
  late final TextEditingController _controller;
  final FocusNode _focusNode = FocusNode();
  Timer? _debounce;

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController(text: widget.initialMemo ?? '');
    _focusNode.addListener(() {
      if (mounted) setState(() {}); // Rebuild to hide/show hint
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    _focusNode.dispose();
    _debounce?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final appColors = Theme.of(context).extension<AppColors>()!;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Icon(LucideIcons.fileText, size: 16, color: appColors.brandPrimary),
            const SizedBox(width: 8),
            Text(
              'メモ',
              style: Theme.of(context).textTheme.titleMedium?.copyWith(
                    fontWeight: FontWeight.bold,
                    color: Theme.of(context).brightness == Brightness.dark
                        ? Colors.white
                        : null,
                  ),
            ),
          ],
        ),
        const SizedBox(height: 12),
        TextField(
          controller: _controller,
          focusNode: _focusNode,
          maxLines: 4,
          decoration: InputDecoration(
            hintText: _focusNode.hasFocus ? '' : 'メモを入力後に自動保存', // Disappear on focus
            hintStyle: TextStyle(color: appColors.textTertiary),
            border: const OutlineInputBorder(),
            filled: true,
            fillColor: Theme.of(context).cardColor,
          ),
          onChanged: (value) {
            if (_debounce?.isActive ?? false) _debounce!.cancel();
            _debounce = Timer(const Duration(milliseconds: 500), () {
              widget.onUpdate(value);
            });
          },
        ),
      ],
    );
  }
}
