import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../../../core/constants/app_colors.dart';
import '../../../core/constants/app_typography.dart';
import '../../providers/restaurant_provider.dart';
import '../../view_models/add_restaurant_view_model.dart';
import 'widgets/add_restaurant_form.dart';

class ManualRestaurantInputScreen extends ConsumerStatefulWidget {
  const ManualRestaurantInputScreen({super.key});

  @override
  ConsumerState<ManualRestaurantInputScreen> createState() =>
      _ManualRestaurantInputScreenState();
}

class _ManualRestaurantInputScreenState
    extends ConsumerState<ManualRestaurantInputScreen> {
  final _formKey = GlobalKey<FormState>();

  late final TextEditingController _nameController;
  late final TextEditingController _categoryController;
  late final TextEditingController _subCategoryController;
  late final TextEditingController _descriptionController;
  late final TextEditingController _phoneController;
  late final TextEditingController _roadAddressController;
  late final TextEditingController _jibunAddressController;
  late final TextEditingController _latitudeController;
  late final TextEditingController _longitudeController;
  late final TextEditingController _naverUrlController;

  @override
  void initState() {
    super.initState();
    _nameController = TextEditingController();
    _categoryController = TextEditingController();
    _subCategoryController = TextEditingController();
    _descriptionController = TextEditingController();
    _phoneController = TextEditingController();
    _roadAddressController = TextEditingController();
    _jibunAddressController = TextEditingController();
    _latitudeController = TextEditingController();
    _longitudeController = TextEditingController();
    _naverUrlController = TextEditingController();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      ref.read(addRestaurantViewModelProvider.notifier).reset();
    });
  }

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

  void _onFieldChanged(String _) {
    final viewModel = ref.read(addRestaurantViewModelProvider.notifier);
    final formData = RestaurantFormData.fromControllers(
      nameController: _nameController,
      categoryController: _categoryController,
      subCategoryController: _subCategoryController,
      descriptionController: _descriptionController,
      phoneController: _phoneController,
      roadAddressController: _roadAddressController,
      jibunAddressController: _jibunAddressController,
      latitudeController: _latitudeController,
      longitudeController: _longitudeController,
      naverUrlController: _naverUrlController,
    );
    viewModel.updateFormData(formData);
  }

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

    final viewModel = ref.read(addRestaurantViewModelProvider.notifier);
    final success = await viewModel.saveRestaurant();

    if (!mounted) return;

    if (success) {
      Navigator.of(context).pop(true);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Row(
            children: const [
              Icon(Icons.check_circle, color: Colors.white, size: 20),
              SizedBox(width: 8),
              Text('맛집이 추가되었습니다'),
            ],
          ),
          backgroundColor: Colors.green,
        ),
      );
    } else {
      final errorMessage =
          ref.read(addRestaurantViewModelProvider).errorMessage ??
          '저장에 실패했습니다.';
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(errorMessage),
          backgroundColor: Colors.redAccent,
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    final isDark = Theme.of(context).brightness == Brightness.dark;
    final state = ref.watch(addRestaurantViewModelProvider);
    final categories = ref
        .watch(categoriesProvider)
        .maybeWhen(data: (list) => list, orElse: () => const <String>[]);
    final subCategories = ref
        .watch(subCategoriesProvider)
        .maybeWhen(data: (list) => list, orElse: () => const <String>[]);

    return Scaffold(
      appBar: AppBar(
        title: const Text('직접 입력'),
        backgroundColor: isDark
            ? AppColors.darkPrimary
            : AppColors.lightPrimary,
        foregroundColor: Colors.white,
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(24),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Text('가게 정보를 직접 입력하세요', style: AppTypography.body1(isDark)),
              const SizedBox(height: 16),
              AddRestaurantForm(
                formKey: _formKey,
                nameController: _nameController,
                categoryController: _categoryController,
                subCategoryController: _subCategoryController,
                descriptionController: _descriptionController,
                phoneController: _phoneController,
                roadAddressController: _roadAddressController,
                jibunAddressController: _jibunAddressController,
                latitudeController: _latitudeController,
                longitudeController: _longitudeController,
                onFieldChanged: _onFieldChanged,
                categories: categories,
                subCategories: subCategories,
                geocodingStatus: state.geocodingStatus,
              ),
              const SizedBox(height: 24),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  TextButton(
                    onPressed: state.isLoading
                        ? null
                        : () => Navigator.of(context).pop(),
                    child: const Text('취소'),
                  ),
                  const SizedBox(width: 8),
                  ElevatedButton(
                    onPressed: state.isLoading ? null : _save,
                    child: state.isLoading
                        ? const SizedBox(
                            width: 18,
                            height: 18,
                            child: CircularProgressIndicator(
                              strokeWidth: 2,
                              valueColor: AlwaysStoppedAnimation<Color>(
                                Colors.white,
                              ),
                            ),
                          )
                        : const Text('저장'),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
