import 'package:flutter/material.dart';
import '../controllers/sms_scan_controller.dart';
import '../widgets/sms_scan/scan_loading_widget.dart';
import '../widgets/sms_scan/scan_initial_widget.dart';
import '../widgets/sms_scan/scan_progress_widget.dart';
import '../widgets/sms_scan/subscription_card_widget.dart';
import '../widgets/common/snackbar/app_snackbar.dart';
import '../l10n/app_localizations.dart';
import '../widgets/payment_card/payment_card_form_sheet.dart';
import '../routes/app_routes.dart';
import '../models/payment_card_suggestion.dart';
import '../theme/ui_constants.dart';

class SmsScanScreen extends StatefulWidget {
  const SmsScanScreen({super.key});

  @override
  State<SmsScanScreen> createState() => _SmsScanScreenState();
}

class _SmsScanScreenState extends State<SmsScanScreen> {
  late SmsScanController _controller;
  late final ScrollController _scrollController;

  @override
  void initState() {
    super.initState();
    _controller = SmsScanController();
    _controller.addListener(_handleControllerUpdate);
    _scrollController = ScrollController();
  }

  @override
  void dispose() {
    _controller.removeListener(_handleControllerUpdate);
    _controller.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  void _handleControllerUpdate() {
    if (mounted) {
      setState(() {});
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _controller.initializeWebsiteUrl(context);
  }

  Widget _buildContent() {
    if (_controller.isLoading) {
      return const ScanLoadingWidget();
    }

    if (_controller.scannedSubscriptions.isEmpty) {
      return ScanInitialWidget(
        onScanPressed: () => _controller.startScan(context),
        errorMessage: _controller.errorMessage,
      );
    }

    // 모든 구독 처리 완료 확인
    if (_controller.currentIndex >= _controller.scannedSubscriptions.length) {
      // 중복 스낵바 방지를 위해 바로 초기 화면으로
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted && _controller.scannedSubscriptions.isNotEmpty) {
          AppSnackBar.showSuccess(
            context: context,
            message: AppLocalizations.of(context).allSubscriptionsProcessed,
          );
          // 상태 초기화
          _controller.resetState();
        }
      });
      return ScanInitialWidget(
        onScanPressed: () => _controller.startScan(context),
        errorMessage: _controller.errorMessage,
      );
    }

    final currentSubscription =
        _controller.scannedSubscriptions[_controller.currentIndex];

    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16.0),
          child: ScanProgressWidget(
            currentIndex: _controller.currentIndex,
            totalCount: _controller.scannedSubscriptions.length,
          ),
        ),
        const SizedBox(height: 24),
        SubscriptionCardWidget(
          subscription: currentSubscription,
          serviceNameController: _controller.serviceNameController,
          websiteUrlController: _controller.websiteUrlController,
          selectedCategoryId: _controller.selectedCategoryId,
          onCategoryChanged: _controller.setSelectedCategoryId,
          selectedPaymentCardId: _controller.selectedPaymentCardId,
          onPaymentCardChanged: _controller.setSelectedPaymentCardId,
          enableServiceNameEditing: _controller.isServiceNameEditable,
          onServiceNameChanged: _controller.isServiceNameEditable
              ? (value) => _controller.updateCurrentServiceName(context, value)
              : null,
          onAddCard: () async {
            final newCardId = await PaymentCardFormSheet.show(context);
            if (newCardId != null) {
              _controller.setSelectedPaymentCardId(newCardId);
            }
          },
          onManageCards: () {
            Navigator.of(context).pushNamed(AppRoutes.paymentCardManagement);
          },
          onAdd: _handleAddSubscription,
          onSkip: _handleSkipSubscription,
          detectedCardSuggestion: _controller.currentSuggestion,
          showDetectedCardShortcut: _controller.shouldSuggestCardCreation,
          onAddDetectedCard: (suggestion) =>
              _handleDetectedCardCreation(suggestion),
        ),
      ],
    );
  }

  Future<void> _handleAddSubscription() async {
    await _controller.addCurrentSubscription(context);
    if (!mounted) return;
    WidgetsBinding.instance.addPostFrameCallback((_) => _scrollToTop());
  }

  void _handleSkipSubscription() {
    _controller.skipCurrentSubscription(context);
    WidgetsBinding.instance.addPostFrameCallback((_) => _scrollToTop());
  }

  Future<void> _handleDetectedCardCreation(
      PaymentCardSuggestion suggestion) async {
    final newCardId = await PaymentCardFormSheet.show(
      context,
      initialIssuerName: suggestion.issuerName,
      initialLast4: suggestion.last4,
    );
    if (newCardId != null) {
      _controller.setSelectedPaymentCardId(newCardId);
    }
  }

  void _scrollToTop() {
    if (!_scrollController.hasClients) return;
    _scrollController.animateTo(
      0,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeOut,
    );
  }

  @override
  Widget build(BuildContext context) {
    // 로딩 중일 때는 화면 정중앙에 표시
    if (_controller.isLoading) {
      return const ScanLoadingWidget();
    }

    return SingleChildScrollView(
      controller: _scrollController,
      padding: EdgeInsets.zero,
      child: Padding(
        padding: const EdgeInsets.only(top: UIConstants.pageTopPadding),
        child: Column(
          children: [
            _buildContent(),
            // FloatingNavigationBar를 위한 충분한 하단 여백
            SizedBox(
              height: 120 + MediaQuery.of(context).padding.bottom,
            ),
          ],
        ),
      ),
    );
  }
}
