import 'package:flutter/material.dart';

import '../../../../core/constants/app_colors.dart';
import '../../../../core/constants/app_typography.dart';
import '../../../services/restaurant_form_validator.dart';

class FetchedRestaurantJsonView extends StatefulWidget {
  final bool isDark;
  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 TextEditingController naverUrlController;
  final ValueChanged<String> onFieldChanged;

  const FetchedRestaurantJsonView({
    super.key,
    required this.isDark,
    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.naverUrlController,
    required this.onFieldChanged,
  });

  @override
  State<FetchedRestaurantJsonView> createState() =>
      _FetchedRestaurantJsonViewState();
}

class _FetchedRestaurantJsonViewState extends State<FetchedRestaurantJsonView> {
  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 = {
      '기타',
      if (widget.categoryController.text.trim().isNotEmpty)
        widget.categoryController.text.trim(),
    };
    _availableSubCategories = {
      '기타',
      if (widget.subCategoryController.text.trim().isNotEmpty)
        widget.subCategoryController.text.trim(),
    };

    if (widget.categoryController.text.trim().isEmpty) {
      widget.categoryController.text = '기타';
    }
    if (widget.subCategoryController.text.trim().isEmpty) {
      widget.subCategoryController.text = '기타';
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: widget.isDark
            ? AppColors.darkBackground
            : AppColors.lightBackground.withOpacity(0.5),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: widget.isDark ? AppColors.darkDivider : AppColors.lightDivider,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.code, size: 18),
              const SizedBox(width: 8),
              Text(
                '가져온 정보',
                style: AppTypography.body1(
                  widget.isDark,
                ).copyWith(fontWeight: FontWeight.w600),
              ),
            ],
          ),
          const SizedBox(height: 12),
          _buildJsonField(
            context,
            label: '상호',
            controller: widget.nameController,
            icon: Icons.store,
            validator: (value) =>
                value == null || value.isEmpty ? '가게 이름을 입력해주세요' : null,
          ),
          _buildJsonField(
            context,
            label: '도로명 주소',
            controller: widget.roadAddressController,
            icon: Icons.location_on,
            validator: RestaurantFormValidator.validateAddress,
          ),
          _buildJsonField(
            context,
            label: '지번 주소',
            controller: widget.jibunAddressController,
            icon: Icons.map,
          ),
          _buildCoordinateFields(context),
          _buildJsonField(
            context,
            label: '전화번호',
            controller: widget.phoneController,
            icon: Icons.phone,
            keyboardType: TextInputType.phone,
            validator: RestaurantFormValidator.validatePhoneNumber,
          ),
          Row(
            children: [
              Expanded(child: _buildCategoryField(context)),
              const SizedBox(width: 8),
              Expanded(child: _buildSubCategoryField(context)),
            ],
          ),
          _buildJsonField(
            context,
            label: '설명',
            controller: widget.descriptionController,
            icon: Icons.description,
            maxLines: 2,
          ),
        ],
      ),
    );
  }

  Widget _buildCoordinateFields(BuildContext context) {
    final border = OutlineInputBorder(borderRadius: BorderRadius.circular(8));

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: const [
            Icon(Icons.my_location, size: 16),
            SizedBox(width: 8),
            Text('좌표'),
          ],
        ),
        const SizedBox(height: 6),
        Row(
          children: [
            Expanded(
              child: TextFormField(
                controller: widget.latitudeController,
                keyboardType: const TextInputType.numberWithOptions(
                  decimal: true,
                ),
                decoration: InputDecoration(
                  labelText: '위도',
                  border: border,
                  isDense: true,
                ),
                onChanged: widget.onFieldChanged,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '위도를 입력해주세요';
                  }
                  final latitude = double.tryParse(value);
                  if (latitude == null || latitude < -90 || latitude > 90) {
                    return '올바른 위도값을 입력해주세요';
                  }
                  return null;
                },
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: TextFormField(
                controller: widget.longitudeController,
                keyboardType: const TextInputType.numberWithOptions(
                  decimal: true,
                ),
                decoration: InputDecoration(
                  labelText: '경도',
                  border: border,
                  isDense: true,
                ),
                onChanged: widget.onFieldChanged,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '경도를 입력해주세요';
                  }
                  final longitude = double.tryParse(value);
                  if (longitude == null ||
                      longitude < -180 ||
                      longitude > 180) {
                    return '올바른 경도값을 입력해주세요';
                  }
                  return null;
                },
              ),
            ),
          ],
        ),
        const SizedBox(height: 12),
      ],
    );
  }

  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 hasExact = _availableCategories.any(
          (c) => c.toLowerCase() == lowerQuery,
        );
        if (!hasExact) {
          matches.insert(0, query.isEmpty ? '기타' : query);
        }
        return matches;
      },
      displayStringForOption: (option) => option,
      onSelected: (option) {
        final normalized = option.trim().isEmpty ? '기타' : option.trim();
        setState(() {
          _availableCategories.add(normalized);
        });
        widget.categoryController.text = 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: RestaurantFormValidator.validateCategory,
            );
          },
      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 isNew = !_availableCategories.contains(option);
                  return ListTile(
                    dense: true,
                    title: Text(
                      isNew ? '새 카테고리 추가: $option' : option,
                      style: TextStyle(
                        fontWeight: isNew ? 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 hasExact = _availableSubCategories.any(
          (c) => c.toLowerCase() == lowerQuery,
        );
        if (!hasExact) {
          matches.insert(0, query.isEmpty ? '기타' : query);
        }
        return matches;
      },
      displayStringForOption: (option) => option,
      onSelected: (option) {
        final normalized = option.trim().isEmpty ? '기타' : option.trim();
        setState(() {
          _availableSubCategories.add(normalized);
        });
        widget.subCategoryController.text = 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 isNew = !_availableSubCategories.contains(option);
                  return ListTile(
                    dense: true,
                    title: Text(
                      isNew ? '새 세부 카테고리 추가: $option' : option,
                      style: TextStyle(
                        fontWeight: isNew ? FontWeight.w600 : null,
                      ),
                    ),
                    onTap: () => onSelected(option),
                  );
                },
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildJsonField(
    BuildContext context, {
    required String label,
    required TextEditingController controller,
    required IconData icon,
    int maxLines = 1,
    TextInputType? keyboardType,
    bool monospace = false,
    String? Function(String?)? validator,
  }) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(icon, size: 16),
              const SizedBox(width: 8),
              Text('$label:'),
            ],
          ),
          const SizedBox(height: 6),
          TextFormField(
            controller: controller,
            maxLines: maxLines,
            keyboardType: keyboardType,
            onChanged: widget.onFieldChanged,
            validator: validator,
            decoration: InputDecoration(
              labelText: label,
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
              ),
              isDense: true,
            ),
            style: monospace
                ? const TextStyle(fontFamily: 'RobotoMono', fontSize: 14)
                : null,
          ),
        ],
      ),
    );
  }
}
