import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:siro_admin/constant/colors.dart';
import 'package:siro_admin/controller/admin/financial_v2_controller.dart';

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

  @override
  Widget build(BuildContext context) {
    final controller = Get.put(FinancialV2Controller());

    return Scaffold(
      backgroundColor: AppColor.bg,
      appBar: AppBar(
        title: const Text('الإدارة المالية المتقدمة',
            style: TextStyle(fontWeight: FontWeight.bold)),
        backgroundColor: AppColor.surface,
        elevation: 0,
        centerTitle: true,
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh_rounded),
            onPressed: () => controller.fetchAllFinancials(),
          )
        ],
      ),
      body: GetBuilder<FinancialV2Controller>(
        builder: (ctrl) {
          if (ctrl.isLoading) {
            return const Center(
                child: CircularProgressIndicator(color: AppColor.accent));
          }

          return SingleChildScrollView(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _buildMainFinancialStats(ctrl.stats),
                const SizedBox(height: 24),
                _buildSectionTitle('طرق الدفع'),
                _buildPaymentMethodBreakdown(ctrl.stats),
                const SizedBox(height: 32),
                _buildSectionTitle('تسويات الكباتن (مستحقات معلقة)'),
                _buildSettlementsList(ctrl.settlements),
                const SizedBox(height: 40),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _buildSectionTitle(String title) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 16),
      child: Text(
        title,
        style: const TextStyle(
          color: AppColor.textPrimary,
          fontSize: 16,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }

  Widget _buildMainFinancialStats(Map<String, dynamic> stats) {
    return Column(
      children: [
        _buildFinancialCard(
          'إجمالي عمولة المنصة',
          '${stats['total_platform_commission'] ?? 0} ج.م',
          Icons.account_balance_rounded,
          AppColor.accent,
        ),
        const SizedBox(height: 12),
        Row(
          children: [
            Expanded(
              child: _buildFinancialCard(
                'إجمالي دخل الكباتن',
                '${stats['total_driver_pay'] ?? 0}',
                Icons.person_pin_rounded,
                AppColor.info,
                isSmall: true,
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: _buildFinancialCard(
                'إجمالي الإيرادات',
                '${stats['total_revenue'] ?? 0}',
                Icons.payments_rounded,
                AppColor.success,
                isSmall: true,
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildFinancialCard(
      String title, String value, IconData icon, Color color,
      {bool isSmall = false}) {
    return Container(
      padding: EdgeInsets.all(isSmall ? 16 : 24),
      decoration: BoxDecoration(
        color: AppColor.surface,
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: color.withOpacity(0.2)),
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [AppColor.surface, color.withOpacity(0.05)],
        ),
      ),
      child: Row(
        children: [
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: color.withOpacity(0.1),
              borderRadius: BorderRadius.circular(14),
            ),
            child: Icon(icon, color: color, size: isSmall ? 20 : 28),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(title,
                    style: const TextStyle(
                        color: AppColor.textSecondary, fontSize: 12)),
                const SizedBox(height: 4),
                Text(value,
                    style: TextStyle(
                        color: AppColor.textPrimary,
                        fontSize: isSmall ? 18 : 24,
                        fontWeight: FontWeight.bold)),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPaymentMethodBreakdown(Map<String, dynamic> stats) {
    double cash = double.tryParse(stats['cash_payments'].toString()) ?? 0;
    double digital = double.tryParse(stats['digital_payments'].toString()) ?? 0;
    double total = cash + digital;
    if (total == 0) total = 1;

    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: AppColor.surface,
        borderRadius: BorderRadius.circular(20),
      ),
      child: Column(
        children: [
          _buildPaymentBar('نقدي (Cash)', cash, total, AppColor.warning),
          const SizedBox(height: 16),
          _buildPaymentBar('إلكتروني / محفظة', digital, total, AppColor.info),
        ],
      ),
    );
  }

  Widget _buildPaymentBar(
      String label, double value, double total, Color color) {
    double percent = value / total;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(label,
                style:
                    const TextStyle(color: AppColor.textPrimary, fontSize: 13)),
            Text('${value.toStringAsFixed(0)} ج.م',
                style: TextStyle(color: color, fontWeight: FontWeight.bold)),
          ],
        ),
        const SizedBox(height: 8),
        ClipRRect(
          borderRadius: BorderRadius.circular(4),
          child: LinearProgressIndicator(
            value: percent,
            backgroundColor: AppColor.divider,
            color: color,
            minHeight: 8,
          ),
        ),
      ],
    );
  }

  Widget _buildSettlementsList(List<dynamic> settlements) {
    if (settlements.isEmpty)
      return const Center(child: Text('لا توجد تسويات معلقة'));

    return ListView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: settlements.length,
      itemBuilder: (ctx, i) {
        final s = settlements[i];
        return Container(
          margin: const EdgeInsets.only(bottom: 12),
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: AppColor.surface,
            borderRadius: BorderRadius.circular(16),
            border: Border.all(color: AppColor.divider),
          ),
          child: Row(
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('${s['first_name']} ${s['last_name']}',
                        style: const TextStyle(
                            color: AppColor.textPrimary,
                            fontWeight: FontWeight.bold)),
                    Text(s['phone'] ?? '',
                        style: const TextStyle(
                            color: AppColor.textSecondary, fontSize: 12)),
                    const SizedBox(height: 4),
                    Text('${s['total_rides']} رحلة مكتملة',
                        style: const TextStyle(
                            color: AppColor.info, fontSize: 11)),
                  ],
                ),
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  const Text('المستحقات',
                      style: TextStyle(
                          color: AppColor.textSecondary, fontSize: 10)),
                  Text('${s['total_earned']} ج.م',
                      style: const TextStyle(
                          color: AppColor.accent,
                          fontSize: 18,
                          fontWeight: FontWeight.bold)),
                  const SizedBox(height: 4),
                  ElevatedButton(
                    onPressed: () {},
                    style: ElevatedButton.styleFrom(
                      backgroundColor: AppColor.accent.withOpacity(0.1),
                      foregroundColor: AppColor.accent,
                      elevation: 0,
                      minimumSize: const Size(80, 32),
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8)),
                    ),
                    child: const Text('تسوية',
                        style: TextStyle(
                            fontSize: 11, fontWeight: FontWeight.bold)),
                  ),
                ],
              ),
            ],
          ),
        );
      },
    );
  }
}
