import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../core/api/api_service.dart';
import '../../core/l10n/app_localizations.dart';
import '../../core/theme/app_theme.dart';
import '../../core/utils/money.dart';
import '../../core/widgets/loading_overlay.dart';

final invoicesProvider =
    FutureProvider.autoDispose.family<Map<String, dynamic>, String>((ref, uuid) async {
  return ref.watch(apiServiceProvider).getInvoices(uuid);
});

class InvoicesScreen extends ConsumerWidget {
  final String participantUuid;

  const InvoicesScreen({super.key, required this.participantUuid});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final l = AppLocalizations.of(context);
    final invoices = ref.watch(invoicesProvider(participantUuid));

    return Scaffold(
      backgroundColor: const Color(0xFFF8FAFC),
      appBar: AppBar(
        title: Text(l.t('invoices')),
        centerTitle: true,
        backgroundColor: Colors.white,
        surfaceTintColor: Colors.transparent,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios_new, size: 18),
          onPressed: () => context.pop(),
        ),
      ),
      body: invoices.when(
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (e, _) => Center(child: Text(l.t('error_occurred'))),
        data: (data) {
          final items = (data['data'] as List?) ?? [];
          if (items.isEmpty) {
            return EmptyState(icon: Icons.receipt_long, message: l.t('no_invoices'));
          }
          return ListView.builder(
            physics: const BouncingScrollPhysics(),
            padding: const EdgeInsets.all(16),
            itemCount: items.length,
            itemBuilder: (ctx, i) {
              final inv = items[i] as Map<String, dynamic>;
              return _InvoiceTile(invoice: inv, index: i);
            },
          );
        },
      ),
    );
  }
}

class _InvoiceTile extends StatelessWidget {
  final Map<String, dynamic> invoice;
  final int index;

  const _InvoiceTile({required this.invoice, required this.index});

  @override
  Widget build(BuildContext context) {
    final status = invoice['status'] ?? 'draft';
    final (statusColor, statusLabel) = _statusInfo(status);
    final total = invoice['total_amount'] ?? 0;
    final balance = invoice['balance_due'] ?? 0;

    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(color: Colors.black.withValues(alpha: 0.03), blurRadius: 8, offset: const Offset(0, 2)),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
                decoration: BoxDecoration(
                  color: statusColor.withValues(alpha: 0.1),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Text(
                  statusLabel,
                  style: TextStyle(fontSize: 11, color: statusColor, fontWeight: FontWeight.w600),
                ),
              ),
              const Spacer(),
              Text(
                invoice['invoice_number'] ?? '',
                style: TextStyle(fontSize: 12, color: Colors.grey.shade500),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Row(
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      invoice['description'] ?? invoice['items_summary'] ?? '',
                      style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 4),
                    Text(
                      invoice['issued_date'] ?? '',
                      style: TextStyle(fontSize: 12, color: Colors.grey.shade500),
                    ),
                  ],
                ),
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Text(
                    formatMoney(total),
                    style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                  ),
                  if (balance > 0)
                    Text(
                      'متبقي: ${formatMoney(balance)}',
                      style: TextStyle(fontSize: 12, color: Colors.red.shade600),
                    ),
                ],
              ),
            ],
          ),
          if (balance > 0 && status != 'cancelled') ...[
            const SizedBox(height: 12),
            SizedBox(
              width: double.infinity,
              height: 40,
              child: ElevatedButton(
                onPressed: () {},
                style: ElevatedButton.styleFrom(
                  backgroundColor: AppTheme.primaryColor,
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                ),
                child: const Text('ادفع الآن', style: TextStyle(fontSize: 13, color: Colors.white)),
              ),
            ),
          ],
        ],
      ),
    )
        .animate(delay: Duration(milliseconds: 60 * index))
        .fadeIn(duration: 400.ms)
        .slideY(begin: 0.04, end: 0, curve: Curves.easeOut);
  }

  (Color, String) _statusInfo(String status) => switch (status) {
        'paid' => (Colors.green, 'مدفوعة'),
        'partially_paid' => (Colors.orange, 'مدفوعة جزئياً'),
        'sent' => (Colors.blue, 'مرسلة'),
        'overdue' => (Colors.red, 'متأخرة'),
        'cancelled' => (Colors.grey, 'ملغاة'),
        'draft' => (Colors.grey.shade600, 'مسودة'),
        _ => (Colors.grey, status),
      };
}
