/// Page: Payment Detail Page
///
/// Displays detailed information about an invoice/payment.
library;

import 'package:flutter/material.dart';
import 'package:worker/core/widgets/loading_indicator.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
import 'package:worker/core/constants/ui_constants.dart';
import 'package:worker/core/database/models/enums.dart';
import 'package:worker/core/theme/colors.dart';
import 'package:worker/core/utils/extensions.dart';
import 'package:worker/features/orders/presentation/providers/invoices_provider.dart';

/// Payment Detail Page
///
/// Features:
/// - Invoice header with status
/// - Payment summary
/// - Customer information
/// - Payment history
/// - Action buttons
class PaymentDetailPage extends ConsumerWidget {
  const PaymentDetailPage({required this.invoiceId, super.key});

  /// Invoice ID
  final String invoiceId;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final colorScheme = Theme.of(context).colorScheme;
    final invoicesAsync = ref.watch(invoicesProvider);

    return Scaffold(
      backgroundColor: colorScheme.surfaceContainerLowest,
      appBar: AppBar(
        leading: IconButton(
          icon: FaIcon(FontAwesomeIcons.arrowLeft, color: colorScheme.onSurface, size: 20),
          onPressed: () => context.pop(),
        ),
        title: Text(
          'Chi tiết Hóa đơn',
          style: TextStyle(color: colorScheme.onSurface),
        ),
        elevation: AppBarSpecs.elevation,
        backgroundColor: colorScheme.surface,
        foregroundColor: colorScheme.onSurface,
        centerTitle: false,
        actions: [
          IconButton(
            icon: FaIcon(FontAwesomeIcons.shareNodes, color: colorScheme.onSurface, size: 20),
            onPressed: () {
              // TODO: Implement share functionality
              ScaffoldMessenger.of(
                context,
              ).showSnackBar(const SnackBar(content: Text('Chia sẻ hóa đơn')));
            },
          ),
        ],
      ),
      body: invoicesAsync.when(
        data: (invoices) {
          final invoice = invoices.firstWhere(
            (inv) => inv.invoiceId == invoiceId,
            orElse: () => invoices.first,
          );


          return SingleChildScrollView(
            padding: const EdgeInsets.all(4),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              spacing: 12,
              children: [
                // Invoice Header Card
                _buildInvoiceHeader(
                  context,
                  invoice.invoiceNumber,
                  invoice.orderId,
                  invoice.issueDate,
                  invoice.status,
                  invoice.totalAmount,
                  invoice.amountPaid,
                  invoice.amountRemaining,
                ),


                // Dates and Customer Info Card
                _buildCustomerInfo(
                  context,
                  invoice.issueDate,
                  invoice.dueDate,
                  invoice.isOverdue,
                ),


                // Product List Card
                _buildProductList(context),


                // Payment History Card
                _buildPaymentHistory(
                  context,
                  invoice.amountPaid,
                  invoice.issueDate
                ),


                // Download Section Card
                _buildDownloadSection(context, invoice.invoiceNumber),


                // Support Button
                Container(
                  width: double.infinity,
                  margin: const EdgeInsets.symmetric(horizontal: 16),
                  child: OutlinedButton.icon(
                    onPressed: () {
                      // TODO: Navigate to chat/support
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(content: Text('Liên hệ hỗ trợ')),
                      );
                    },
                    icon: const FaIcon(FontAwesomeIcons.message, size: 18),
                    label: const Text('Liên hệ hỗ trợ'),
                    style: OutlinedButton.styleFrom(
                      padding: const EdgeInsets.symmetric(
                        vertical: 16,
                        horizontal: 16,
                      ),
                      side: BorderSide(
                        color: colorScheme.outlineVariant,
                        width: 2,
                      ),
                      foregroundColor: colorScheme.onSurface,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                    ),
                  ),
                ),


                // Payment Button
                Container(
                  width: double.infinity,
                  margin: const EdgeInsets.symmetric(horizontal: 16),
                  child: ElevatedButton.icon(
                    onPressed:
                        (invoice.status == InvoiceStatus.paid || invoice.isPaid)
                        ? null
                        : () {
                            // TODO: Navigate to payment page
                            ScaffoldMessenger.of(context).showSnackBar(
                              const SnackBar(
                                content: Text('Mở cổng thanh toán'),
                              ),
                            );
                          },
                    icon: FaIcon(
                      (invoice.status == InvoiceStatus.paid || invoice.isPaid)
                          ? FontAwesomeIcons.solidCircleCheck
                          : FontAwesomeIcons.creditCard,
                      size: 18,
                    ),
                    label: Text(
                      (invoice.status == InvoiceStatus.paid || invoice.isPaid)
                          ? 'Đã hoàn tất'
                          : 'Thanh toán',
                    ),
                    style: ElevatedButton.styleFrom(
                      padding: const EdgeInsets.symmetric(vertical: 16),
                      backgroundColor:
                          (invoice.status == InvoiceStatus.paid ||
                              invoice.isPaid)
                          ? AppColors.success
                          : colorScheme.primary,
                      disabledBackgroundColor: AppColors.success,
                      foregroundColor: colorScheme.surface,
                      disabledForegroundColor: colorScheme.surface,
                      elevation: 0,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                    ),
                  ),
                ),

              ],
            ),
          );
        },
        loading: () => const CustomLoadingIndicator(),
        error: (error, stack) => Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const FaIcon(
                FontAwesomeIcons.circleExclamation,
                size: 64,
                color: AppColors.danger,
              ),
              const SizedBox(height: 16),
              Text(
                'Không tìm thấy hóa đơn',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.w600,
                  color: colorScheme.onSurface,
                ),
              ),
              const SizedBox(height: 24),
              ElevatedButton(
                onPressed: () => context.pop(),
                child: const Text('Quay lại'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// Build invoice header section
  Widget _buildInvoiceHeader(
    BuildContext context,
    String invoiceNumber,
    String? orderId,
    DateTime issueDate,
    InvoiceStatus status,
    double totalAmount,
    double amountPaid,
    double amountRemaining,
  ) {
    final colorScheme = Theme.of(context).colorScheme;

    return Card(
      elevation: 1,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          children: [
            // Invoice ID and Status
            Column(
              children: [
                Text(
                  '#$invoiceNumber',
                  style: TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.w700,
                    color: colorScheme.onSurface,
                  ),
                ),
                const SizedBox(height: 8),
                if (orderId != null)
                  Text(
                    'Đơn hàng: #$orderId | Ngày đặt: ${_formatDate(issueDate)}',
                    style: TextStyle(
                      fontSize: 14,
                      color: colorScheme.onSurfaceVariant,
                    ),
                  ),
                const SizedBox(height: 12),
                _buildStatusBadge(status),
              ],
            ),

            const Padding(
              padding: EdgeInsets.symmetric(vertical: 20),
              child: Divider(height: 1),
            ),

            // Payment Summary
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: colorScheme.surfaceContainerLowest,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                children: [
                  _buildSummaryRow(
                    context,
                    'Tổng tiền hóa đơn:',
                    totalAmount.toVNCurrency,
                  ),
                  const SizedBox(height: 12),
                  _buildSummaryRow(
                    context,
                    'Đã thanh toán:',
                    amountPaid.toVNCurrency,
                  ),
                  const Padding(
                    padding: EdgeInsets.symmetric(vertical: 12),
                    child: Divider(height: 2, thickness: 2),
                  ),
                  _buildSummaryRow(
                    context,
                    'Còn lại:',
                    amountRemaining.toVNCurrency,
                    isHighlighted: true,
                    valueColor: amountRemaining > 0
                        ? AppColors.danger
                        : AppColors.success,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// Build customer info and dates section
  Widget _buildCustomerInfo(
    BuildContext context,
    DateTime issueDate,
    DateTime dueDate,
    bool isOverdue,
  ) {
    final colorScheme = Theme.of(context).colorScheme;

    return Card(
      elevation: 1,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          children: [
            // Dates Grid
            Row(
              children: [
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'Ngày đặt hàng',
                        style: TextStyle(
                          fontSize: 12,
                          color: colorScheme.onSurfaceVariant,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        _formatDate(issueDate),
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                          color: colorScheme.onSurface,
                        ),
                      ),
                    ],
                  ),
                ),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'Hạn thanh toán',
                        style: TextStyle(
                          fontSize: 12,
                          color: colorScheme.onSurfaceVariant,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        _formatDate(dueDate),
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                          color: isOverdue
                              ? AppColors.danger
                              : colorScheme.onSurface,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),

            const SizedBox(height: 20),

            // Customer Info Box
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: colorScheme.surfaceContainerLowest,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'Thông tin khách hàng',
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      color: colorScheme.onSurface,
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    'Công ty TNHH Xây Dựng Minh An\n'
                    'Địa chỉ: 123 Nguyễn Văn Linh, Quận 7, TP.HCM\n'
                    'SĐT: 0901234567 | Email: contact@minhan.com',
                    style: TextStyle(
                      fontSize: 14,
                      color: colorScheme.onSurfaceVariant,
                      height: 1.5,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// Build product list section
  Widget _buildProductList(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;

    // Mock product data - in real app, this would come from order items
    final products = [
      {
        'name': 'Gạch Granite Eurotile Premium 60x60',
        'sku': 'GT-PR-6060-001',
        'quantity': '150 m²',
        'price': '450.000đ/m²',
      },
      {
        'name': 'Gạch Ceramic Cao Cấp 30x60',
        'sku': 'CE-CC-3060-002',
        'quantity': '80 m²',
        'price': '280.000đ/m²',
      },
      {
        'name': 'Keo dán gạch chuyên dụng',
        'sku': 'KD-CD-001',
        'quantity': '20 bao',
        'price': '85.000đ/bao',
      },
    ];

    return Card(
      elevation: 1,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                FaIcon(FontAwesomeIcons.box, color: colorScheme.primary, size: 18),
                const SizedBox(width: 8),
                Text(
                  'Danh sách sản phẩm',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.w700,
                    color: colorScheme.onSurface,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),

            ...products
                .map(
                  (product) => Container(
                    margin: const EdgeInsets.only(bottom: 12),
                    padding: const EdgeInsets.all(16),
                    decoration: BoxDecoration(
                      border: Border.all(color: colorScheme.outlineVariant),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // Product image placeholder
                        Container(
                          width: 60,
                          height: 60,
                          decoration: BoxDecoration(
                            color: colorScheme.surfaceContainerLowest,
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: FaIcon(
                            FontAwesomeIcons.image,
                            color: colorScheme.onSurfaceVariant,
                            size: 22,
                          ),
                        ),
                        const SizedBox(width: 16),
                        // Product info
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                product['name']!,
                                style: TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.w600,
                                  color: colorScheme.onSurface,
                                ),
                              ),
                              const SizedBox(height: 4),
                              Text(
                                'SKU: ${product['sku']}',
                                style: TextStyle(
                                  fontSize: 12,
                                  color: colorScheme.onSurfaceVariant,
                                ),
                              ),
                              const SizedBox(height: 8),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                    'Số lượng: ${product['quantity']}',
                                    style: TextStyle(
                                      fontSize: 12,
                                      color: colorScheme.onSurfaceVariant,
                                    ),
                                  ),
                                  Text(
                                    product['price']!,
                                    style: TextStyle(
                                      fontSize: 14,
                                      fontWeight: FontWeight.w600,
                                      color: colorScheme.onSurface,
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                )
                .toList(),
          ],
        ),
      ),
    );
  }

  /// Build payment history section
  Widget _buildPaymentHistory(
    BuildContext context,
    double amountPaid,
    DateTime paymentDate,
  ) {
    final colorScheme = Theme.of(context).colorScheme;
    final hasHistory = amountPaid > 0;

    return Card(
      elevation: 1,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                FaIcon(FontAwesomeIcons.clockRotateLeft, color: colorScheme.primary, size: 18),
                const SizedBox(width: 8),
                Text(
                  'Lịch sử thanh toán',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.w700,
                    color: colorScheme.onSurface,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),

            if (hasHistory)
              Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  border: Border.all(color: colorScheme.outlineVariant),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Row(
                  children: [
                    Container(
                      width: 40,
                      height: 40,
                      decoration: BoxDecoration(
                        color: AppColors.success.withValues(alpha: 0.1),
                        shape: BoxShape.circle,
                      ),
                      child: const Center(
                        child: FaIcon(
                          FontAwesomeIcons.check,
                          color: AppColors.success,
                          size: 18,
                        ),
                      ),
                    ),
                    const SizedBox(width: 16),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            'Thanh toán lần 1',
                            style: TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w600,
                              color: colorScheme.onSurface,
                            ),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            'Chuyển khoản | Ref: TK20241020001',
                            style: TextStyle(
                              fontSize: 12,
                              color: colorScheme.onSurfaceVariant,
                            ),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            '${_formatDate(paymentDate)} - 14:30',
                            style: TextStyle(
                              fontSize: 12,
                              color: colorScheme.onSurfaceVariant,
                            ),
                          ),
                        ],
                      ),
                    ),
                    Text(
                      amountPaid.toVNCurrency,
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                        color: AppColors.success,
                      ),
                    ),
                  ],
                ),
              )
            else
              Center(
                child: Padding(
                  padding: const EdgeInsets.symmetric(vertical: 20),
                  child: Column(
                    children: [
                      FaIcon(
                        FontAwesomeIcons.receipt,
                        size: 48,
                        color: colorScheme.outlineVariant,
                      ),
                      const SizedBox(height: 12),
                      Text(
                        'Chưa có lịch sử thanh toán',
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                          color: colorScheme.onSurfaceVariant,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        'Hóa đơn này chưa được thanh toán',
                        style: TextStyle(
                          fontSize: 14,
                          color: colorScheme.onSurfaceVariant,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  /// Build download section
  Widget _buildDownloadSection(BuildContext context, String invoiceNumber) {
    final colorScheme = Theme.of(context).colorScheme;

    return Card(
      elevation: 1,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                FaIcon(FontAwesomeIcons.download, color: colorScheme.primary, size: 18),
                const SizedBox(width: 8),
                Text(
                  'Tải chứng từ',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.w700,
                    color: colorScheme.onSurface,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            _buildDownloadButton(
              context,
              icon: FontAwesomeIcons.filePdf,
              label: 'Hóa đơn PDF',
              onTap: () {
                // TODO: Download invoice PDF
              },
            ),
            const SizedBox(height: 12),
            _buildDownloadButton(
              context,
              icon: FontAwesomeIcons.receipt,
              label: 'Phiếu thu PDF',
              onTap: () {
                // TODO: Download receipt PDF
              },
            ),
          ],
        ),
      ),
    );
  }

  /// Build download button
  Widget _buildDownloadButton(
    BuildContext context, {
    required IconData icon,
    required String label,
    required VoidCallback onTap,
  }) {
    final colorScheme = Theme.of(context).colorScheme;

    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(8),
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
        decoration: BoxDecoration(
          color: colorScheme.surfaceContainerLowest,
          border: Border.all(color: colorScheme.outlineVariant),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            FaIcon(icon, size: 18, color: colorScheme.onSurfaceVariant),
            const SizedBox(width: 8),
            Flexible(
              child: Text(
                label,
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                  color: colorScheme.onSurfaceVariant,
                ),
                textAlign: TextAlign.center,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// Build status badge
  Widget _buildStatusBadge(InvoiceStatus status) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      decoration: BoxDecoration(
        color: _getStatusColor(status).withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(20),
        border: Border.all(
          color: _getStatusColor(status).withValues(alpha: 0.3),
          width: 1,
        ),
      ),
      child: Text(
        _getStatusText(status).toUpperCase(),
        style: TextStyle(
          fontSize: 14,
          fontWeight: FontWeight.w700,
          color: _getStatusColor(status),
        ),
      ),
    );
  }

  /// Build summary row
  Widget _buildSummaryRow(
    BuildContext context,
    String label,
    String value, {
    bool isHighlighted = false,
    Color? valueColor,
  }) {
    final colorScheme = Theme.of(context).colorScheme;

    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          label,
          style: TextStyle(
            fontSize: isHighlighted ? 18 : 16,
            fontWeight: isHighlighted ? FontWeight.w700 : FontWeight.w400,
            color: colorScheme.onSurfaceVariant,
          ),
        ),
        Text(
          value,
          style: TextStyle(
            fontSize: isHighlighted ? 18 : 16,
            fontWeight: isHighlighted ? FontWeight.w700 : FontWeight.w600,
            color: valueColor ?? colorScheme.onSurface,
          ),
        ),
      ],
    );
  }

  /// Get status color
  Color _getStatusColor(InvoiceStatus status) {
    switch (status) {
      case InvoiceStatus.draft:
        return AppColors.grey500;
      case InvoiceStatus.issued:
        return AppColors.warning;
      case InvoiceStatus.partiallyPaid:
        return AppColors.info;
      case InvoiceStatus.paid:
        return AppColors.success;
      case InvoiceStatus.overdue:
        return AppColors.danger;
      case InvoiceStatus.cancelled:
        return AppColors.grey500;
      case InvoiceStatus.refunded:
        return AppColors.warning;
    }
  }

  /// Get status text
  String _getStatusText(InvoiceStatus status) {
    switch (status) {
      case InvoiceStatus.draft:
        return 'Nháp';
      case InvoiceStatus.issued:
        return 'Chưa thanh toán';
      case InvoiceStatus.partiallyPaid:
        return 'Một phần';
      case InvoiceStatus.paid:
        return 'Đã thanh toán';
      case InvoiceStatus.overdue:
        return 'Quá hạn';
      case InvoiceStatus.cancelled:
        return 'Đã hủy';
      case InvoiceStatus.refunded:
        return 'Đã hoàn tiền';
    }
  }

  /// Format date
  String _formatDate(DateTime date) {
    return DateFormat('dd/MM/yyyy').format(date);
  }
}
