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('النسب العامة'),
                    _buildKazanCard(),
                    const SizedBox(height: 24),
                    _buildSectionHeader('أسعار الفئات الإضافية'),
                    _buildPricesGrid(),
                    const SizedBox(height: 32),
                    MyElevatedButton(
                      title: 'حفظ جميع التعديلات',
                      icon: Icons.save_rounded,
                      onPressed: () => _handleSave(),
                    ),
                    const SizedBox(height: 100),
                  ],
                ),
              )),
      ],
    );
  }

  Widget _buildSectionHeader(String title) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 12, left: 4),
      child: Text(
        title,
        style: AppStyle.title.copyWith(color: AppColor.accent),
      ),
    );
  }

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

  Widget _buildPriceInputRow(String title, String key, String desc, IconData icon) {
    final TextEditingController textController = TextEditingController(
      text: controller.kazanData[key]?.toString() ?? '0'
    );

    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: 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) => controller.kazanData[key] = val,
            ),
          ),
          const SizedBox(width: 8),
          Text('ل.س', style: AppStyle.caption),
        ],
      ),
    );
  }

  Widget _buildPricesGrid() {
    final Map<String, dynamic> priceFields = {
      'comfortPrice': {'label': 'Comfort', 'icon': Icons.chair_rounded},
      'speedPrice': {'label': 'Speed', 'icon': Icons.flash_on_rounded},
      'familyPrice': {'label': 'Family', 'icon': Icons.groups_rounded},
      'deliveryPrice': {'label': 'Delivery', 'icon': Icons.delivery_dining_rounded},
      'freePrice': {'label': 'Free', 'icon': Icons.money_off_rounded},
      'latePrice': {'label': 'Late Night', 'icon': Icons.nightlight_round},
      'heavyPrice': {'label': 'Heavy Load', 'icon': Icons.inventory_2_rounded},
      'naturePrice': {'label': 'Nature', 'icon': Icons.forest_rounded},
    };

    return Container(
      decoration: AppStyle.cardDecoration,
      padding: const EdgeInsets.all(12),
      child: GridView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          childAspectRatio: 2.5,
          crossAxisSpacing: 8,
          mainAxisSpacing: 8,
        ),
        itemCount: priceFields.length,
        itemBuilder: (context, index) {
          String key = priceFields.keys.elementAt(index);
          var field = priceFields[key];
          return _buildCompactPriceInputCard(key, field['label'], field['icon']);
        },
      ),
    );
  }

  Widget _buildCompactPriceInputCard(String key, String label, IconData icon) {
    final TextEditingController textController = TextEditingController(
      text: controller.kazanData[key]?.toString() ?? '0'
    );

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: AppColor.surfaceElevated,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: AppColor.divider.withAlpha(100)),
      ),
      child: Row(
        children: [
          Icon(icon, size: 16, color: AppColor.textSecondary),
          const SizedBox(width: 6),
          Expanded(
            child: Text(label, style: AppStyle.caption.copyWith(fontSize: 11), overflow: TextOverflow.ellipsis),
          ),
          SizedBox(
            width: 50,
            child: TextField(
              controller: textController,
              keyboardType: TextInputType.number,
              textAlign: TextAlign.center,
              style: AppStyle.number.copyWith(fontSize: 14),
              decoration: const InputDecoration(
                border: InputBorder.none,
                isDense: true,
                contentPadding: EdgeInsets.zero,
              ),
              onChanged: (val) => controller.kazanData[key] = val,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSliderItem(String title, String key, String desc, IconData icon) {
    double value = double.tryParse(controller.kazanData[key]?.toString() ?? '0') ?? 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) {
            controller.kazanData[key] = val.toInt().toString();
          },
        ),
      ],
    );
  }

  void _handleSave() async {
    final data = Map<String, dynamic>.from(controller.kazanData);
    data['adminId'] = 'admin'; // Should be dynamic from auth service
    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)
      );
    }
  }
}
