import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
import 'package:real_estate_mobile/core/constants/app_colors.dart';
import 'package:real_estate_mobile/features/profile/data/profile_repository.dart';

class PaymentSuccessScreen extends ConsumerStatefulWidget {
  final String? sessionId;

  const PaymentSuccessScreen({super.key, this.sessionId});

  @override
  ConsumerState<PaymentSuccessScreen> createState() =>
      _PaymentSuccessScreenState();
}

class _PaymentSuccessScreenState extends ConsumerState<PaymentSuccessScreen> {
  Map<String, dynamic>? _subscription;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadSubscription();
  }

  Future<void> _loadSubscription() async {
    try {
      final repo = ProfileRepository();
      final sub = await repo.getSubscription();
      if (mounted) {
        setState(() {
          _subscription = sub;
          _isLoading = false;
        });
      }
    } catch (_) {
      if (mounted) setState(() => _isLoading = false);
    }
  }

  String _formatDate(String? dateStr) {
    if (dateStr == null) return 'N/A';
    try {
      final date = DateTime.parse(dateStr);
      return DateFormat('MMM dd, yyyy').format(date);
    } catch (_) {
      return dateStr;
    }
  }

  String _formatAmount(dynamic amount) {
    if (amount == null) return '\$499.00';
    if (amount is int) return '\$${(amount / 100).toStringAsFixed(2)}';
    if (amount is double) return '\$${(amount / 100).toStringAsFixed(2)}';
    return '\$$amount';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: _isLoading
            ? const Center(
                child:
                    CircularProgressIndicator(color: AppColors.accentOrange))
            : SingleChildScrollView(
                padding: const EdgeInsets.fromLTRB(24, 20, 24, 40),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // Back button
                    GestureDetector(
                      onTap: () => context.go('/'),
                      child: const Icon(Icons.arrow_back,
                          color: AppColors.primaryDark),
                    ),
                    const SizedBox(height: 20),

                    // Title
                    const Center(
                      child: Text(
                        'Payments',
                        style: TextStyle(
                          fontFamily: 'Fractul',
                          fontSize: 25,
                          fontWeight: FontWeight.w700,
                          color: AppColors.primaryDark,
                        ),
                      ),
                    ),
                    const SizedBox(height: 12),
                    const Center(
                      child: Text(
                        'Manage Your billing cycles , upgrade your\nplan , or boost individual listings',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontFamily: 'SourceSerif4',
                          fontSize: 14,
                          color: AppColors.primaryDark,
                        ),
                      ),
                    ),
                    const SizedBox(height: 30),

                    // Success card
                    Container(
                      width: double.infinity,
                      padding: const EdgeInsets.symmetric(
                          vertical: 32, horizontal: 24),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(10),
                        border: Border.all(
                          color: AppColors.primaryDark.withValues(alpha: 0.5),
                          width: 0.5,
                        ),
                      ),
                      child: Column(
                        children: [
                          // Success icon
                          Container(
                            width: 40,
                            height: 40,
                            decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              border: Border.all(
                                  color: AppColors.accentOrange, width: 2),
                            ),
                            child: const Icon(
                              Icons.check,
                              color: AppColors.accentOrange,
                              size: 24,
                            ),
                          ),
                          const SizedBox(height: 16),

                          // Payment Successful!
                          const Text(
                            'Payment Successful !',
                            style: TextStyle(
                              fontFamily: 'Fractul',
                              fontSize: 20,
                              fontWeight: FontWeight.w700,
                              color: AppColors.primaryDark,
                            ),
                          ),
                          const SizedBox(height: 12),

                          const Text(
                            'Your annual membership is now active. You have\nfull access to all premium features',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              fontFamily: 'SourceSerif4',
                              fontSize: 14,
                              color: AppColors.primaryDark,
                            ),
                          ),
                          const SizedBox(height: 32),

                          // Transaction Details header
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              const Text(
                                'Transaction Details',
                                style: TextStyle(
                                  fontFamily: 'SourceSerif4',
                                  fontSize: 14,
                                  color: AppColors.primaryDark,
                                ),
                              ),
                              Row(
                                children: [
                                  Icon(Icons.verified_user,
                                      size: 18,
                                      color: Colors.green.shade600),
                                  const SizedBox(width: 6),
                                  const Text(
                                    'Verified User',
                                    style: TextStyle(
                                      fontFamily: 'SourceSerif4',
                                      fontSize: 14,
                                      color: AppColors.primaryDark,
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                          const SizedBox(height: 20),

                          // Transaction ID
                          _buildDetailRow(
                            'Transaction ID',
                            widget.sessionId != null &&
                                    widget.sessionId!.length > 16
                                ? 'REQ-${widget.sessionId!.substring(0, 8)}'
                                : 'REQ-${widget.sessionId ?? 'N/A'}',
                          ),
                          const SizedBox(height: 14),

                          // Amount Paid
                          _buildDetailRow(
                            'Amount Paid',
                            _formatAmount(
                                _subscription?['plan']?['amount']),
                          ),
                          const SizedBox(height: 14),

                          // Date
                          _buildDetailRow(
                            'Date',
                            _formatDate(_subscription?['createdAt'] ??
                                DateTime.now().toIso8601String()),
                          ),
                          const SizedBox(height: 14),

                          // Next Renewal Date
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              const Text(
                                'Next Renewal Date',
                                style: TextStyle(
                                  fontFamily: 'SourceSerif4',
                                  fontSize: 14,
                                  color: AppColors.primaryDark,
                                ),
                              ),
                              Text(
                                _formatDate(
                                    _subscription?['currentPeriodEnd']),
                                style: const TextStyle(
                                  fontFamily: 'SourceSerif4',
                                  fontSize: 14,
                                  fontWeight: FontWeight.w600,
                                  color: AppColors.accentOrange,
                                ),
                              ),
                            ],
                          ),
                          const SizedBox(height: 20),

                          // Divider
                          Divider(
                              color:
                                  AppColors.primaryDark.withValues(alpha: 0.2)),
                          const SizedBox(height: 20),

                          // Go To Dashboard button
                          SizedBox(
                            width: 200,
                            child: ElevatedButton.icon(
                              onPressed: () => context.go('/'),
                              icon: const Icon(Icons.dashboard,
                                  size: 18, color: Colors.white),
                              label: const Text(
                                'Go To Dashboard',
                                style: TextStyle(
                                  fontFamily: 'Fractul',
                                  fontSize: 14,
                                  fontWeight: FontWeight.w700,
                                  color: Colors.white,
                                ),
                              ),
                              style: ElevatedButton.styleFrom(
                                backgroundColor: AppColors.accentOrange,
                                padding:
                                    const EdgeInsets.symmetric(vertical: 14),
                                shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(15)),
                              ),
                            ),
                          ),
                          const SizedBox(height: 12),

                          // Download Receipt button
                          SizedBox(
                            width: 200,
                            child: ElevatedButton.icon(
                              onPressed: () {
                                // TODO: implement receipt download
                                ScaffoldMessenger.of(context).showSnackBar(
                                  const SnackBar(
                                      content:
                                          Text('Receipt download coming soon')),
                                );
                              },
                              icon: const Icon(Icons.download,
                                  size: 18, color: Colors.white),
                              label: const Text(
                                'Download Receipt',
                                style: TextStyle(
                                  fontFamily: 'Fractul',
                                  fontSize: 14,
                                  fontWeight: FontWeight.w700,
                                  color: Colors.white,
                                ),
                              ),
                              style: ElevatedButton.styleFrom(
                                backgroundColor: AppColors.accentOrange,
                                padding:
                                    const EdgeInsets.symmetric(vertical: 14),
                                shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(15)),
                              ),
                            ),
                          ),
                          const SizedBox(height: 24),

                          // Trust badges
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(Icons.verified_user,
                                  size: 18, color: Colors.green.shade600),
                              const SizedBox(width: 6),
                              const Text(
                                'Verified User',
                                style: TextStyle(
                                  fontFamily: 'SourceSerif4',
                                  fontSize: 14,
                                  color: AppColors.primaryDark,
                                ),
                              ),
                              const SizedBox(width: 24),
                              const Icon(Icons.lock,
                                  size: 18, color: AppColors.primaryDark),
                              const SizedBox(width: 6),
                              const Text(
                                'Secure Checkout',
                                style: TextStyle(
                                  fontFamily: 'SourceSerif4',
                                  fontSize: 14,
                                  color: AppColors.primaryDark,
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
      ),
    );
  }

  Widget _buildDetailRow(String label, String value) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          label,
          style: TextStyle(
            fontFamily: 'SourceSerif4',
            fontSize: 14,
            color: AppColors.primaryDark.withValues(alpha: 0.5),
          ),
        ),
        Text(
          value,
          style: const TextStyle(
            fontFamily: 'SourceSerif4',
            fontSize: 14,
            color: AppColors.primaryDark,
          ),
        ),
      ],
    );
  }
}
