package org.example.petshopdesktop.controllers.dialogcontrollers;

import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import org.example.petshopdesktop.DTOs.ServiceDTO;
import org.example.petshopdesktop.api.dto.service.ServiceRequest;
import org.example.petshopdesktop.api.endpoints.ServiceApi;
import org.example.petshopdesktop.util.ActivityLogger;

import java.math.BigDecimal;


public class ServiceDialogController {

    @FXML
    private Button btnCancel;

    @FXML
    private Button btnSave;

    @FXML
    private Label lblMode;

    @FXML
    private Label lblServiceId;

    @FXML
    private TextField txtServiceDesc;

    @FXML
    private TextField txtServiceName;

    @FXML
    private TextField txtServicePrice;

    @FXML
    private ComboBox<Integer> cbHours;

    @FXML
    private ComboBox<Integer> cbMinutes;

    private String mode;
    private ServiceDTO selectedService;



    @FXML
    public void initialize() {
        cbHours.getItems().addAll(0, 1, 2, 3, 4);
        cbMinutes.getItems().addAll(0, 15, 30, 45);
        btnSave.setOnAction(e -> saveService());
        btnCancel.setOnAction(e -> close());
    }

    public void setMode(String mode) {
        this.mode = mode;
        lblMode.setText(mode + " Service");

        if (mode.equals("Add")) {
            lblServiceId.setVisible(false);
        } else {
            lblServiceId.setVisible(true);
        }
    }

    public void setService(ServiceDTO service) {
        this.selectedService = service;

        lblServiceId.setText("ID: " + service.getServiceId());
        txtServiceName.setText(service.getServiceName());
        txtServiceDesc.setText(service.getServiceDesc());
        int totalMinutes = service.getServiceDuration();
        cbHours.setValue(totalMinutes / 60);
        cbMinutes.setValue(totalMinutes % 60);
        txtServicePrice.setText(String.valueOf(service.getServicePrice()));
    }

    private void saveService() {

        String name = txtServiceName.getText();
        String desc = txtServiceDesc.getText();
        String priceText = txtServicePrice.getText();

        Integer hours = cbHours.getValue();
        Integer minutes = cbMinutes.getValue();

        // -------- VALIDATION --------
        if (name == null || name.isBlank()) {
            showError("Service name is required.");
            return;
        }

        if (priceText == null || priceText.isBlank()) {
            showError("Price is required.");
            return;
        }

        if (hours == null || minutes == null) {
            showError("Please select duration.");
            return;
        }

        double price;

        try {
            price = Double.parseDouble(priceText);
        } catch (NumberFormatException e) {
            showError("Price must be numeric.");
            return;
        }

        try {
            int durationMinutes = (hours * 60) + minutes;

            ServiceRequest request = new ServiceRequest();
            request.setServiceName(name);
            request.setServiceDesc(desc);
            request.setServicePrice(BigDecimal.valueOf(price));
            request.setServiceDuration(durationMinutes);

            if (mode.equals("Add")) {
                ServiceApi.getInstance().createService(request);
            } else {
                Long serviceId = (long) selectedService.getServiceId();
                ServiceApi.getInstance().updateService(serviceId, request);
            }

            close();

        } catch (Exception e) {
            ActivityLogger.getInstance().logException(
                "ServiceDialogController.saveService",
                e,
                "Saving service in " + mode + " mode");
            e.printStackTrace();
            showError("Database error while saving service.");
        }
    }

    private void showError(String msg) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setHeaderText("Invalid Input");
        alert.setContentText(msg);
        alert.showAndWait();
    }

    private void close() {
        Stage stage = (Stage) btnSave.getScene().getWindow();
        stage.close();
    }
}