package org.example.petshopdesktop.controllers;

import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Modality;
import javafx.stage.Stage;

import org.example.petshopdesktop.DTOs.AppointmentDTO;
import org.example.petshopdesktop.api.dto.appointment.AppointmentResponse;
import org.example.petshopdesktop.api.endpoints.AppointmentApi;
import org.example.petshopdesktop.controllers.dialogcontrollers.AppointmentDialogController;
import org.example.petshopdesktop.util.ActivityLogger;
import org.example.petshopdesktop.util.TableViewSupport;

import java.util.List;
import java.util.Comparator;
import java.util.stream.Collectors;

public class AppointmentController {

    @FXML private TableView<AppointmentDTO> tvAppointments;

    @FXML private TableColumn<AppointmentDTO,Integer> colAppointmentId;
    @FXML private TableColumn<AppointmentDTO,String> colPetName;
    @FXML private TableColumn<AppointmentDTO,String> colServiceName;
    @FXML private TableColumn<AppointmentDTO,String> colAppointmentDate;
    @FXML private TableColumn<AppointmentDTO,String> colAppointmentTime;
    @FXML private TableColumn<AppointmentDTO,String> colCustomerName;
    @FXML private TableColumn<AppointmentDTO,String> colEmployeeName;
    @FXML private TableColumn<AppointmentDTO,String> colAppointmentStatus;

    @FXML private Button btnAdd;
    @FXML private Button btnEdit;
    @FXML private Button btnDelete;
    @FXML private Button btnRefresh;

    @FXML private Label lblStatus;

    @FXML private TextField txtSearch;

    private final ObservableList<AppointmentDTO> appointments = FXCollections.observableArrayList();
    private FilteredList<AppointmentDTO> filtered;

    @FXML
    public void initialize(){
        btnEdit.setDisable(true);
        btnDelete.setDisable(true);
        tvAppointments.getSelectionModel().setSelectionMode(javafx.scene.control.SelectionMode.MULTIPLE);

        colAppointmentId.setCellValueFactory(new PropertyValueFactory<>("appointmentId"));
        colPetName.setCellValueFactory(new PropertyValueFactory<>("petName"));
        colServiceName.setCellValueFactory(new PropertyValueFactory<>("serviceName"));
        colAppointmentDate.setCellValueFactory(new PropertyValueFactory<>("appointmentDate"));
        colAppointmentTime.setCellValueFactory(new PropertyValueFactory<>("appointmentTime"));
        colCustomerName.setCellValueFactory(new PropertyValueFactory<>("customerName"));
        colEmployeeName.setCellValueFactory(new PropertyValueFactory<>("employeeName"));
        colAppointmentStatus.setCellValueFactory(new PropertyValueFactory<>("appointmentStatus"));

        filtered = new FilteredList<>(appointments, a -> true);
        TableViewSupport.bindSortedItems(tvAppointments, filtered);
        TableViewSupport.installDoubleClickAction(tvAppointments, selected -> openDialog(selected, "Edit"));

        if (txtSearch != null) {
            txtSearch.textProperty().addListener((obs, o, n) -> applyFilter(n));
        }

        tvAppointments.getSelectionModel().selectedItemProperty().addListener((obs, oldValue, newValue) -> {
            boolean hasSelection = newValue != null;
            btnEdit.setDisable(!hasSelection);
            btnDelete.setDisable(!hasSelection);
        });

        tvAppointments.setOnKeyPressed(event -> {
            if (event.getCode() == javafx.scene.input.KeyCode.DELETE) {
                if (tvAppointments.getSelectionModel().getSelectedItem() != null) {
                    btnDeleteClicked(null);
                }
            }
        });

        loadAppointments();
    }

    private void loadAppointments(){
        new Thread(() -> {
            try{
                List<AppointmentResponse> responses = AppointmentApi.getInstance().listAppointments(null);
                List<AppointmentDTO> appointmentDTOs = responses.stream()
                    .map(this::mapToAppointmentDTO)
                    .sorted(Comparator.comparing((AppointmentDTO a) -> a.getAppointmentDate() + "T" + a.getAppointmentTime()).reversed())
                    .collect(Collectors.toList());

                Platform.runLater(() -> {
                    appointments.setAll(appointmentDTOs);
                });
            }catch(Exception e){
                Platform.runLater(() -> {
                    ActivityLogger.getInstance().logException(
                        "AppointmentController.loadAppointments",
                        e,
                        "Loading appointments for table display");
                    e.printStackTrace();
                });
            }
        }).start();
    }

    private void applyFilter(String text) {
        String query = text == null || text.trim().isEmpty() ? null : text.trim();
        new Thread(() -> {
            try {
                List<AppointmentResponse> responses = AppointmentApi.getInstance().listAppointments(query);
                List<AppointmentDTO> appointmentDTOs = responses.stream()
                    .map(this::mapToAppointmentDTO)
                    .sorted(Comparator.comparing((AppointmentDTO a) -> a.getAppointmentDate() + "T" + a.getAppointmentTime()).reversed())
                    .collect(Collectors.toList());

                Platform.runLater(() -> {
                    appointments.setAll(appointmentDTOs);
                });
            } catch (Exception e) {
                Platform.runLater(() -> {
                    ActivityLogger.getInstance().logException(
                        "AppointmentController.applyFilter",
                        e,
                        String.format("Filtering appointments with query: %s", query));
                    e.printStackTrace();
                });
            }
        }).start();
    }

    @FXML
    void btnRefresh(ActionEvent event) {
        txtSearch.clear();
        tvAppointments.getSortOrder().clear();
        loadAppointments();
        TableViewSupport.flashStatus(lblStatus, "Refreshed");
    }

    @FXML
    void btnAddClicked(ActionEvent event){
        openDialog(null, "Add");
    }

    @FXML
    void btnEditClicked(ActionEvent event){

        AppointmentDTO selected =
                tvAppointments.getSelectionModel().getSelectedItem();

        if(selected == null){
            showAlert("Select Appointment", "Please select appointment to edit.");
            return;
        }

        openDialog(selected, "Edit");
    }

    @FXML
    void btnDeleteClicked(ActionEvent event){
        
        var selectedAppointments = tvAppointments.getSelectionModel().getSelectedItems();
        if (selectedAppointments.isEmpty()) return;

        Alert question = new Alert(Alert.AlertType.CONFIRMATION);
        question.setHeaderText("Please confirm delete");
        String message = selectedAppointments.size() == 1
            ? "Are you sure you want to delete this appointment?"
            : "Are you sure you want to delete " + selectedAppointments.size() + " appointments?";
        question.setContentText(message);
        question.getDialogPane().lookupButton(ButtonType.OK).requestFocus();
        java.util.Optional<ButtonType> result = question.showAndWait();

        if (result.isPresent() && result.get() == ButtonType.OK) {
            List<Long> ids = selectedAppointments.stream()
                .map(a -> (long) a.getAppointmentId())
                .collect(Collectors.toList());

            try {
                AppointmentApi.getInstance().deleteAppointments(ids);
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setHeaderText("Database Operation Confirmed");
                alert.setContentText("Successfully deleted " + ids.size() + " appointment(s)");
                alert.showAndWait();
            } catch (Exception e) {
                ActivityLogger.getInstance().logException(
                    "AppointmentController.btnDeleteClicked",
                    e,
                    "Deleting appointments");
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setHeaderText("Delete Operation Failed");
                alert.setContentText(e.getMessage());
                alert.showAndWait();
            }

            loadAppointments();
        }
    }

    private void openDialog(AppointmentDTO appt, String mode){

        try{
            FXMLLoader loader = new FXMLLoader(
                    getClass().getResource(
                            "/org/example/petshopdesktop/dialogviews/appointment-dialog-view.fxml"
                    )
            );

            Scene scene = new Scene(loader.load());

            AppointmentDialogController controller =
                    loader.getController();

            controller.setMode(mode);

            if(mode.equals("Edit")){
                controller.displayAppointmentDetails(appt);
            }

            Stage stage = new Stage();
            stage.initModality(Modality.APPLICATION_MODAL);
            stage.setScene(scene);
            stage.showAndWait();

            loadAppointments();

        }catch(Exception e){
            ActivityLogger.getInstance().logException(
                "AppointmentController.openDialog",
                e,
                "Opening appointment dialog in " + mode + " mode");
            e.printStackTrace();
        }
    }

    private void showAlert(String title, String msg){
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(msg);
        alert.showAndWait();
    }

    private AppointmentDTO mapToAppointmentDTO(AppointmentResponse response) {
        return new AppointmentDTO(
            response.getAppointmentId().intValue(),
            response.getCustomerId() != null ? response.getCustomerId().intValue() : 0,
            response.getCustomerName() != null ? response.getCustomerName() : "",
            response.getPetId() != null ? response.getPetId().intValue() : 0,
            response.getPetName() != null ? response.getPetName() : "",
            response.getServiceId() != null ? response.getServiceId().intValue() : 0,
            response.getServiceName() != null ? response.getServiceName() : "",
            response.getEmployeeId() != null ? response.getEmployeeId().intValue() : 0,
            response.getEmployeeName() != null ? response.getEmployeeName() : "",
            response.getAppointmentDate() != null ? response.getAppointmentDate().toString() : "",
            response.getAppointmentTime() != null ? response.getAppointmentTime().toString() : "",
            normalizeAppointmentStatus(response.getAppointmentStatus())
        );
    }

    private String normalizeAppointmentStatus(String status) {
        if (status == null) {
            return "Booked";
        }
        return switch (status.trim().toLowerCase()) {
            case "booked" -> "Booked";
            case "completed" -> "Completed";
            case "missed" -> "Missed";
            case "cancelled", "canceled" -> "Cancelled";
            default -> "Booked";
        };
    }
}
