import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.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;
  final String? naverUrl; // 순수 URL (클릭 가능한 링크용)

  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,
    this.naverUrl,
  });

  @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,
          ),
          _buildNaverUrlField(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 _buildNaverUrlField(BuildContext context) {
    final url = widget.naverUrl ?? '';
    if (url.isEmpty) return const SizedBox.shrink();

    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: const [
              Icon(Icons.link, size: 16),
              SizedBox(width: 8),
              Text('네이버 지도:'),
            ],
          ),
          const SizedBox(height: 6),
          InkWell(
            onTap: () => _launchNaverUrl(url),
            borderRadius: BorderRadius.circular(8),
            child: Container(
              width: double.infinity,
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 14),
              decoration: BoxDecoration(
                border: Border.all(
                  color: widget.isDark
                      ? AppColors.darkDivider
                      : AppColors.lightDivider,
                ),
                borderRadius: BorderRadius.circular(8),
                color: widget.isDark
                    ? AppColors.darkSurface
                    : AppColors.lightSurface,
              ),
              child: Row(
                children: [
                  Expanded(
                    child: Text(
                      url,
                      style: TextStyle(
                        color: Colors.blue[700],
                        decoration: TextDecoration.underline,
                      ),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  const SizedBox(width: 8),
                  Icon(
                    Icons.open_in_new,
                    size: 18,
                    color: Colors.blue[700],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Future<void> _launchNaverUrl(String url) async {
    final uri = Uri.tryParse(url);
    if (uri == null) return;

    try {
      await launchUrl(uri, mode: LaunchMode.externalApplication);
    } catch (_) {
      // 웹 환경에서 실패 시 platformDefault 모드로 재시도
      await launchUrl(uri, mode: LaunchMode.platformDefault);
    }
  }

  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,
          ),
        ],
      ),
    );
  }
}
