import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/invoices_controller.dart';

class InvoicesListView extends GetView<InvoicesController> {
  const InvoicesListView({super.key});

  @override
  Widget build(BuildContext context) {
    final isDark = Theme.of(context).brightness == Brightness.dark;

    return Column(
      children: [
        // App Bar replacement
        Container(
          padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top, left: 8, right: 8, bottom: 12),
          color: isDark ? const Color(0xFF1E1E2E) : const Color(0xFF0F4C81),
          child: Row(
            children: [
              const SizedBox(width: 48),
              Expanded(
                child: Center(
                  child: Text(
                    'الفواتير',
                    style: TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold),
                  ),
                ),
              ),
              IconButton(
                icon: const Icon(Icons.search_rounded, color: Colors.white),
                onPressed: () => controller.toggleSearch(),
              ),
              IconButton(
                icon: const Icon(Icons.refresh_rounded, color: Colors.white),
                onPressed: () => controller.loadInvoices(),
              ),
            ],
          ),
        ),

        // Search Bar
        Obx(() => AnimatedContainer(
          duration: const Duration(milliseconds: 300),
          height: controller.isSearching.value ? 64 : 0,
          child: controller.isSearching.value
              ? Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                  child: TextField(
                    onChanged: (v) => controller.searchQuery.value = v,
                    textDirection: TextDirection.rtl,
                    decoration: InputDecoration(
                      hintText: 'بحث بالرقم أو اسم المورد...',
                      prefixIcon: const Icon(Icons.search, size: 20),
                      filled: true,
                      fillColor: isDark ? Colors.white10 : Colors.white,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(12),
                        borderSide: BorderSide.none,
                      ),
                      contentPadding: const EdgeInsets.symmetric(horizontal: 16),
                    ),
                  ),
                )
              : const SizedBox(),
        )),

        // Filter Tabs
        Container(
          height: 44,
          margin: const EdgeInsets.symmetric(vertical: 8),
          child: ListView(
            scrollDirection: Axis.horizontal,
            padding: const EdgeInsets.symmetric(horizontal: 16),
            children: [
              _buildFilterChip('الكل', 'all', controller, isDark),
              _buildFilterChip('قيد المعالجة', 'uploaded', controller, isDark),
              _buildFilterChip('جاهزة', 'extracted', controller, isDark),
              _buildFilterChip('معتمدة', 'approved', controller, isDark),
              _buildFilterChip('مُقدَّمة', 'submitted', controller, isDark),
            ],
          ),
        ),

        // Invoice List
        Expanded(
          child: Obx(() {
            if (controller.isLoading.value) {
              return _buildShimmerList();
            }

            final invoices = controller.filteredInvoices;

            if (invoices.isEmpty) {
              return _buildEmptyState(isDark);
            }

            return RefreshIndicator(
              onRefresh: () async => controller.loadInvoices(),
              child: ListView.builder(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                itemCount: invoices.length,
                itemBuilder: (context, index) => _buildInvoiceCard(invoices[index], isDark),
              ),
            );
          }),
        ),
      ],
    );
  }

  Widget _buildFilterChip(String label, String value, InvoicesController ctrl, bool isDark) {
    return Obx(() {
      final isSelected = ctrl.filterStatus.value == value;
      return Padding(
        padding: const EdgeInsets.only(left: 8),
        child: ChoiceChip(
          label: Text(label),
          selected: isSelected,
          onSelected: (_) => ctrl.filterStatus.value = value,
          selectedColor: const Color(0xFF0F4C81),
          backgroundColor: isDark ? Colors.white10 : Colors.white,
          labelStyle: TextStyle(
            color: isSelected ? Colors.white : (isDark ? Colors.white70 : Colors.black87),
            fontWeight: isSelected ? FontWeight.w700 : FontWeight.w400,
            fontSize: 13,
          ),
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
          side: BorderSide(color: isSelected ? Colors.transparent : Colors.grey.shade300),
        ),
      );
    });
  }

  Widget _buildInvoiceCard(Map<String, dynamic> inv, bool isDark) {
    final status = inv['status'] ?? '';
    Color statusColor;
    String statusText;
    IconData statusIcon;

    switch (status) {
      case 'approved':
        statusColor = const Color(0xFF10B981);
        statusText = '✓ معتمدة';
        statusIcon = Icons.check_circle;
        break;
      case 'extracted':
        statusColor = const Color(0xFF3B82F6);
        statusText = 'جاهزة للتدقيق';
        statusIcon = Icons.pending_actions;
        break;
      case 'submitted':
        statusColor = const Color(0xFF6366F1);
        statusText = 'مُقدَّمة لجوفتورة';
        statusIcon = Icons.verified;
        break;
      default:
        statusColor = const Color(0xFFF59E0B);
        statusText = 'قيد المعالجة';
        statusIcon = Icons.hourglass_empty;
    }

    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      elevation: 0,
      color: isDark ? const Color(0xFF1E1E2E) : Colors.white,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(14),
        side: BorderSide(color: isDark ? Colors.white10 : Colors.grey.shade200),
      ),
      child: InkWell(
        borderRadius: BorderRadius.circular(14),
        onTap: () {
          Get.toNamed('/invoice-detail', arguments: {'id': inv['id'].toString()});
        },
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Row(
            children: [
              Container(
                width: 48,
                height: 48,
                decoration: BoxDecoration(
                  color: statusColor.withValues(alpha: 0.1),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Icon(statusIcon, color: statusColor, size: 24),
              ),
              const SizedBox(width: 14),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      inv['supplier_name'] ?? inv['company_name'] ?? 'بدون اسم',
                      style: TextStyle(
                        fontWeight: FontWeight.w700,
                        fontSize: 15,
                        color: isDark ? Colors.white : const Color(0xFF0F172A),
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 4),
                    Text(
                      '# ${inv['invoice_number'] ?? '—'}  •  ${inv['invoice_date'] ?? '—'}',
                      style: TextStyle(
                        fontSize: 12,
                        color: isDark ? Colors.white38 : const Color(0xFF94A3B8),
                        fontFamily: 'monospace',
                      ),
                    ),
                  ],
                ),
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Text(
                    '${double.tryParse(inv['grand_total']?.toString() ?? '0')?.toStringAsFixed(2) ?? '0.00'} JOD',
                    style: TextStyle(
                      fontWeight: FontWeight.w800,
                      fontSize: 14,
                      color: isDark ? const Color(0xFF5EEAD4) : const Color(0xFF008080),
                      fontFamily: 'monospace',
                    ),
                  ),
                  const SizedBox(height: 6),
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
                    decoration: BoxDecoration(
                      color: statusColor.withValues(alpha: 0.1),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Text(
                      statusText,
                      style: TextStyle(color: statusColor, fontSize: 11, fontWeight: FontWeight.w600),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildEmptyState(bool isDark) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.receipt_long_rounded, size: 80, color: isDark ? Colors.white12 : Colors.grey.shade300),
          const SizedBox(height: 16),
          Text(
            'لا توجد فواتير بعد',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w600,
              color: isDark ? Colors.white38 : Colors.grey,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            'ابدأ بتصوير فواتيرك من زر الماسح الضوئي',
            style: TextStyle(fontSize: 13, color: isDark ? Colors.white24 : Colors.grey.shade400),
          ),
        ],
      ),
    );
  }

  Widget _buildShimmerList() {
    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: 5,
      itemBuilder: (context, index) => Container(
        height: 80,
        margin: const EdgeInsets.only(bottom: 12),
        decoration: BoxDecoration(
          color: Colors.grey.withValues(alpha: 0.1),
          borderRadius: BorderRadius.circular(14),
        ),
      ),
    );
  }
}
