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

class ZipcodeSearchFilter extends StatefulWidget {
  final Function(String) onSearch;
  final Function(String?) onSidoChanged;
  final Function(String?) onGuChanged;
  final VoidCallback onClearFilters;
  final List<String> sidoList;
  final List<String> guList;
  final String? selectedSido;
  final String? selectedGu;

  const ZipcodeSearchFilter({
    super.key,
    required this.onSearch,
    required this.onSidoChanged,
    required this.onGuChanged,
    required this.onClearFilters,
    required this.sidoList,
    required this.guList,
    this.selectedSido,
    this.selectedGu,
  });

  @override
  State<ZipcodeSearchFilter> createState() => _ZipcodeSearchFilterState();
}

class _ZipcodeSearchFilterState extends State<ZipcodeSearchFilter> {
  final TextEditingController _searchController = TextEditingController();
  Timer? _debounceTimer;
  bool _hasFilters = false;

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

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

  void _onSidoChanged(String? value) {
    widget.onSidoChanged(value);
    _updateHasFilters();
  }

  void _onGuChanged(String? value) {
    widget.onGuChanged(value);
    _updateHasFilters();
  }

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

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

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

    return Column(
      children: [
        // 첫 번째 행: 검색 입력
        Row(
          children: [
            // 검색 입력
            Expanded(
              flex: 3,
              child: Row(
                children: [
                  Icon(
                    Icons.search,
                    size: 18,
                    color: theme.colorScheme.mutedForeground,
                  ),
                  const SizedBox(width: 12),
                  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: 16,
                        color: theme.colorScheme.mutedForeground,
                      ),
                    ),
                  ],
                ],
              ),
            ),
            const SizedBox(width: 16),
            
            // 필터 초기화 버튼
            if (_hasFilters)
              ShadButton.outline(
                onPressed: _clearFilters,
                size: ShadButtonSize.sm,
                child: const Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(Icons.filter_alt_off, size: 16),
                    SizedBox(width: 6),
                    Text('초기화'),
                  ],
                ),
              ),
          ],
        ),
        const SizedBox(height: 16),
        
        // 두 번째 행: 시도/구 선택
        Row(
          children: [
            // 시도 선택
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '시도',
                    style: theme.textTheme.small?.copyWith(
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  const SizedBox(height: 6),
                  SizedBox(
                    width: double.infinity,
                    child: ShadSelect<String>(
                      placeholder: const Text('시도 선택'),
                      onChanged: _onSidoChanged,
                      options: [
                        const ShadOption(
                          value: null,
                          child: Text('전체'),
                        ),
                        ...widget.sidoList.map((sido) => ShadOption(
                          value: sido,
                          child: Text(sido),
                        )),
                      ],
                      selectedOptionBuilder: (context, value) {
                        return Row(
                          children: [
                            Icon(
                              Icons.location_city,
                              size: 16,
                              color: theme.colorScheme.primary,
                            ),
                            const SizedBox(width: 8),
                            Text(value ?? '전체'),
                          ],
                        );
                      },
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(width: 16),
            
            // 구 선택
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '구/군',
                    style: theme.textTheme.small?.copyWith(
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  const SizedBox(height: 6),
                  SizedBox(
                    width: double.infinity,
                    child: ShadSelect<String>(
                      placeholder: Text(
                        widget.selectedSido == null 
                            ? '시도를 먼저 선택하세요' 
                            : '구/군 선택'
                      ),
                      onChanged: widget.selectedSido != null ? _onGuChanged : null,
                      options: [
                        const ShadOption(
                          value: null,
                          child: Text('전체'),
                        ),
                        ...widget.guList.map((gu) => ShadOption(
                          value: gu,
                          child: Text(gu),
                        )),
                      ],
                      selectedOptionBuilder: (context, value) {
                        return Row(
                          children: [
                            Icon(
                              Icons.location_on,
                              size: 16,
                              color: widget.selectedSido != null 
                                  ? theme.colorScheme.primary 
                                  : theme.colorScheme.mutedForeground,
                            ),
                            const SizedBox(width: 8),
                            Text(value ?? '전체'),
                          ],
                        );
                      },
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(width: 16),
            
            // 빠른 검색 팁
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: theme.colorScheme.accent.withValues(alpha: 0.1),
                borderRadius: BorderRadius.circular(8),
                border: Border.all(
                  color: theme.colorScheme.accent.withValues(alpha: 0.2),
                ),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(
                    Icons.tips_and_updates_outlined,
                    size: 16,
                    color: theme.colorScheme.accent,
                  ),
                  const SizedBox(width: 6),
                  Text(
                    '팁: 우편번호나 동네 이름으로 빠르게 검색하세요',
                    style: theme.textTheme.small?.copyWith(
                      color: theme.colorScheme.accent,
                      fontSize: 11,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ],
    );
  }
}