import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../model/filament_model.dart';
import '../helpers/filament_repository.dart';

class EditController extends GetxController {
  Rx<FilamentModel?> originalFilament = Rx<FilamentModel?>(null);

  // Form Controllers
  final nameController = TextEditingController();
  final typeController = TextEditingController();
  final weightController = TextEditingController();
  final weightUsedController = TextEditingController();
  final currentUsageController = TextEditingController();
  final priceController = TextEditingController();
  final manufacturerController = TextEditingController();
  final purchaseDateController = TextEditingController();
  final notesController = TextEditingController();
  final piecesController = TextEditingController();
  final printingTempController = TextEditingController();
  final bedTempController = TextEditingController();

  // Reactive color for UI updates
  final selectedColor = 'White'.obs;

  // Validation
  final formKey = GlobalKey<FormState>();
  final isSaving = false.obs;

  // Available options
  final List<String> filamentTypes = [
    'PLA',
    'PLA+',
    'ABS',
    'PETG',
    'TPU',
    'ASA',
    'Nylon',
    'PC',
    'PVA',
  ];

  final List<String> availableColors = [
    'White',
    'Black',
    'Red',
    'Blue',
    'Green',
    'Yellow',
    'Orange',
    'Purple',
    'Pink',
    'Grey',
    'Brown',
  ];

  @override
  void onInit() {
    if (Get.arguments != null && Get.arguments['filament'] != null) {
      originalFilament.value = Get.arguments['filament'];
      _populateForm();
    }
    super.onInit();
  }

  void _populateForm() {
    final filament = originalFilament.value;
    if (filament != null) {
      nameController.text = filament.name;
      typeController.text = filament.type;
      selectedColor.value = filament.color;
      selectedColor.value = filament.color;
      weightController.text = filament.weight.toString();
      weightUsedController.text = filament.weightUsed.toString();
      priceController.text = filament.price.toString();
      manufacturerController.text = filament.manufacturer ?? '';
      purchaseDateController.text = filament.purchaseDate ?? '';
      notesController.text = filament.notes ?? '';
      piecesController.text = filament.pices.toString();
      printingTempController.text = filament.printingTemp?.toString() ?? '';
      bedTempController.text = filament.bedTemp?.toString() ?? '';
    }
  }

  Future<void> saveFilament() async {
    if (!formKey.currentState!.validate()) return;

    isSaving.value = true;

    try {
      // Berechne den neuen Gesamtverbrauch
      final currentWeightUsed = double.tryParse(weightUsedController.text) ?? 0;
      final additionalUsage = double.tryParse(currentUsageController.text) ?? 0;
      final totalWeightUsed = currentWeightUsed + additionalUsage;

      final updatedFilament = FilamentModel(
        id:
            originalFilament.value?.id ??
            DateTime.now().millisecondsSinceEpoch.toString(),
        name: nameController.text.trim(),
        type: typeController.text.trim(),
        color: selectedColor.value.trim(),
        weight: double.tryParse(weightController.text) ?? 0,
        weightUsed: totalWeightUsed,
        price: double.tryParse(priceController.text) ?? 0,
        manufacturer: manufacturerController.text.trim().isEmpty
            ? null
            : manufacturerController.text.trim(),
        purchaseDate: purchaseDateController.text.trim().isEmpty
            ? null
            : purchaseDateController.text.trim(),
        notes: notesController.text.trim().isEmpty
            ? null
            : notesController.text.trim(),
        pices: int.tryParse(piecesController.text) ?? 0,
        printingTemp: int.tryParse(printingTempController.text) ?? 0,
        bedTemp: int.tryParse(bedTempController.text) ?? 0,
      );

      bool success;
      if (originalFilament.value != null) {
        success = await FilamentRepository.to.updateFilament(updatedFilament);
      } else {
        success = await FilamentRepository.to.createFilament(updatedFilament);
      }

      if (success) {
        Get.back(result: updatedFilament);
        Get.snackbar(
          'Erfolg',
          originalFilament.value != null
              ? 'Filament wurde aktualisiert'
              : 'Filament wurde erstellt',
          snackPosition: SnackPosition.BOTTOM,
          backgroundColor: Get.theme.colorScheme.primary.withAlpha(26),
          colorText: Get.theme.colorScheme.primary,
        );
      } else {
        Get.snackbar(
          'Fehler',
          'Filament konnte nicht gespeichert werden',
          snackPosition: SnackPosition.BOTTOM,
          backgroundColor: Colors.red.withAlpha(26),
          colorText: Colors.red,
        );
      }
    } catch (e) {
      Get.snackbar(
        'Fehler',
        'Ein Fehler ist aufgetreten: $e',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red.withAlpha(26),
        colorText: Colors.red,
      );
    } finally {
      isSaving.value = false;
    }
  }

  @override
  void onClose() {
    nameController.dispose();
    typeController.dispose();
    weightController.dispose();
    weightUsedController.dispose();
    currentUsageController.dispose();
    priceController.dispose();
    manufacturerController.dispose();
    purchaseDateController.dispose();
    notesController.dispose();
    piecesController.dispose();
    printingTempController.dispose();
    bedTempController.dispose();
    super.onClose();
  }
}
