import 'package:flutter/material.dart';
import 'autocomplete_dropdown.dart';
import 'form_field_wrapper.dart';
import 'category_data.dart';

// 카테고리 선택 필드 (대분류/중분류/소분류)
class CategorySelectionField extends StatefulWidget {
  final String category;
  final String subCategory;
  final String subSubCategory;
  final Function(String, String, String) onCategoryChanged;
  final bool isRequired;

  const CategorySelectionField({
    Key? key,
    required this.category,
    required this.subCategory,
    required this.subSubCategory,
    required this.onCategoryChanged,
    this.isRequired = false,
  }) : super(key: key);

  @override
  State<CategorySelectionField> createState() => _CategorySelectionFieldState();
}

class _CategorySelectionFieldState extends State<CategorySelectionField> {
  // 검색 관련 컨트롤러 및 상태 변수
  final TextEditingController _categoryController = TextEditingController();
  final FocusNode _categoryFocusNode = FocusNode();
  bool _showCategoryDropdown = false;
  List<String> _filteredCategories = [];

  // 중분류 관련 변수
  final TextEditingController _subCategoryController = TextEditingController();
  final FocusNode _subCategoryFocusNode = FocusNode();
  bool _showSubCategoryDropdown = false;
  List<String> _filteredSubCategories = [];

  // 소분류 관련 변수
  final TextEditingController _subSubCategoryController =
      TextEditingController();
  final FocusNode _subSubCategoryFocusNode = FocusNode();
  bool _showSubSubCategoryDropdown = false;
  List<String> _filteredSubSubCategories = [];

  List<String> _allCategories = [];
  String _selectedCategory = '';
  String _selectedSubCategory = '';
  String _selectedSubSubCategory = '';

  @override
  void initState() {
    super.initState();
    _selectedCategory = widget.category;
    _selectedSubCategory = widget.subCategory;
    _selectedSubSubCategory = widget.subSubCategory;
    _categoryController.text = _selectedCategory;
    _subCategoryController.text = _selectedSubCategory;
    _subSubCategoryController.text = _selectedSubSubCategory;

    // 모든 카테고리 목록 초기화
    _allCategories = categoryData.keys.toList();
    _filteredCategories = List.from(_allCategories);

    // 중분류 목록 초기화
    _updateSubCategories();

    // 소분류 목록 초기화
    _updateSubSubCategories();

    // 대분류 컨트롤러 리스너 설정
    _categoryController.addListener(_onCategoryTextChanged);
    _categoryFocusNode.addListener(() {
      setState(() {
        if (_categoryFocusNode.hasFocus) {
          _showCategoryDropdown = _filteredCategories.isNotEmpty;
        } else {
          _showCategoryDropdown = false;
        }
      });
    });

    // 중분류 컨트롤러 리스너 설정
    _subCategoryController.addListener(_onSubCategoryTextChanged);
    _subCategoryFocusNode.addListener(() {
      setState(() {
        if (_subCategoryFocusNode.hasFocus) {
          _showSubCategoryDropdown = _filteredSubCategories.isNotEmpty;
        } else {
          _showSubCategoryDropdown = false;
        }
      });
    });

    // 소분류 컨트롤러 리스너 설정
    _subSubCategoryController.addListener(_onSubSubCategoryTextChanged);
    _subSubCategoryFocusNode.addListener(() {
      setState(() {
        if (_subSubCategoryFocusNode.hasFocus) {
          _showSubSubCategoryDropdown = _filteredSubSubCategories.isNotEmpty;
        } else {
          _showSubSubCategoryDropdown = false;
        }
      });
    });
  }

  @override
  void dispose() {
    _categoryController.dispose();
    _categoryFocusNode.dispose();
    _subCategoryController.dispose();
    _subCategoryFocusNode.dispose();
    _subSubCategoryController.dispose();
    _subSubCategoryFocusNode.dispose();
    super.dispose();
  }

  // 중분류 목록 업데이트
  void _updateSubCategories() {
    if (_selectedCategory.isNotEmpty) {
      final subCategories =
          categoryData[_selectedCategory]?.keys.toList() ?? [];
      _filteredSubCategories = List.from(subCategories);
    } else {
      _filteredSubCategories = [];
    }
  }

  // 소분류 목록 업데이트
  void _updateSubSubCategories() {
    if (_selectedCategory.isNotEmpty && _selectedSubCategory.isNotEmpty) {
      final subSubCategories =
          categoryData[_selectedCategory]?[_selectedSubCategory] ?? [];
      _filteredSubSubCategories = List.from(subSubCategories);
    } else {
      _filteredSubSubCategories = [];
    }
  }

  void _onCategoryTextChanged() {
    final text = _categoryController.text;
    setState(() {
      _selectedCategory = text;

      if (text.isEmpty) {
        _filteredCategories = List.from(_allCategories);
      } else {
        _filteredCategories =
            _allCategories
                .where(
                  (item) => item.toLowerCase().contains(text.toLowerCase()),
                )
                .toList();

        // 시작 부분이 일치하는 항목 우선 정렬
        _filteredCategories.sort((a, b) {
          bool aStartsWith = a.toLowerCase().startsWith(text.toLowerCase());
          bool bStartsWith = b.toLowerCase().startsWith(text.toLowerCase());

          if (aStartsWith && !bStartsWith) return -1;
          if (!aStartsWith && bStartsWith) return 1;
          return a.compareTo(b);
        });
      }

      _showCategoryDropdown =
          _filteredCategories.isNotEmpty && _categoryFocusNode.hasFocus;

      // 카테고리가 변경되면 하위 카테고리 초기화
      if (_selectedCategory != widget.category) {
        _selectedSubCategory = '';
        _subCategoryController.text = '';
        _selectedSubSubCategory = '';
        _subSubCategoryController.text = '';
        _updateSubCategories();
        _updateSubSubCategories();
      }

      // 콜백 호출
      widget.onCategoryChanged(
        _selectedCategory,
        _selectedSubCategory,
        _selectedSubSubCategory,
      );
    });
  }

  // 중분류 텍스트 변경 핸들러
  void _onSubCategoryTextChanged() {
    final text = _subCategoryController.text;
    setState(() {
      _selectedSubCategory = text;

      if (_selectedCategory.isNotEmpty) {
        final subCategories =
            categoryData[_selectedCategory]?.keys.toList() ?? [];

        if (text.isEmpty) {
          _filteredSubCategories = List.from(subCategories);
        } else {
          _filteredSubCategories =
              subCategories
                  .where(
                    (item) => item.toLowerCase().contains(text.toLowerCase()),
                  )
                  .toList();

          // 시작 부분이 일치하는 항목 우선 정렬
          _filteredSubCategories.sort((a, b) {
            bool aStartsWith = a.toLowerCase().startsWith(text.toLowerCase());
            bool bStartsWith = b.toLowerCase().startsWith(text.toLowerCase());

            if (aStartsWith && !bStartsWith) return -1;
            if (!aStartsWith && bStartsWith) return 1;
            return a.compareTo(b);
          });
        }
      } else {
        _filteredSubCategories = [];
      }

      _showSubCategoryDropdown =
          _filteredSubCategories.isNotEmpty && _subCategoryFocusNode.hasFocus;

      // 중분류가 변경되면 소분류 초기화
      if (_selectedSubCategory != widget.subCategory) {
        _selectedSubSubCategory = '';
        _subSubCategoryController.text = '';
        _updateSubSubCategories();
      }

      // 콜백 호출
      widget.onCategoryChanged(
        _selectedCategory,
        _selectedSubCategory,
        _selectedSubSubCategory,
      );
    });
  }

  // 소분류 텍스트 변경 핸들러
  void _onSubSubCategoryTextChanged() {
    final text = _subSubCategoryController.text;
    setState(() {
      _selectedSubSubCategory = text;

      if (_selectedCategory.isNotEmpty && _selectedSubCategory.isNotEmpty) {
        final subSubCategories =
            categoryData[_selectedCategory]?[_selectedSubCategory] ?? [];

        if (text.isEmpty) {
          _filteredSubSubCategories = List.from(subSubCategories);
        } else {
          _filteredSubSubCategories =
              subSubCategories
                  .where(
                    (item) => item.toLowerCase().contains(text.toLowerCase()),
                  )
                  .toList();

          // 시작 부분이 일치하는 항목 우선 정렬
          _filteredSubSubCategories.sort((a, b) {
            bool aStartsWith = a.toLowerCase().startsWith(text.toLowerCase());
            bool bStartsWith = b.toLowerCase().startsWith(text.toLowerCase());

            if (aStartsWith && !bStartsWith) return -1;
            if (!aStartsWith && bStartsWith) return 1;
            return a.compareTo(b);
          });
        }
      } else {
        _filteredSubSubCategories = [];
      }

      _showSubSubCategoryDropdown =
          _filteredSubSubCategories.isNotEmpty &&
          _subSubCategoryFocusNode.hasFocus;

      // 콜백 호출
      widget.onCategoryChanged(
        _selectedCategory,
        _selectedSubCategory,
        _selectedSubSubCategory,
      );
    });
  }

  void _selectCategory(String category) {
    setState(() {
      _selectedCategory = category;
      _categoryController.text = category;
      _showCategoryDropdown = false;
      _selectedSubCategory = '';
      _subCategoryController.text = '';
      _selectedSubSubCategory = '';
      _subSubCategoryController.text = '';
      _updateSubCategories();
      _updateSubSubCategories();
      widget.onCategoryChanged(
        _selectedCategory,
        _selectedSubCategory,
        _selectedSubSubCategory,
      );
    });
  }

  // 중분류 선택 핸들러
  void _selectSubCategory(String subCategory) {
    setState(() {
      _selectedSubCategory = subCategory;
      _subCategoryController.text = subCategory;
      _showSubCategoryDropdown = false;
      _selectedSubSubCategory = '';
      _subSubCategoryController.text = '';
      _updateSubSubCategories();
      widget.onCategoryChanged(
        _selectedCategory,
        _selectedSubCategory,
        _selectedSubSubCategory,
      );
    });
  }

  // 소분류 선택 핸들러
  void _selectSubSubCategory(String subSubCategory) {
    setState(() {
      _selectedSubSubCategory = subSubCategory;
      _subSubCategoryController.text = subSubCategory;
      _showSubSubCategoryDropdown = false;
      widget.onCategoryChanged(
        _selectedCategory,
        _selectedSubCategory,
        _selectedSubSubCategory,
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return FormFieldWrapper(
      label: '카테고리',
      isRequired: widget.isRequired,
      child: Column(
        children: [
          // 대분류 입력 필드 (자동완성)
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              TextFormField(
                controller: _categoryController,
                focusNode: _categoryFocusNode,
                decoration: InputDecoration(
                  hintText: '대분류',
                  contentPadding: const EdgeInsets.symmetric(
                    horizontal: 12,
                    vertical: 12,
                  ),
                  suffixIcon:
                      _categoryController.text.isNotEmpty
                          ? IconButton(
                            icon: const Icon(Icons.clear),
                            onPressed: () {
                              setState(() {
                                _categoryController.clear();
                                _selectedCategory = '';
                                _selectedSubCategory = '';
                                _selectedSubSubCategory = '';
                                _subCategoryController.clear();
                                _subSubCategoryController.clear();
                                _filteredCategories = List.from(_allCategories);
                                _filteredSubCategories = [];
                                _filteredSubSubCategories = [];
                                _showCategoryDropdown =
                                    _categoryFocusNode.hasFocus;
                                widget.onCategoryChanged('', '', '');
                              });
                            },
                          )
                          : IconButton(
                            icon: const Icon(Icons.arrow_drop_down),
                            onPressed: () {
                              setState(() {
                                _showCategoryDropdown = !_showCategoryDropdown;
                              });
                            },
                          ),
                ),
                validator: (value) {
                  if (widget.isRequired && (value == null || value.isEmpty)) {
                    return '대분류를 선택해주세요';
                  }
                  return null;
                },
                onTap: () {
                  setState(() {
                    if (!_showCategoryDropdown) {
                      _showCategoryDropdown = true;
                    }
                  });
                },
              ),

              // 대분류 자동완성 드롭다운
              AutocompleteDropdown(
                items: _filteredCategories,
                inputText: _categoryController.text,
                onSelect: _selectCategory,
                showDropdown: _showCategoryDropdown,
              ),
            ],
          ),

          const SizedBox(height: 12),

          // 중분류 및 소분류 선택 행
          Row(
            children: [
              // 중분류 입력 필드 (자동완성)
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    TextFormField(
                      controller: _subCategoryController,
                      focusNode: _subCategoryFocusNode,
                      decoration: InputDecoration(
                        hintText: '중분류',
                        contentPadding: const EdgeInsets.symmetric(
                          horizontal: 12,
                          vertical: 12,
                        ),
                        suffixIcon:
                            _subCategoryController.text.isNotEmpty
                                ? IconButton(
                                  icon: const Icon(Icons.clear),
                                  onPressed: () {
                                    setState(() {
                                      _subCategoryController.clear();
                                      _selectedSubCategory = '';
                                      _selectedSubSubCategory = '';
                                      _subSubCategoryController.clear();
                                      _updateSubCategories();
                                      _updateSubSubCategories();
                                      _showSubCategoryDropdown =
                                          _subCategoryFocusNode.hasFocus;
                                      widget.onCategoryChanged(
                                        _selectedCategory,
                                        '',
                                        '',
                                      );
                                    });
                                  },
                                )
                                : IconButton(
                                  icon: const Icon(Icons.arrow_drop_down),
                                  onPressed: () {
                                    setState(() {
                                      _showSubCategoryDropdown =
                                          !_showSubCategoryDropdown;
                                    });
                                  },
                                ),
                      ),
                      enabled: _selectedCategory.isNotEmpty,
                      onTap: () {
                        setState(() {
                          if (!_showSubCategoryDropdown &&
                              _filteredSubCategories.isNotEmpty) {
                            _showSubCategoryDropdown = true;
                          }
                        });
                      },
                    ),

                    // 중분류 자동완성 드롭다운
                    AutocompleteDropdown(
                      items: _filteredSubCategories,
                      inputText: _subCategoryController.text,
                      onSelect: _selectSubCategory,
                      showDropdown: _showSubCategoryDropdown,
                    ),
                  ],
                ),
              ),

              const SizedBox(width: 12),

              // 소분류 입력 필드 (자동완성)
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    TextFormField(
                      controller: _subSubCategoryController,
                      focusNode: _subSubCategoryFocusNode,
                      decoration: InputDecoration(
                        hintText: '소분류',
                        contentPadding: const EdgeInsets.symmetric(
                          horizontal: 12,
                          vertical: 12,
                        ),
                        suffixIcon:
                            _subSubCategoryController.text.isNotEmpty
                                ? IconButton(
                                  icon: const Icon(Icons.clear),
                                  onPressed: () {
                                    setState(() {
                                      _subSubCategoryController.clear();
                                      _selectedSubSubCategory = '';
                                      _updateSubSubCategories();
                                      _showSubSubCategoryDropdown =
                                          _subSubCategoryFocusNode.hasFocus;
                                      widget.onCategoryChanged(
                                        _selectedCategory,
                                        _selectedSubCategory,
                                        '',
                                      );
                                    });
                                  },
                                )
                                : IconButton(
                                  icon: const Icon(Icons.arrow_drop_down),
                                  onPressed: () {
                                    setState(() {
                                      _showSubSubCategoryDropdown =
                                          !_showSubSubCategoryDropdown;
                                    });
                                  },
                                ),
                      ),
                      enabled:
                          _selectedCategory.isNotEmpty &&
                          _selectedSubCategory.isNotEmpty,
                      onTap: () {
                        setState(() {
                          if (!_showSubSubCategoryDropdown &&
                              _filteredSubSubCategories.isNotEmpty) {
                            _showSubSubCategoryDropdown = true;
                          }
                        });
                      },
                    ),

                    // 소분류 자동완성 드롭다운
                    AutocompleteDropdown(
                      items: _filteredSubSubCategories,
                      inputText: _subSubCategoryController.text,
                      onSelect: _selectSubSubCategory,
                      showDropdown: _showSubSubCategoryDropdown,
                    ),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
