package com.avaya.ccs.javafxrefclient;

import com.avaya.ccs.api.DestinationI;
import com.avaya.ccs.api.DestinationListI;
import com.avaya.ccs.api.enums.DestinationType;
import com.avaya.ccs.api.enums.InteractionType;
import com.avaya.ccs.core.Media;
import com.avaya.ccs.core.User;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.web.HTMLEditor;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class EmailForwardForm {
    private static final Logger LOG = Logger.getLogger(EmailForwardForm.class);
    private final Stage form = new Stage();
    ComboBox<String> skillsetListBox;
    HTMLEditor htmlEditor;
    FileChooser fileChooser;
    private Media media;
    private boolean mediaSet;
    private String agentSignature;
    private MediaFormI mediaForm;
    private RelocationType relocationType;

    enum RelocationType {
        Consult, Transfer
    }

    private final InteractionExecutor interactionExe;

    private final ObservableList<DestinationI> destinationsOL = FXCollections.observableArrayList();
    private String currentInteractionID;
    private ListView<DestinationI> destinationsLV = new ListView<>();
    private InteractionType interactionType;

    public EmailForwardForm(InteractionExecutor interactionExe, String css, InteractionType interactionType) {
        this.interactionExe = interactionExe;
        BorderPane consultBorder = new BorderPane();
        Scene forwardScene = new Scene(consultBorder, 300, 400);
        forwardScene.getStylesheets().add(css);
        form.setScene(forwardScene);
        this.interactionType = interactionType;
    }

    public void buildForwardUI(InteractionData interactionData) {
        Insets insets = new Insets(20); // 20 pixels padding on all sides

        //-------------------------------- Build transfer tabs--------------------------------


        Tab transferToUserTab = new Tab("User");
        Tab transferToSkillsetTab = new Tab("Skillset");
        Tab transferToExternalTab = new Tab("External");

        StackPane transferPane = new StackPane();
        transferToSkillsetTab.setContent(transferPane);

        TabPane tabPane = new TabPane();
        tabPane.getTabs().addAll(transferToUserTab, transferToSkillsetTab, transferToExternalTab);
        //bp.setCenter(tabPane);
        //List<String> skillsetList keep Skillsets to populate skillsetListBox;should be obtained from AACC interaction

        List<String> skillsetList = new ArrayList<>();
        destinationsOL.forEach(dest->{

            if(dest.getDestinationType()==DestinationType.Skillset){
                skillsetList.add(dest.getName());
            }

        });
        skillsetListBox = new ComboBox<>();
        skillsetListBox.setPrefWidth(200);
        skillsetListBox.getItems().addAll(skillsetList);
        skillsetListBox.setValue("EM_Default_Skillset_1");

        //List<String> selectedSkillsetList keep track of selected items

        List<String> selectedSkillsetList = new ArrayList<>();






        //-------------------------------- Build transfer to skillset UI --------------------------------
        Button skillsetSendButton = new Button("Send");
        Button skillsetCancelButton = new Button("Cancel");
        VBox skillsetVBox = new VBox(5);
        HBox skillsetHBox = new HBox(5);
        skillsetHBox.getChildren().addAll(skillsetSendButton, skillsetCancelButton);
        skillsetVBox.setPadding(insets);
        Label skillsetLabel = new Label("Skillset");
        Label skillsetAgentNoteLabel = new Label("Agent Note");
        TextArea skillsetNoteTextArea = new TextArea();
        skillsetNoteTextArea.setPrefRowCount(10);

        transferToSkillsetTab.setContent(skillsetVBox);
        skillsetVBox.getChildren().addAll(skillsetLabel, skillsetListBox, skillsetAgentNoteLabel, skillsetNoteTextArea, skillsetHBox);
        Scene scene = new Scene(tabPane, 600, 300);
        form.setScene(scene);
        form.show();

        skillsetSendButton.setOnAction(e -> {
            //Implement  email sending functionality
            //...
            //...
        });

        skillsetListBox.setOnAction(e -> {
            String selectedValue = skillsetListBox.getValue();
            if (selectedValue != null && !selectedSkillsetList.contains(selectedValue)) {
                selectedSkillsetList.add(selectedValue);
                System.out.println("Selected elements: " + selectedSkillsetList);
            }
        });

        skillsetCancelButton.setOnAction(e -> {
            form.close();
        });

        skillsetCancelButton.setOnAction(e -> {
            form.close();
        });

        //-------------------------------- Build transfer to user UI --------------------------------
        TableView<User> tableView = new TableView<>();
       /* TableColumn<User, String> LOGONIDCol = new TableColumn<>("LOGONID");
        TableColumn<User, String> firstNameCol = new TableColumn<>("First Name");
        TableColumn<User, String> lastNameCol = new TableColumn<>("Last Name");
        TableColumn<User, String> friendlyNameCol = new TableColumn<>("Friendly Name");
        TableColumn<User, String> userTypeCol = new TableColumn<>("User Type");

        //This is a mokup list, data should be obtained from AACC interaction
        List<User> data = Arrays.asList(
                new User("881108", "Agent401108", "AACC20", "Alex08", "Agent"),
                new User("881108", "Agent401108", "AACC20", "Alex08", "Agent"),
                new User("881108", "Agent401108", "AACC20", "Alex08", "Agent"),
                new User("881108", "Agent401108", "AACC20", "Alex08", "Agent")
        );

        LOGONIDCol.setCellValueFactory(new PropertyValueFactory<>("LOGONID"));
        firstNameCol.setCellValueFactory(new PropertyValueFactory<>("firstName"));
        lastNameCol.setCellValueFactory(new PropertyValueFactory<>("lastName"));
        friendlyNameCol.setCellValueFactory(new PropertyValueFactory<>("friendlyName"));
        userTypeCol.setCellValueFactory(new PropertyValueFactory<>("UserType"));

        tableView.getColumns().addAll(LOGONIDCol, firstNameCol, lastNameCol, friendlyNameCol, userTypeCol);
        tableView.getItems().addAll(data);

        tableView.setTableMenuButtonVisible(false);
        tableView.setPlaceholder(new StackPane());*/

        Label userNoteTextAreaLabel = new Label("Agent note");
        TextArea userNoteTextArea = new TextArea();

        VBox userVbox = new VBox(5);
        userVbox.setPadding(insets);
        HBox userHbox = new HBox(10);
        Button userSendButton = new Button("Send");
        Button userCancelButton = new Button("Cancel");
        userHbox.getChildren().addAll(userSendButton, userCancelButton);
        userVbox.getChildren().addAll(tableView, userNoteTextAreaLabel, userNoteTextArea, userHbox);
        transferToUserTab.setContent(userVbox);

        userSendButton.setOnAction(e -> {
            //Implement send functionality here
            //...
            //...
        });

        userCancelButton.setOnAction(e -> {
            form.close();
        });


        //-------------------------------- Build transfer to external UI --------------------------------
        htmlEditor = new HTMLEditor();
        fileChooser = new FileChooser();
        TextField toField = new TextField();
        toField.setPromptText("To (separate multiple addresses with commas)");

        TextField ccField = new TextField();
        ccField.setPromptText("CC (separate multiple addresses with commas)");

        TextField subjectField = new TextField();
        subjectField.setPromptText("Subject");

        // Create HTMLEditor
        HTMLEditor htmlEditor = new HTMLEditor();
        htmlEditor.setPrefHeight(600);

        // Create a FileChooser for the "Attach" button

        fileChooser.setTitle("Attach File");

        Button attachButton = new Button("Attach");
        attachButton.setPadding(insets);

        attachButton.setOnAction(e -> {
            File selectedFile = fileChooser.showOpenDialog(form);
            if (selectedFile != null) {
                //Implement attachment handling here
                // For example, store the file path and show it to the user
                //...
                //...
                System.out.println("Attached: " + selectedFile.getPath());
            }
        });

        TextArea externalAgentNoteTextArea = new TextArea();
        externalAgentNoteTextArea.setPrefRowCount(10);

        Button externalSendButton = new Button("Send");
        Button externalCancelButton = new Button("Cancel");

        externalSendButton.setOnAction(e -> {
            String to = toField.getText();
            String cc = ccField.getText();
            String subject = subjectField.getText();
            String content = htmlEditor.getHtmlText();

            //Implement email send  handling here
            // For example, store the file path and show it to the user
            //...
            //...

            System.out.println("To: " + to);
            System.out.println("CC: " + cc);
            System.out.println("Subject: " + subject);
            System.out.println("Content: " + content);
        });

        externalCancelButton.setOnAction(e -> {
            form.close();
        });
        Label agentExternalLabel = new Label("Agent note");
        VBox vboxExtTransfer = new VBox(10);
        vboxExtTransfer.setPadding(insets);
        HBox hboxExtTransfer = new HBox();
        hboxExtTransfer.setPadding(insets);
        hboxExtTransfer.getChildren().addAll(externalSendButton, externalCancelButton);
        vboxExtTransfer.getChildren().addAll(toField, ccField, subjectField, htmlEditor, agentExternalLabel, externalAgentNoteTextArea, hboxExtTransfer);
        transferToExternalTab.setContent(vboxExtTransfer);
    }

    public void updateDestinationList(String interactionID, DestinationListI list) {
        String methodName = "updateDestinationList ";
        //TODO conroy1 convoluted: make simpler. Can remove this block when am sure that Forms and Interactions are properly integrated
        if (interactionID.equals(currentInteractionID)) {
            LOG.info(methodName + "Contact ID:" + interactionID + " updating list with " + list.getDestinations().size()
                    + " items");
        } else {
            LOG.error(methodName + "Contact ID:" + interactionID + " does not match current contactID:"
                    + currentInteractionID);
            return;
        }
        /////////

        //if this is a Transfers form, add all destinations.
        //if it's a Consult form, only add Agent destinations

        if  (relocationType== RelocationType.Transfer) {
            LOG.debug(methodName + "Transfer");
            destinationsOL.addAll(list.getDestinations());
        } else if (relocationType== RelocationType.Consult) {
            LOG.debug(methodName + " Consult");
            for (DestinationI item:list.getDestinations()) {
                if  (item.getDestinationType() == DestinationType.Agent) {
                    destinationsOL.add(item);
                }
            }
        } else {
            LOG.error(methodName, " Unsupported relocation type. Destinations: "+list);
        }
    }
    public void setCurrentInteractionId(String id) {
        this.currentInteractionID = id;
    }

    public void initializeForwardForm(InteractionData interactionData) {
        initializeForm(true, interactionData);
    }

    private void initializeForm(boolean transfer, InteractionData interactionData) {
        this.relocationType = RelocationType.Transfer;
        form.titleProperty().set(relocationType.name());
        buildForwardUI(interactionData);
    }

    public void setMediaForm(MediaFormI emailForm) {
        this.mediaForm=emailForm;
    }

    public void setInteractionMedia(Media media) {
        if (media!=null) {
            this.media=media;
            this.mediaSet=true;
        }
    }

    public void setAgentSignature(String agentSignature) {
        this.agentSignature=agentSignature;
    }

    public boolean isMediaSet() {
        return mediaSet;
    }

    public void show() {
        form.show();
    }
}