import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../../../services/restaurant_form_validator.dart';

/// 식당 추가 폼 위젯
class AddRestaurantForm extends StatefulWidget {
  final GlobalKey<FormState> formKey;
  final TextEditingController nameController;
  final TextEditingController categoryController;
  final TextEditingController subCategoryController;
  final TextEditingController descriptionController;
  final TextEditingController phoneController;
  final TextEditingController roadAddressController;
  final TextEditingController jibunAddressController;
  final TextEditingController latitudeController;
  final TextEditingController longitudeController;
  final Function(String) onFieldChanged;
  final List<String> categories;
  final List<String> subCategories;
  final String geocodingStatus;

  const AddRestaurantForm({
    super.key,
    required this.formKey,
    required this.nameController,
    required this.categoryController,
    required this.subCategoryController,
    required this.descriptionController,
    required this.phoneController,
    required this.roadAddressController,
    required this.jibunAddressController,
    required this.latitudeController,
    required this.longitudeController,
    required this.onFieldChanged,
    this.categories = const <String>[],
    this.subCategories = const <String>[],
    this.geocodingStatus = '',
  });

  @override
  State<AddRestaurantForm> createState() => _AddRestaurantFormState();
}

class _AddRestaurantFormState extends State<AddRestaurantForm> {
  late final FocusNode _categoryFocusNode;
  late final FocusNode _subCategoryFocusNode;
  late Set<String> _availableCategories;
  late Set<String> _availableSubCategories;

  @override
  void initState() {
    super.initState();
    _categoryFocusNode = FocusNode();
    _subCategoryFocusNode = FocusNode();
    _availableCategories = {...widget.categories};
    _availableSubCategories = {...widget.subCategories};
    final currentCategory = widget.categoryController.text.trim();
    if (currentCategory.isNotEmpty) {
      _availableCategories.add(currentCategory);
    }
    final currentSubCategory = widget.subCategoryController.text.trim();
    if (currentSubCategory.isNotEmpty) {
      _availableSubCategories.add(currentSubCategory);
    }
  }

  @override
  void didUpdateWidget(covariant AddRestaurantForm oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (!setEquals(oldWidget.categories.toSet(), widget.categories.toSet())) {
      setState(() {
        _availableCategories = {...widget.categories, ..._availableCategories};
      });
    }
    if (!setEquals(
      oldWidget.subCategories.toSet(),
      widget.subCategories.toSet(),
    )) {
      setState(() {
        _availableSubCategories = {
          ...widget.subCategories,
          ..._availableSubCategories,
        };
      });
    }
  }

  @override
  void dispose() {
    _categoryFocusNode.dispose();
    _subCategoryFocusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: widget.formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // 가게 이름
          TextFormField(
            controller: widget.nameController,
            decoration: InputDecoration(
              labelText: '가게 이름 *',
              hintText: '예: 맛있는 한식당',
              prefixIcon: const Icon(Icons.store),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
              ),
            ),
            onChanged: widget.onFieldChanged,
            validator: (value) {
              if (value == null || value.isEmpty) {
                return '가게 이름을 입력해주세요';
              }
              return null;
            },
          ),
          const SizedBox(height: 16),

          // 카테고리
          Row(
            children: [
              Expanded(child: _buildCategoryField(context)),
              const SizedBox(width: 8),
              Expanded(child: _buildSubCategoryField(context)),
            ],
          ),
          const SizedBox(height: 16),

          // 설명
          TextFormField(
            controller: widget.descriptionController,
            maxLines: 2,
            decoration: InputDecoration(
              labelText: '설명',
              hintText: '맛집에 대한 간단한 설명',
              prefixIcon: const Icon(Icons.description),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
              ),
            ),
            onChanged: widget.onFieldChanged,
          ),
          const SizedBox(height: 16),

          // 전화번호
          TextFormField(
            controller: widget.phoneController,
            keyboardType: TextInputType.phone,
            decoration: InputDecoration(
              labelText: '전화번호',
              hintText: '예: 02-1234-5678',
              prefixIcon: const Icon(Icons.phone),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
              ),
            ),
            onChanged: widget.onFieldChanged,
            validator: (value) =>
                RestaurantFormValidator.validatePhoneNumber(value),
          ),
          const SizedBox(height: 16),

          // 도로명 주소
          TextFormField(
            controller: widget.roadAddressController,
            decoration: InputDecoration(
              labelText: '도로명 주소 *',
              hintText: '예: 서울시 중구 세종대로 110',
              prefixIcon: const Icon(Icons.location_on),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
              ),
            ),
            onChanged: widget.onFieldChanged,
            validator: (value) =>
                RestaurantFormValidator.validateAddress(value),
          ),
          const SizedBox(height: 16),

          // 지번 주소
          TextFormField(
            controller: widget.jibunAddressController,
            decoration: InputDecoration(
              labelText: '지번 주소',
              hintText: '예: 서울시 중구 태평로1가 31',
              prefixIcon: const Icon(Icons.map),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
              ),
            ),
            onChanged: widget.onFieldChanged,
          ),
          const SizedBox(height: 16),

          // 위도/경도 입력
          Row(
            children: [
              Expanded(
                child: TextFormField(
                  controller: widget.latitudeController,
                  keyboardType: const TextInputType.numberWithOptions(
                    decimal: true,
                  ),
                  decoration: InputDecoration(
                    labelText: '위도',
                    hintText: '37.5665',
                    prefixIcon: const Icon(Icons.explore),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  onChanged: widget.onFieldChanged,
                  validator: (value) {
                    if (value != null && value.isNotEmpty) {
                      final latitude = double.tryParse(value);
                      if (latitude == null || latitude < -90 || latitude > 90) {
                        return '올바른 위도값을 입력해주세요';
                      }
                    }
                    return null;
                  },
                ),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: TextFormField(
                  controller: widget.longitudeController,
                  keyboardType: const TextInputType.numberWithOptions(
                    decimal: true,
                  ),
                  decoration: InputDecoration(
                    labelText: '경도',
                    hintText: '126.9780',
                    prefixIcon: const Icon(Icons.explore),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  onChanged: widget.onFieldChanged,
                  validator: (value) {
                    if (value != null && value.isNotEmpty) {
                      final longitude = double.tryParse(value);
                      if (longitude == null ||
                          longitude < -180 ||
                          longitude > 180) {
                        return '올바른 경도값을 입력해주세요';
                      }
                    }
                    return null;
                  },
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                '주소가 정확하지 않을 경우 위도/경도를 현재 위치로 입력합니다.',
                style: Theme.of(
                  context,
                ).textTheme.bodySmall?.copyWith(color: Colors.grey),
                textAlign: TextAlign.center,
              ),
              if (widget.geocodingStatus.isNotEmpty) ...[
                const SizedBox(height: 4),
                Text(
                  widget.geocodingStatus,
                  style: Theme.of(context).textTheme.bodySmall?.copyWith(
                    color: Colors.blueGrey,
                    fontWeight: FontWeight.w600,
                  ),
                  textAlign: TextAlign.center,
                ),
              ],
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildCategoryField(BuildContext context) {
    return RawAutocomplete<String>(
      textEditingController: widget.categoryController,
      focusNode: _categoryFocusNode,
      optionsBuilder: (TextEditingValue value) {
        final query = value.text.trim();
        if (query.isEmpty) {
          return _availableCategories;
        }

        final lowerQuery = query.toLowerCase();
        final matches = _availableCategories
            .where((c) => c.toLowerCase().contains(lowerQuery))
            .toList();

        final hasExactMatch = _availableCategories.any(
          (c) => c.toLowerCase() == lowerQuery,
        );
        if (!hasExactMatch) {
          matches.insert(0, query);
        }

        return matches;
      },
      displayStringForOption: (option) => option,
      onSelected: (option) {
        final normalized = option.trim();
        widget.categoryController.text = normalized;
        if (normalized.isNotEmpty) {
          setState(() {
            _availableCategories.add(normalized);
          });
        }
        widget.onFieldChanged(normalized);
      },
      fieldViewBuilder:
          (context, textEditingController, focusNode, onFieldSubmitted) {
            return TextFormField(
              controller: textEditingController,
              focusNode: focusNode,
              decoration: InputDecoration(
                labelText: '카테고리 *',
                hintText: '예: 한식',
                prefixIcon: const Icon(Icons.category),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
                suffixIcon: const Icon(Icons.arrow_drop_down),
              ),
              onChanged: widget.onFieldChanged,
              onFieldSubmitted: (_) => onFieldSubmitted(),
              validator: (value) =>
                  RestaurantFormValidator.validateCategory(value),
            );
          },
      optionsViewBuilder: (context, onSelected, options) {
        return Align(
          alignment: Alignment.topLeft,
          child: Material(
            elevation: 4,
            borderRadius: BorderRadius.circular(8),
            child: ConstrainedBox(
              constraints: const BoxConstraints(maxHeight: 220, minWidth: 200),
              child: ListView.builder(
                padding: EdgeInsets.zero,
                shrinkWrap: true,
                itemCount: options.length,
                itemBuilder: (context, index) {
                  final option = options.elementAt(index);
                  final isNewEntry = !_availableCategories.contains(option);
                  return ListTile(
                    dense: true,
                    title: Text(
                      isNewEntry ? '새 카테고리 추가: $option' : option,
                      style: TextStyle(
                        fontWeight: isNewEntry ? FontWeight.w600 : null,
                      ),
                    ),
                    onTap: () => onSelected(option),
                  );
                },
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildSubCategoryField(BuildContext context) {
    return RawAutocomplete<String>(
      textEditingController: widget.subCategoryController,
      focusNode: _subCategoryFocusNode,
      optionsBuilder: (TextEditingValue value) {
        final query = value.text.trim();
        if (query.isEmpty) {
          return _availableSubCategories;
        }

        final lowerQuery = query.toLowerCase();
        final matches = _availableSubCategories
            .where((c) => c.toLowerCase().contains(lowerQuery))
            .toList();

        final hasExactMatch = _availableSubCategories.any(
          (c) => c.toLowerCase() == lowerQuery,
        );
        if (!hasExactMatch && query.isNotEmpty) {
          matches.insert(0, query);
        }

        return matches;
      },
      displayStringForOption: (option) => option,
      onSelected: (option) {
        final normalized = option.trim();
        widget.subCategoryController.text = normalized;
        if (normalized.isNotEmpty) {
          setState(() {
            _availableSubCategories.add(normalized);
          });
        }
        widget.onFieldChanged(normalized);
      },
      fieldViewBuilder:
          (context, textEditingController, focusNode, onFieldSubmitted) {
            return TextFormField(
              controller: textEditingController,
              focusNode: focusNode,
              decoration: InputDecoration(
                labelText: '세부 카테고리',
                hintText: '예: 갈비',
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
                suffixIcon: const Icon(Icons.arrow_drop_down),
              ),
              onChanged: widget.onFieldChanged,
              onFieldSubmitted: (_) => onFieldSubmitted(),
            );
          },
      optionsViewBuilder: (context, onSelected, options) {
        return Align(
          alignment: Alignment.topLeft,
          child: Material(
            elevation: 4,
            borderRadius: BorderRadius.circular(8),
            child: ConstrainedBox(
              constraints: const BoxConstraints(maxHeight: 220, minWidth: 200),
              child: ListView.builder(
                padding: EdgeInsets.zero,
                shrinkWrap: true,
                itemCount: options.length,
                itemBuilder: (context, index) {
                  final option = options.elementAt(index);
                  final isNewEntry = !_availableSubCategories.contains(option);
                  return ListTile(
                    dense: true,
                    title: Text(
                      isNewEntry ? '새 세부 카테고리 추가: $option' : option,
                      style: TextStyle(
                        fontWeight: isNewEntry ? FontWeight.w600 : null,
                      ),
                    ),
                    onTap: () => onSelected(option),
                  );
                },
              ),
            ),
          ),
        );
      },
    );
  }
}
