import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/companies_management_controller.dart';
import 'add_company_view.dart';
import '../../../app/routes/app_pages.dart';

class CompaniesManagementView extends StatelessWidget {
  const CompaniesManagementView({super.key});

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

    return Scaffold(
      appBar: AppBar(
        title: const Text('إدارة الشركات', style: TextStyle(fontFamily: 'El Messiri')),
        centerTitle: true,
        backgroundColor: const Color(0xFF0F4C81),
        foregroundColor: Colors.white,
        elevation: 0,
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh_rounded),
            onPressed: () => controller.fetchCompanies(),
          ),
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () async {
              await Get.to(() => const AddCompanyView());
              controller.fetchCompanies();
            },
          ),
        ],
      ),
      body: Obx(() {
        if (controller.isLoading.value) {
          return const Center(child: CircularProgressIndicator());
        }

        if (controller.companies.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.business_center_outlined, size: 80, color: Colors.grey.shade400),
                const SizedBox(height: 16),
                const Text('لا يوجد شركات مسجلة', style: TextStyle(fontSize: 18, color: Colors.grey)),
                const SizedBox(height: 16),
                ElevatedButton.icon(
                  onPressed: () async {
                    await Get.to(() => const AddCompanyView());
                    controller.fetchCompanies();
                  },
                  icon: const Icon(Icons.add),
                  label: const Text('إضافة شركة'),
                  style: ElevatedButton.styleFrom(backgroundColor: const Color(0xFF0F4C81)),
                ),
              ],
            ),
          );
        }

        return RefreshIndicator(
          onRefresh: controller.fetchCompanies,
          child: ListView.builder(
            padding: const EdgeInsets.all(16),
            itemCount: controller.companies.length,
            itemBuilder: (context, index) {
              final company = controller.companies[index];
              return _buildCompanyCard(company, controller, isDark, context);
            },
          ),
        );
      }),
    );
  }

  Widget _buildCompanyCard(Map<String, dynamic> company, CompaniesManagementController controller, bool isDark, BuildContext context) {
    final invoicesCount = company['invoices_count'] ?? 0;
    final totalAmount = double.tryParse(company['total_amount']?.toString() ?? '0') ?? 0;

    return Card(
      elevation: 0,
      margin: const EdgeInsets.only(bottom: 16),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
        side: BorderSide(color: isDark ? Colors.white10 : Colors.grey.shade200),
      ),
      color: isDark ? const Color(0xFF1E1E2E) : Colors.white,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Header
            Row(
              children: [
                Container(
                  padding: const EdgeInsets.all(10),
                  decoration: BoxDecoration(
                    color: const Color(0xFF0F4C81).withValues(alpha: 0.1),
                    shape: BoxShape.circle,
                  ),
                  child: const Icon(Icons.business, color: Color(0xFF0F4C81)),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        company['name'] ?? 'شركة',
                        style: TextStyle(
                          fontSize: 17, fontWeight: FontWeight.bold,
                          color: isDark ? Colors.white : const Color(0xFF0F172A),
                        ),
                      ),
                      const SizedBox(height: 2),
                      Text(
                        'TIN: ${company['tax_identification_number'] ?? '—'}',
                        style: TextStyle(fontSize: 12, color: isDark ? Colors.white38 : Colors.grey, fontFamily: 'monospace'),
                      ),
                    ],
                  ),
                ),
                PopupMenuButton<String>(
                  icon: Icon(Icons.more_vert, color: isDark ? Colors.white54 : Colors.grey),
                  onSelected: (value) {
                    switch (value) {
                      case 'edit':
                        _showEditDialog(context, company, controller);
                        break;
                      case 'stats':
                        Get.toNamed(AppRoutes.COMPANY_STATS, arguments: {
                          'company_id': company['id'],
                          'company_name': company['name'],
                        });
                        break;
                      case 'delete':
                        _confirmDelete(context, controller, company['id'], company['name'] ?? '');
                        break;
                    }
                  },
                  itemBuilder: (context) => [
                    const PopupMenuItem(value: 'edit', child: Row(children: [Icon(Icons.edit, size: 18), SizedBox(width: 8), Text('تعديل البيانات')])),
                    const PopupMenuItem(value: 'stats', child: Row(children: [Icon(Icons.bar_chart, size: 18), SizedBox(width: 8), Text('الإحصائيات')])),
                    const PopupMenuItem(value: 'delete', child: Row(children: [Icon(Icons.delete, size: 18, color: Colors.red), SizedBox(width: 8), Text('حذف', style: TextStyle(color: Colors.red))])),
                  ],
                ),
              ],
            ),
            const SizedBox(height: 16),

            // Info chips
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: [
                _chip(Icons.receipt_long, '$invoicesCount فاتورة', Colors.blue),
                _chip(Icons.payments, '${totalAmount.toStringAsFixed(2)} JOD', const Color(0xFF10B981)),
                if (company['address'] != null && company['address'].toString().isNotEmpty)
                  _chip(Icons.location_on, company['address'], Colors.orange),
                if (company['is_jofotara_linked'] == 1)
                  _chip(Icons.verified, 'جوفتورة', const Color(0xFF6366F1)),
              ],
            ),

            const SizedBox(height: 12),

            // Action buttons
            Row(
              children: [
                Expanded(
                  child: OutlinedButton.icon(
                    onPressed: () => _showEditDialog(context, company, controller),
                    icon: const Icon(Icons.edit, size: 16),
                    label: const Text('تعديل', style: TextStyle(fontSize: 13)),
                    style: OutlinedButton.styleFrom(
                      foregroundColor: const Color(0xFF0F4C81),
                      side: const BorderSide(color: Color(0xFF0F4C81)),
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                    ),
                  ),
                ),
                const SizedBox(width: 8),
                Expanded(
                  child: OutlinedButton.icon(
                    onPressed: () => Get.toNamed(AppRoutes.COMPANY_STATS, arguments: {
                      'company_id': company['id'],
                      'company_name': company['name'],
                    }),
                    icon: const Icon(Icons.bar_chart, size: 16),
                    label: const Text('إحصائيات', style: TextStyle(fontSize: 13)),
                    style: OutlinedButton.styleFrom(
                      foregroundColor: const Color(0xFF10B981),
                      side: const BorderSide(color: Color(0xFF10B981)),
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _chip(IconData icon, String text, Color color) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 14, color: color),
          const SizedBox(width: 4),
          Text(text, style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: color)),
        ],
      ),
    );
  }

  void _showEditDialog(BuildContext context, Map<String, dynamic> company, CompaniesManagementController controller) {
    final nameC = TextEditingController(text: company['name'] ?? '');
    final tinC = TextEditingController(text: company['tax_identification_number'] ?? '');
    final addressC = TextEditingController(text: company['address'] ?? '');
    final phoneC = TextEditingController(text: company['contact_phone'] ?? '');
    final emailC = TextEditingController(text: company['contact_email'] ?? '');

    Get.dialog(
      AlertDialog(
        title: const Text('تعديل بيانات الشركة', textAlign: TextAlign.center),
        content: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              _editField('اسم الشركة', nameC, Icons.business),
              _editField('الرقم الضريبي', tinC, Icons.numbers),
              _editField('العنوان', addressC, Icons.location_on),
              _editField('الهاتف', phoneC, Icons.phone),
              _editField('البريد', emailC, Icons.email),
            ],
          ),
        ),
        actions: [
          TextButton(onPressed: () => Get.back(), child: const Text('إلغاء')),
          ElevatedButton(
            onPressed: () {
              Get.back();
              controller.updateCompany(company['id'], {
                'name': nameC.text,
                'tax_identification_number': tinC.text,
                'address': addressC.text,
                'contact_phone': phoneC.text,
                'contact_email': emailC.text,
              });
            },
            style: ElevatedButton.styleFrom(backgroundColor: const Color(0xFF0F4C81)),
            child: const Text('حفظ', style: TextStyle(color: Colors.white)),
          ),
        ],
      ),
    );
  }

  Widget _editField(String label, TextEditingController controller, IconData icon) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: TextField(
        controller: controller,
        textDirection: TextDirection.rtl,
        decoration: InputDecoration(
          labelText: label,
          prefixIcon: Icon(icon, size: 20),
          border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
          contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
        ),
      ),
    );
  }

  void _confirmDelete(BuildContext context, CompaniesManagementController controller, String id, String name) {
    Get.defaultDialog(
      title: 'حذف الشركة',
      middleText: 'هل أنت متأكد من حذف "$name" نهائياً؟\nسيتم حذف جميع الفواتير المرتبطة.',
      textConfirm: 'حذف',
      textCancel: 'إلغاء',
      confirmTextColor: Colors.white,
      buttonColor: Colors.red,
      onConfirm: () {
        Get.back();
        controller.deleteCompany(id);
      },
    );
  }
}
