import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../constant/colors.dart';
import '../../../constant/style.dart';
import '../../../controller/admin/kazan_controller.dart';
import '../../widgets/my_scafold.dart';
import '../../widgets/elevated_btn.dart';

class KazanEditorPage extends StatelessWidget {
  KazanEditorPage({super.key});

  final KazanController controller = Get.put(KazanController());

  @override
  Widget build(BuildContext context) {
    return MyScafolld(
      title: 'تعديل أسعار كازان'.tr,
      isleading: true,
      body: [
        Obx(() => controller.isLoading.value && controller.kazanData.isEmpty
            ? const Center(child: CircularProgressIndicator())
            : SingleChildScrollView(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // ⚙️ الإعدادات العامة
                    _buildSectionHeader('⚙️ الإعدادات العامة'),
                    _buildGeneralSettings(),
                    const SizedBox(height: 24),

                    // 🚗 أسعار الكيلومتر لكل نوع سيارة
                    _buildSectionHeader('🚗 أسعار الكيلومتر لكل نوع سيارة'),
                    _buildKmPricesGrid(),
                    const SizedBox(height: 24),

                    // ⏱️ أسعار الدقيقة
                    _buildSectionHeader('⏱️ أسعار الدقيقة (حسب وقت اليوم)'),
                    _buildMinutePrices(),
                    const SizedBox(height: 32),

                    // 💾 زر الحفظ
                    MyElevatedButton(
                      title: '💾 حفظ جميع التعديلات',
                      icon: Icons.save_rounded,
                      onPressed: () => _handleSave(),
                    ),
                    const SizedBox(height: 100),
                  ],
                ),
              )),
      ],
    );
  }

  // ====================================================================
  // 1. الإعدادات العامة
  // ====================================================================
  Widget _buildGeneralSettings() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: AppStyle.cardDecoration,
      child: Column(
        children: [
          _buildSliderItem(
            'نسبة كازان العامة (عمولة المنصة)',
            'kazanPercent',
            'النسبة المئوية التي تقتطعها المنصة من كل رحلة',
            Icons.percent_rounded,
          ),
          const Divider(height: 32, color: AppColor.divider),
          _buildPriceInputRow(
            'سعر الوقود المرجعي',
            'fuelPrice',
            'السعر المستخدم في حسابات تعويض الوقود',
            Icons.local_gas_station_rounded,
          ),
          const Divider(height: 32, color: AppColor.divider),
          _buildPriceInputRow(
            'رمز العملة',
            'currency',
            'مثال: SYP, EGP, JOD, IQD',
            Icons.currency_exchange_rounded,
          ),
        ],
      ),
    );
  }

  // ====================================================================
  // 2. أسعار الكيلومتر - كل نوع سيارة له حقل خاص به
  // ====================================================================
  Widget _buildKmPricesGrid() {
    // 🆕 9 أنواع سيارات - كل واحد له عمود سعر مستقل
    final Map<String, Map<String, dynamic>> priceFields = {
      'speedPrice': {
        'label': 'Speed ⚡',
        'icon': Icons.flash_on_rounded,
        'color': Colors.amber.shade700
      },
      'comfortPrice': {
        'label': 'Comfort ❄️',
        'icon': Icons.chair_rounded,
        'color': Colors.blue.shade700
      },
      'ladyPrice': {
        'label': 'Lady 👩',
        'icon': Icons.female_rounded,
        'color': Colors.pink.shade400
      },
      'electricPrice': {
        'label': 'Electric 🔋',
        'icon': Icons.electric_car_rounded,
        'color': Colors.green.shade700
      },
      'vanPrice': {
        'label': 'Van 🚐',
        'icon': Icons.airport_shuttle_rounded,
        'color': Colors.deepPurple.shade700
      },
      'deliveryPrice': {
        'label': 'Delivery 📦',
        'icon': Icons.delivery_dining_rounded,
        'color': Colors.orange.shade700
      },
      'mishwarVipPrice': {
        'label': 'Mishwar Vip ⭐',
        'icon': Icons.star_rounded,
        'color': Colors.amber.shade900
      },
      'fixedPrice': {
        'label': 'Fixed Price 💰',
        'icon': Icons.money_rounded,
        'color': Colors.teal.shade700
      },
      'awfarPrice': {
        'label': 'Awfar Car 🚗',
        'icon': Icons.directions_car_rounded,
        'color': Colors.brown.shade600
      },
    };

    return Container(
      decoration: AppStyle.cardDecoration,
      padding: const EdgeInsets.all(12),
      child: GridView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3, // 3 أعمدة بدلاً من 2
          childAspectRatio: 1.8,
          crossAxisSpacing: 8,
          mainAxisSpacing: 8,
        ),
        itemCount: priceFields.length,
        itemBuilder: (context, index) {
          String key = priceFields.keys.elementAt(index);
          var field = priceFields[key]!;
          return _buildKmPriceCard(
              key, field['label'], field['icon'], field['color']);
        },
      ),
    );
  }

  Widget _buildKmPriceCard(
      String key, String label, IconData icon, Color color) {
    final TextEditingController textController =
        TextEditingController(text: _getValue(key));

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
      decoration: BoxDecoration(
        color: color.withAlpha(25),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: color.withAlpha(80)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Row(
            children: [
              Icon(icon, size: 14, color: color),
              const SizedBox(width: 4),
              Expanded(
                child: Text(
                  label,
                  style: AppStyle.caption
                      .copyWith(fontSize: 10, fontWeight: FontWeight.bold),
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ],
          ),
          const SizedBox(height: 4),
          Row(
            children: [
              Expanded(
                child: TextField(
                  controller: textController,
                  keyboardType: TextInputType.number,
                  textAlign: TextAlign.center,
                  style: AppStyle.number.copyWith(fontSize: 13, color: color),
                  decoration: const InputDecoration(
                    border: InputBorder.none,
                    isDense: true,
                    contentPadding: EdgeInsets.symmetric(vertical: 2),
                  ),
                  onChanged: (val) => _setValue(key, val),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  // ====================================================================
  // 3. أسعار الدقيقة (حسب وقت اليوم)
  // ====================================================================
  Widget _buildMinutePrices() {
    final Map<String, Map<String, dynamic>> minuteFields = {
      'normalMinPrice': {
        'label': 'Normal (سعر الدقيقة العادي)',
        'desc': '9 ص - 2 م / 6 م - 9 م',
        'icon': Icons.wb_sunny_rounded,
        'color': Colors.orange
      },
      'peakMinPrice': {
        'label': 'Peak (سعر الدقيقة ذروة)',
        'desc': '2 م - 5 م',
        'icon': Icons.whatshot_rounded,
        'color': Colors.red
      },
      'lateMinPrice': {
        'label': 'Late (سعر الدقيقة ليلي)',
        'desc': '9 م - 1 ص',
        'icon': Icons.nightlight_round,
        'color': Colors.indigo
      },
    };

    return Container(
      decoration: AppStyle.cardDecoration,
      padding: const EdgeInsets.all(16),
      child: Column(
        children: minuteFields.entries.map((entry) {
          return Padding(
            padding: const EdgeInsets.symmetric(vertical: 6),
            child: _buildPriceInputRow(
              entry.value['label'],
              entry.key,
              entry.value['desc'],
              entry.value['icon'],
            ),
          );
        }).toList(),
      ),
    );
  }

  // ====================================================================
  // دوال مساعدة للـ UI
  // ====================================================================
  Widget _buildSectionHeader(String title) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 12, left: 4),
      child: Text(
        title,
        style: AppStyle.title.copyWith(color: AppColor.accent),
      ),
    );
  }

  String _getValue(String key) {
    return controller.kazanData[key]?.toString() ?? '0';
  }

  void _setValue(String key, String val) {
    controller.kazanData[key] = val;
  }

  Widget _buildPriceInputRow(
      String title, String key, String desc, IconData icon) {
    final TextEditingController textController =
        TextEditingController(text: _getValue(key));

    return Row(
      children: [
        Icon(icon, size: 20, color: AppColor.accent),
        const SizedBox(width: 8),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(title,
                  style: AppStyle.body.copyWith(fontWeight: FontWeight.bold)),
              Text(desc, style: AppStyle.caption.copyWith(fontSize: 10)),
            ],
          ),
        ),
        Container(
          width: 100,
          height: 40,
          decoration: BoxDecoration(
            color: AppColor.surfaceElevated,
            borderRadius: BorderRadius.circular(8),
            border: Border.all(color: AppColor.divider),
          ),
          child: TextField(
            controller: textController,
            keyboardType: TextInputType.number,
            textAlign: TextAlign.center,
            style:
                AppStyle.number.copyWith(fontSize: 16, color: AppColor.accent),
            decoration: const InputDecoration(
              border: InputBorder.none,
              isDense: true,
              contentPadding: EdgeInsets.symmetric(vertical: 10),
            ),
            onChanged: (val) => _setValue(key, val),
          ),
        ),
      ],
    );
  }

  Widget _buildSliderItem(
      String title, String key, String desc, IconData icon) {
    double value = double.tryParse(_getValue(key)) ?? 0;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                Icon(icon, size: 18, color: AppColor.accent),
                const SizedBox(width: 8),
                Text(title, style: AppStyle.title),
              ],
            ),
            Text(
              '${value.toInt()}%',
              style: AppStyle.number.copyWith(fontSize: 18),
            ),
          ],
        ),
        const SizedBox(height: 4),
        Text(desc, style: AppStyle.caption),
        Slider(
          value: value.clamp(0, 100),
          min: 0,
          max: 100,
          activeColor: AppColor.accent,
          inactiveColor: AppColor.divider,
          onChanged: (val) {
            _setValue(key, val.toInt().toString());
          },
        ),
      ],
    );
  }

  // ====================================================================
  // حفظ البيانات
  // ====================================================================
  void _handleSave() async {
    final data = Map<String, dynamic>.from(controller.kazanData);
    data['adminId'] = 'admin1';

    // التأكد من وجود country (إذا لم يكن موجوداً، استخدم 'syria')
    if (!data.containsKey('country') ||
        data['country'] == null ||
        data['country'].toString().isEmpty) {
      data['country'] = 'Syria';
    }

    bool success = await controller.updateKazan(data);
    if (success) {
      Get.snackbar("نجاح", "تم تحديث الأسعار بنجاح",
          backgroundColor: AppColor.successSoft,
          colorText: AppColor.textPrimary,
          snackPosition: SnackPosition.BOTTOM,
          margin: const EdgeInsets.all(16));
    } else {
      Get.snackbar("خطأ", "فشل تحديث الأسعار",
          backgroundColor: Colors.red.shade100,
          colorText: AppColor.textPrimary,
          snackPosition: SnackPosition.BOTTOM,
          margin: const EdgeInsets.all(16));
    }
  }
}
