import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:lunchpick/core/constants/app_colors.dart';
import 'package:lunchpick/core/constants/app_typography.dart';
import 'package:lunchpick/core/utils/validators.dart';
import 'package:lunchpick/domain/entities/restaurant.dart';
import 'package:lunchpick/presentation/providers/restaurant_provider.dart';

class AddRestaurantDialog extends ConsumerStatefulWidget {
  final int initialTabIndex;
  
  const AddRestaurantDialog({
    super.key,
    this.initialTabIndex = 0,
  });

  @override
  ConsumerState<AddRestaurantDialog> createState() => _AddRestaurantDialogState();
}

class _AddRestaurantDialogState extends ConsumerState<AddRestaurantDialog> with SingleTickerProviderStateMixin {
  final _formKey = GlobalKey<FormState>();
  final _nameController = TextEditingController();
  final _categoryController = TextEditingController();
  final _subCategoryController = TextEditingController();
  final _descriptionController = TextEditingController();
  final _phoneController = TextEditingController();
  final _roadAddressController = TextEditingController();
  final _jibunAddressController = TextEditingController();
  final _latitudeController = TextEditingController();
  final _longitudeController = TextEditingController();
  final _naverUrlController = TextEditingController();
  
  // 기본 좌표 (서울시청)
  final double _defaultLatitude = 37.5665;
  final double _defaultLongitude = 126.9780;
  
  // UI 상태 관리
  late TabController _tabController;
  bool _isLoading = false;
  String? _errorMessage;
  Restaurant? _fetchedRestaurantData;
  final _linkController = TextEditingController();
  
  @override
  void initState() {
    super.initState();
    _tabController = TabController(
      length: 2, 
      vsync: this,
      initialIndex: widget.initialTabIndex,
    );
  }

  @override
  void dispose() {
    _nameController.dispose();
    _categoryController.dispose();
    _subCategoryController.dispose();
    _descriptionController.dispose();
    _phoneController.dispose();
    _roadAddressController.dispose();
    _jibunAddressController.dispose();
    _latitudeController.dispose();
    _longitudeController.dispose();
    _naverUrlController.dispose();
    _linkController.dispose();
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final isDark = Theme.of(context).brightness == Brightness.dark;
    
    return Dialog(
      backgroundColor: isDark ? AppColors.darkSurface : AppColors.lightSurface,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
      ),
      child: Container(
        constraints: const BoxConstraints(maxWidth: 400),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 제목과 탭바
            Container(
              padding: const EdgeInsets.fromLTRB(24, 24, 24, 0),
              child: Column(
                children: [
                  Text(
                    '맛집 추가',
                    style: AppTypography.heading1(isDark),
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: 16),
                  Container(
                    decoration: BoxDecoration(
                      color: isDark ? AppColors.darkBackground : AppColors.lightBackground,
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: TabBar(
                      controller: _tabController,
                      indicator: BoxDecoration(
                        color: AppColors.lightPrimary,
                        borderRadius: BorderRadius.circular(12),
                      ),
                      indicatorSize: TabBarIndicatorSize.tab,
                      labelColor: Colors.white,
                      unselectedLabelColor: isDark ? AppColors.darkTextSecondary : AppColors.lightTextSecondary,
                      labelStyle: AppTypography.body1(false).copyWith(fontWeight: FontWeight.w600),
                      tabs: const [
                        Tab(text: '직접 입력'),
                        Tab(text: '네이버 지도에서 가져오기'),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            // 탭뷰 컨텐츠
            Flexible(
              child: TabBarView(
                controller: _tabController,
                physics: const NeverScrollableScrollPhysics(),
                children: [
                  // 직접 입력 탭
                  SingleChildScrollView(
                    padding: const EdgeInsets.all(24),
                    child: Form(
                      key: _formKey,
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [
                
                // 가게 이름
                TextFormField(
                  controller: _nameController,
                  decoration: InputDecoration(
                    labelText: '가게 이름 *',
                    hintText: '예: 서울갈비',
                    prefixIcon: const Icon(Icons.store),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return '가게 이름을 입력해주세요';
                    }
                    return null;
                  },
                ),
                const SizedBox(height: 16),
                
                // 카테고리
                Row(
                  children: [
                    Expanded(
                      child: TextFormField(
                        controller: _categoryController,
                        decoration: InputDecoration(
                          labelText: '카테고리 *',
                          hintText: '예: 한식',
                          prefixIcon: const Icon(Icons.category),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                        ),
                        validator: (value) {
                          if (value == null || value.isEmpty) {
                            return '카테고리를 입력해주세요';
                          }
                          return null;
                        },
                      ),
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: TextFormField(
                        controller: _subCategoryController,
                        decoration: InputDecoration(
                          labelText: '세부 카테고리',
                          hintText: '예: 갈비',
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 16),
                
                // 설명
                TextFormField(
                  controller: _descriptionController,
                  maxLines: 2,
                  decoration: InputDecoration(
                    labelText: '설명',
                    hintText: '맛집에 대한 간단한 설명',
                    prefixIcon: const Icon(Icons.description),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                ),
                const SizedBox(height: 16),
                
                // 전화번호
                TextFormField(
                  controller: _phoneController,
                  keyboardType: TextInputType.phone,
                  decoration: InputDecoration(
                    labelText: '전화번호',
                    hintText: '예: 02-1234-5678',
                    prefixIcon: const Icon(Icons.phone),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                ),
                const SizedBox(height: 16),
                
                // 도로명 주소
                TextFormField(
                  controller: _roadAddressController,
                  decoration: InputDecoration(
                    labelText: '도로명 주소 *',
                    hintText: '예: 서울시 중구 세종대로 110',
                    prefixIcon: const Icon(Icons.location_on),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return '도로명 주소를 입력해주세요';
                    }
                    return null;
                  },
                ),
                const SizedBox(height: 16),
                
                // 지번 주소
                TextFormField(
                  controller: _jibunAddressController,
                  decoration: InputDecoration(
                    labelText: '지번 주소',
                    hintText: '예: 서울시 중구 태평로1가 31',
                    prefixIcon: const Icon(Icons.map),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                ),
                const SizedBox(height: 16),
                
                // 위도/경도 입력
                Row(
                  children: [
                    Expanded(
                      child: TextFormField(
                        controller: _latitudeController,
                        keyboardType: const TextInputType.numberWithOptions(decimal: true),
                        decoration: InputDecoration(
                          labelText: '위도',
                          hintText: '37.5665',
                          prefixIcon: const Icon(Icons.explore),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                        ),
                        validator: Validators.validateLatitude,
                      ),
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: TextFormField(
                        controller: _longitudeController,
                        keyboardType: const TextInputType.numberWithOptions(decimal: true),
                        decoration: InputDecoration(
                          labelText: '경도',
                          hintText: '126.9780',
                          prefixIcon: const Icon(Icons.explore),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                        ),
                        validator: Validators.validateLongitude,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                Text(
                  '* 위도/경도를 입력하지 않으면 서울시청 기준으로 저장됩니다',
                  style: TextStyle(
                    fontSize: 12,
                    color: isDark ? AppColors.darkTextSecondary : AppColors.lightTextSecondary,
                  ),
                ),
                const SizedBox(height: 24),
                
                          // 버튼
                          Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              TextButton(
                                onPressed: () => Navigator.pop(context),
                                child: Text(
                                  '취소',
                                  style: TextStyle(
                                    color: isDark ? AppColors.darkTextSecondary : AppColors.lightTextSecondary,
                                  ),
                                ),
                              ),
                              const SizedBox(width: 8),
                              ElevatedButton(
                                onPressed: _saveRestaurant,
                                style: ElevatedButton.styleFrom(
                                  backgroundColor: AppColors.lightPrimary,
                                  foregroundColor: Colors.white,
                                ),
                                child: const Text('저장'),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                  // 네이버 지도 탭
                  _buildNaverMapTab(isDark),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 네이버 지도 탭 빌드
  Widget _buildNaverMapTab(bool isDark) {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(24),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // 안내 메시지
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: AppColors.lightPrimary.withOpacity(0.1),
              borderRadius: BorderRadius.circular(12),
              border: Border.all(
                color: AppColors.lightPrimary.withOpacity(0.3),
              ),
            ),
            child: Row(
              children: [
                Icon(
                  Icons.info_outline,
                  color: AppColors.lightPrimary,
                  size: 20,
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Text(
                    kIsWeb 
                      ? '네이버 지도에서 맛집 페이지 URL을 복사하여\n붙여넣어 주세요.\n\n웹 환경에서는 프록시 서버를 통해 정보를 가져옵니다.\n네트워크 상황에 따라 시간이 걸릴 수 있습니다.'
                      : '네이버 지도에서 맛집 페이지 URL을 복사하여\n붙여넣어 주세요.',
                    style: TextStyle(
                      fontSize: 14,
                      color: isDark ? AppColors.darkText : AppColors.lightText,
                      height: 1.5,
                    ),
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 24),
          
          // URL 입력 필드
          TextFormField(
            controller: _naverUrlController,
            decoration: InputDecoration(
              labelText: '네이버 지도 URL',
              hintText: 'https://map.naver.com/... 또는 https://naver.me/...',
              prefixIcon: Icon(
                Icons.link,
                color: AppColors.lightPrimary,
              ),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(12),
                borderSide: BorderSide(
                  color: isDark ? AppColors.darkDivider : AppColors.lightDivider,
                ),
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(12),
                borderSide: BorderSide(
                  color: AppColors.lightPrimary,
                  width: 2,
                ),
              ),
              errorText: _errorMessage,
              errorMaxLines: 2,
            ),
            enabled: !_isLoading,
          ),
          const SizedBox(height: 24),
          
          // 가져온 정보 표시 (JSON 스타일)
          if (_fetchedRestaurantData != null) ...[
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: isDark 
                  ? AppColors.darkBackground 
                  : AppColors.lightBackground.withOpacity(0.5),
                borderRadius: BorderRadius.circular(12),
                border: Border.all(
                  color: isDark 
                    ? AppColors.darkDivider 
                    : AppColors.lightDivider,
                ),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 타이틀
                  Row(
                    children: [
                      Icon(
                        Icons.code,
                        size: 20,
                        color: isDark 
                          ? AppColors.darkTextSecondary 
                          : AppColors.lightTextSecondary,
                      ),
                      const SizedBox(width: 8),
                      Text(
                        '가져온 정보',
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w600,
                          color: isDark 
                            ? AppColors.darkTextSecondary 
                            : AppColors.lightTextSecondary,
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 12),
                  // JSON 스타일 정보 표시
                  _buildJsonField(
                    '이름', 
                    _nameController, 
                    isDark,
                    icon: Icons.store,
                  ),
                  _buildJsonField(
                    '카테고리', 
                    _categoryController, 
                    isDark,
                    icon: Icons.category,
                  ),
                  _buildJsonField(
                    '세부 카테고리', 
                    _subCategoryController, 
                    isDark,
                    icon: Icons.label_outline,
                  ),
                  _buildJsonField(
                    '주소', 
                    _roadAddressController, 
                    isDark,
                    icon: Icons.location_on,
                  ),
                  _buildJsonField(
                    '전화', 
                    _phoneController, 
                    isDark,
                    icon: Icons.phone,
                  ),
                  _buildJsonField(
                    '설명', 
                    _descriptionController, 
                    isDark,
                    icon: Icons.description,
                    maxLines: 2,
                  ),
                  _buildJsonField(
                    '좌표', 
                    TextEditingController(
                      text: '${_latitudeController.text}, ${_longitudeController.text}'
                    ), 
                    isDark,
                    icon: Icons.my_location,
                    isCoordinate: true,
                  ),
                  if (_linkController.text.isNotEmpty)
                    _buildJsonField(
                      '링크', 
                      _linkController, 
                      isDark,
                      icon: Icons.link,
                      isLink: true,
                    ),
                ],
              ),
            ),
            const SizedBox(height: 24),
          ],
          
          // 버튼
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              TextButton(
                onPressed: _isLoading ? null : () => Navigator.pop(context),
                child: Text(
                  '취소',
                  style: TextStyle(
                    color: isDark ? AppColors.darkTextSecondary : AppColors.lightTextSecondary,
                  ),
                ),
              ),
              const SizedBox(width: 8),
              if (_fetchedRestaurantData == null)
                ElevatedButton(
                  onPressed: _isLoading ? null : _fetchFromNaverUrl,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: AppColors.lightPrimary,
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                  ),
                  child: _isLoading
                      ? SizedBox(
                          width: 20,
                          height: 20,
                          child: CircularProgressIndicator(
                            strokeWidth: 2,
                            valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                          ),
                        )
                      : Row(
                          mainAxisSize: MainAxisSize.min,
                          children: const [
                            Icon(Icons.download, size: 18),
                            SizedBox(width: 8),
                            Text('가져오기'),
                          ],
                        ),
                )
              else ...[
                OutlinedButton(
                  onPressed: () {
                    setState(() {
                      _fetchedRestaurantData = null;
                      _clearControllers();
                    });
                  },
                  style: OutlinedButton.styleFrom(
                    foregroundColor: isDark 
                      ? AppColors.darkTextSecondary 
                      : AppColors.lightTextSecondary,
                    side: BorderSide(
                      color: isDark 
                        ? AppColors.darkDivider 
                        : AppColors.lightDivider,
                    ),
                    padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                  ),
                  child: const Text('초기화'),
                ),
                const SizedBox(width: 8),
                ElevatedButton(
                  onPressed: _saveRestaurant,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: AppColors.lightPrimary,
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: const [
                      Icon(Icons.save, size: 18),
                      SizedBox(width: 8),
                      Text('저장'),
                    ],
                  ),
                ),
              ],
            ],
          ),
        ],
      ),
    );
  }

  // JSON 스타일 필드 빌드
  Widget _buildJsonField(
    String label,
    TextEditingController controller,
    bool isDark, {
    IconData? icon,
    int maxLines = 1,
    bool isCoordinate = false,
    bool isLink = false,
  }) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              if (icon != null) ...[
                Icon(
                  icon,
                  size: 16,
                  color: isDark 
                    ? AppColors.darkTextSecondary 
                    : AppColors.lightTextSecondary,
                ),
                const SizedBox(width: 8),
              ],
              Text(
                '$label:',
                style: TextStyle(
                  fontSize: 13,
                  fontWeight: FontWeight.w500,
                  color: isDark 
                    ? AppColors.darkTextSecondary 
                    : AppColors.lightTextSecondary,
                ),
              ),
            ],
          ),
          const SizedBox(height: 4),
          if (isCoordinate) 
            Row(
              children: [
                Expanded(
                  child: TextFormField(
                    controller: _latitudeController,
                    style: TextStyle(
                      fontSize: 14,
                      fontFamily: 'monospace',
                      color: isDark ? AppColors.darkText : AppColors.lightText,
                    ),
                    decoration: InputDecoration(
                      hintText: '위도',
                      isDense: true,
                      contentPadding: const EdgeInsets.symmetric(
                        horizontal: 12,
                        vertical: 8,
                      ),
                      filled: true,
                      fillColor: isDark 
                        ? AppColors.darkSurface 
                        : Colors.white,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                        borderSide: BorderSide(
                          color: isDark 
                            ? AppColors.darkDivider 
                            : AppColors.lightDivider,
                        ),
                      ),
                    ),
                  ),
                ),
                const SizedBox(width: 8),
                Text(
                  ',',
                  style: TextStyle(
                    fontSize: 14,
                    fontFamily: 'monospace',
                    color: isDark ? AppColors.darkText : AppColors.lightText,
                  ),
                ),
                const SizedBox(width: 8),
                Expanded(
                  child: TextFormField(
                    controller: _longitudeController,
                    style: TextStyle(
                      fontSize: 14,
                      fontFamily: 'monospace',
                      color: isDark ? AppColors.darkText : AppColors.lightText,
                    ),
                    decoration: InputDecoration(
                      hintText: '경도',
                      isDense: true,
                      contentPadding: const EdgeInsets.symmetric(
                        horizontal: 12,
                        vertical: 8,
                      ),
                      filled: true,
                      fillColor: isDark 
                        ? AppColors.darkSurface 
                        : Colors.white,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                        borderSide: BorderSide(
                          color: isDark 
                            ? AppColors.darkDivider 
                            : AppColors.lightDivider,
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            )
          else
            TextFormField(
              controller: controller,
              maxLines: maxLines,
              style: TextStyle(
                fontSize: 14,
                fontFamily: isLink ? 'monospace' : null,
                color: isLink 
                  ? AppColors.lightPrimary 
                  : isDark ? AppColors.darkText : AppColors.lightText,
                decoration: isLink ? TextDecoration.underline : null,
              ),
              decoration: InputDecoration(
                isDense: true,
                contentPadding: const EdgeInsets.symmetric(
                  horizontal: 12,
                  vertical: 8,
                ),
                filled: true,
                fillColor: isDark 
                  ? AppColors.darkSurface 
                  : Colors.white,
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                  borderSide: BorderSide(
                    color: isDark 
                      ? AppColors.darkDivider 
                      : AppColors.lightDivider,
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }

  // 컨트롤러 초기화
  void _clearControllers() {
    _nameController.clear();
    _categoryController.clear();
    _subCategoryController.clear();
    _descriptionController.clear();
    _phoneController.clear();
    _roadAddressController.clear();
    _jibunAddressController.clear();
    _latitudeController.clear();
    _longitudeController.clear();
    _linkController.clear();
  }

  // 네이버 URL에서 정보 가져오기
  Future<void> _fetchFromNaverUrl() async {
    final url = _naverUrlController.text.trim();
    
    if (url.isEmpty) {
      setState(() {
        _errorMessage = 'URL을 입력해주세요.';
      });
      return;
    }
    
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });
    
    try {
      final notifier = ref.read(restaurantNotifierProvider.notifier);
      final restaurant = await notifier.addRestaurantFromUrl(url);
      
      // 성공 시 폼에 정보 채우고 _fetchedRestaurantData 설정
      setState(() {
        _nameController.text = restaurant.name;
        _categoryController.text = restaurant.category;
        _subCategoryController.text = restaurant.subCategory;
        _descriptionController.text = restaurant.description ?? '';
        _phoneController.text = restaurant.phoneNumber ?? '';
        _roadAddressController.text = restaurant.roadAddress;
        _jibunAddressController.text = restaurant.jibunAddress;
        _latitudeController.text = restaurant.latitude.toString();
        _longitudeController.text = restaurant.longitude.toString();
        
        // 링크 정보가 있다면 설정
        _linkController.text = restaurant.naverUrl ?? '';
        
        // Restaurant 객체 저장
        _fetchedRestaurantData = restaurant;
        
        _isLoading = false;
      });
      
      // 성공 메시지 표시
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Row(
              children: [
                Icon(Icons.check_circle, color: Colors.white, size: 20),
                const SizedBox(width: 8),
                Text('맛집 정보를 가져왔습니다. 확인 후 저장해주세요.'),
              ],
            ),
            backgroundColor: AppColors.lightPrimary,
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
            ),
          ),
        );
      }
    } catch (e) {
      setState(() {
        _isLoading = false;
        _errorMessage = e.toString().replaceFirst('Exception: ', '');
      });
    }
  }

  Future<void> _saveRestaurant() async {
    if (_formKey.currentState?.validate() != true) {
      return;
    }

    final notifier = ref.read(restaurantNotifierProvider.notifier);
    
    try {
      // _fetchedRestaurantData가 있으면 해당 데이터 사용 (네이버에서 가져온 경우)
      final fetchedData = _fetchedRestaurantData;
      if (fetchedData != null) {
        // 사용자가 수정한 필드만 업데이트
        final updatedRestaurant = fetchedData.copyWith(
          name: _nameController.text.trim(),
          category: _categoryController.text.trim(),
          subCategory: _subCategoryController.text.trim().isEmpty 
              ? _categoryController.text.trim() 
              : _subCategoryController.text.trim(),
          description: _descriptionController.text.trim().isEmpty 
              ? null 
              : _descriptionController.text.trim(),
          phoneNumber: _phoneController.text.trim().isEmpty 
              ? null 
              : _phoneController.text.trim(),
          roadAddress: _roadAddressController.text.trim(),
          jibunAddress: _jibunAddressController.text.trim().isEmpty 
              ? _roadAddressController.text.trim() 
              : _jibunAddressController.text.trim(),
          latitude: double.tryParse(_latitudeController.text.trim()) ?? fetchedData.latitude,
          longitude: double.tryParse(_longitudeController.text.trim()) ?? fetchedData.longitude,
          updatedAt: DateTime.now(),
        );
        
        // 이미 완성된 Restaurant 객체를 직접 추가
        await notifier.addRestaurantDirect(updatedRestaurant);
      } else {
        // 직접 입력한 경우 (기존 로직)
        await notifier.addRestaurant(
          name: _nameController.text.trim(),
          category: _categoryController.text.trim(),
          subCategory: _subCategoryController.text.trim().isEmpty 
              ? _categoryController.text.trim() 
              : _subCategoryController.text.trim(),
          description: _descriptionController.text.trim().isEmpty 
              ? null 
              : _descriptionController.text.trim(),
          phoneNumber: _phoneController.text.trim().isEmpty 
              ? null 
              : _phoneController.text.trim(),
          roadAddress: _roadAddressController.text.trim(),
          jibunAddress: _jibunAddressController.text.trim().isEmpty 
              ? _roadAddressController.text.trim() 
              : _jibunAddressController.text.trim(),
          latitude: _latitudeController.text.trim().isEmpty 
              ? _defaultLatitude 
              : double.tryParse(_latitudeController.text.trim()) ?? _defaultLatitude,
          longitude: _longitudeController.text.trim().isEmpty 
              ? _defaultLongitude 
              : double.tryParse(_longitudeController.text.trim()) ?? _defaultLongitude,
          source: DataSource.USER_INPUT,
        );
      }

      if (mounted) {
        Navigator.pop(context);
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('맛집이 추가되었습니다'),
            backgroundColor: AppColors.lightPrimary,
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('오류가 발생했습니다: ${e.toString()}'),
            backgroundColor: AppColors.lightError,
          ),
        );
      }
    }
  }
}