import 'dart:async';
import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';

class VendorSearchFilter extends StatefulWidget {
  final Function(String) onSearch;
  final Function(bool?) onFilterChanged;
  final VoidCallback onClearFilters;

  const VendorSearchFilter({
    super.key,
    required this.onSearch,
    required this.onFilterChanged,
    required this.onClearFilters,
  });

  @override
  State<VendorSearchFilter> createState() => _VendorSearchFilterState();
}

class _VendorSearchFilterState extends State<VendorSearchFilter> {
  final TextEditingController _searchController = TextEditingController();
  Timer? _debounceTimer;
  bool? _selectedStatus;
  bool _hasFilters = false;

  @override
  void dispose() {
    _searchController.dispose();
    _debounceTimer?.cancel();
    super.dispose();
  }

  void _onSearchChanged(String value) {
    // 디바운스 처리 (500ms)
    _debounceTimer?.cancel();
    _debounceTimer = Timer(const Duration(milliseconds: 500), () {
      widget.onSearch(value);
    });

    _updateHasFilters();
  }

  void _onStatusChanged(bool? value) {
    setState(() {
      _selectedStatus = value;
    });
    widget.onFilterChanged(value);
    _updateHasFilters();
  }

  void _clearFilters() {
    setState(() {
      _searchController.clear();
      _selectedStatus = null;
      _hasFilters = false;
    });
    _debounceTimer?.cancel();
    widget.onClearFilters();
  }

  void _updateHasFilters() {
    setState(() {
      _hasFilters =
          _searchController.text.isNotEmpty || _selectedStatus != null;
    });
  }

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

    return Row(
      children: [
        // 검색 입력
        Expanded(
          flex: 2,
          child: Row(
            children: [
              Icon(
                Icons.search,
                size: 16,
                color: theme.colorScheme.mutedForeground,
              ),
              const SizedBox(width: 8),
              Expanded(
                child: ShadInputFormField(
                  controller: _searchController,
                  placeholder: const Text('벤더명으로 검색'),
                  onChanged: _onSearchChanged,
                ),
              ),
              if (_searchController.text.isNotEmpty) ...[
                const SizedBox(width: 8),
                ShadButton.ghost(
                  onPressed: () {
                    _searchController.clear();
                    _onSearchChanged('');
                  },
                  size: ShadButtonSize.sm,
                  child: Icon(
                    Icons.clear,
                    size: 14,
                    color: theme.colorScheme.mutedForeground,
                  ),
                ),
              ],
            ],
          ),
        ),
        const SizedBox(width: 16),

        // 상태 필터
        SizedBox(
          width: 180,
          child: ShadSelect<bool?>(
            placeholder: const Text('상태 선택'),
            onChanged: _onStatusChanged,
            options: [
              ShadOption(value: null, child: const Text('전체')),
              ShadOption(value: true, child: const Text('활성')),
              ShadOption(value: false, child: const Text('비활성')),
            ],
            selectedOptionBuilder: (context, value) {
              String label = '';
              if (value == null) {
                label = '전체';
              } else if (value == true) {
                label = '활성';
              } else if (value == false) {
                label = '비활성';
              }

              return Row(
                children: [
                  if (value == true)
                    const Icon(
                      Icons.check_circle,
                      size: 14,
                      color: Color(0xFF10B981),
                    )
                  else if (value == false)
                    Icon(
                      Icons.cancel,
                      size: 14,
                      color: theme.colorScheme.mutedForeground,
                    )
                  else
                    Icon(
                      Icons.all_inclusive,
                      size: 14,
                      color: theme.colorScheme.foreground,
                    ),
                  const SizedBox(width: 8),
                  Text(label),
                ],
              );
            },
          ),
        ),
        const SizedBox(width: 16),

        // 필터 초기화 버튼
        if (_hasFilters)
          ShadButton.outline(
            onPressed: _clearFilters,
            size: ShadButtonSize.sm,
            child: Row(
              children: [
                Icon(Icons.filter_alt_off, size: 14),
                SizedBox(width: 4),
                Text('필터 초기화'),
              ],
            ),
          ),
      ],
    );
  }
}
