<template>
    <BaseLayout>
        <main class="content">
            <div class="container-fluid p-0">
                <!-- Workflow Header -->
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <div>
                        <nav aria-label="breadcrumb">
                            <ol class="breadcrumb">
                                <li class="breadcrumb-item">
                                    <router-link to="/workflows" class="text-decoration-none">Workflows</router-link>
                                </li>
                                <li class="breadcrumb-item active" aria-current="page">{{ workflowDefinition?.title || workflowInstance?.title || 'Loading...' }}</li>
                            </ol>
                        </nav>
                    </div>
                    <div class="btn-group breadcrumb" role="group">
                        <button class="btn btn-outline-secondary" @click="$router.go(-1)">
                            <b-icon-arrow-left class="me-1"></b-icon-arrow-left>
                            Back
                        </button>
                        <button v-if="canAbort" class="btn btn-outline-danger" @click="abortWorkflow" :disabled="loading">
                            <b-icon-x-circle class="me-1"></b-icon-x-circle>
                            Abort
                        </button>
                    </div>
                </div>

                <!-- Loading State -->
                <div v-if="loading && !workflowInstance" class="text-center py-5">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-2">Loading workflow details...</p>
                </div>

                <!-- Error State -->
                <div v-else-if="error" class="alert alert-danger">
                    <b-icon-exclamation-triangle class="me-2"></b-icon-exclamation-triangle>
                    {{ error }}
                </div>

                <!-- Workflow Content -->
                <div v-else-if="workflowInstance" class="row">
                    <!-- Main Content Area -->
                    <div class="col-xl-9 col-lg-12 col-lg-9-ex">
                        <!-- Current Step Content -->
                        <div class="card">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <div>
                                    <h5 class="card-title mb-0">
                                        {{ currentStepDefinition?.name || `Step ${currentStep}` }}
                                    </h5>
                                    <small class="text-muted">{{ currentStepDefinition?.description }}</small>
                                </div>
                                <div class="step-navigation">
                                    <button class="btn btn-sm btn-outline-secondary me-1"
                                            @click="handlePrevStep"
                                            :disabled="!canNavigatePrev">
                                        <b-icon-chevron-left></b-icon-chevron-left>
                                    </button>
                                    <span class="mx-2 small">{{ currentStepIndex + 1 }} / {{ totalSteps }}</span>
                                    <button class="btn btn-sm btn-outline-secondary"
                                            @click="handleNextStep"
                                            :disabled="!canNavigateNext">
                                        <b-icon-chevron-right></b-icon-chevron-right>
                                    </button>
                                </div>
                            </div>
                            <div class="card-body">
                                <!-- Step-specific content based on workflow type and current step -->
                                <component
                                    v-if="workflowComponent"
                                    :is="workflowComponent"
                                    :workflow-instance="workflowInstance"
                                    :step="currentStep"
                                    :payload="workflowInstance.payload"
                                    @update="handleStepUpdate"
                                    @next="handleNextStep"
                                    @prev="handlePrevStep"
                                    @complete="completeWorkflow"
                                />

                                <!-- Default step content if no specific component -->
                                <div v-else class="text-center py-5">
                                    <b-icon-gear class="text-muted mb-3" style="font-size: 3rem;"></b-icon-gear>
                                    <h5 class="text-muted">{{ currentStepDefinition?.name || 'Step Content' }}</h5>
                                    <p class="text-muted">{{ currentStepDefinition?.description || 'This step is in progress.' }}</p>

                                    <!-- Step Navigation Buttons -->
                                    <div class="mt-4">
                                        <button v-if="canNavigatePrev"
                                                class="btn btn-outline-secondary me-2"
                                                @click="handlePrevStep">
                                            <b-icon-chevron-left class="me-1"></b-icon-chevron-left>
                                            Previous
                                        </button>
                                        <button v-if="canNavigateNext"
                                                class="btn btn-primary"
                                                @click="handleNextStep">
                                            Next
                                            <b-icon-chevron-right class="ms-1"></b-icon-chevron-right>
                                        </button>
                                        <button v-else-if="currentStepIndex === stepDefinitions.length - 1"
                                                class="btn btn-success"
                                                @click="completeWorkflow">
                                            <b-icon-check-circle class="me-1"></b-icon-check-circle>
                                            Complete Workflow
                                        </button>
                                    </div>
                                </div>

                                <!-- Debug Info (only in development) -->
                                <div v-if="true" class="mt-4 border-top pt-3">
                                    <details>
                                        <summary class="text-muted small">Debug Info</summary>
                                        <pre class="small mt-2">{{ JSON.stringify(workflowInstance, null, 2) }}</pre>
                                    </details>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- Workflow Progress Sidebar -->
                    <div class="col-lg-3 mb-4 d-none d-xl-block d-lg-block-ex">
                        <div class="card">
                            <div class="card-header">
                                <h6 class="card-title mb-0">Progress Overview</h6>
                            </div>
                            <div class="card-body">
                                <!-- Overall Progress -->
                                <div class="mb-3">
                                    <div class="d-flex justify-content-between align-items-center mb-1">
                                        <small class="text-muted">Overall Progress</small>
                                        <small class="fw-bold">{{ workflowInstance.progress_percentage }}%</small>
                                    </div>
                                    <div class="progress mb-2" style="height: 8px;">
                                        <div class="progress-bar"
                                             :style="{ width: workflowInstance.progress_percentage + '%' }"
                                             :class="getProgressBarClass(workflowInstance.state)">
                                        </div>
                                    </div>
                                    <span :class="getStatusBadgeClass(workflowInstance.state)">
                                        {{ workflowInstance.status_display || workflowInstance.state }}
                                    </span>
                                </div>

                                <!-- Step List -->
                                <div class="workflow-steps">
                                    <h6 class="mb-3">Steps</h6>
                                    <div v-for="step in stepDefinitions" :key="step.step" class="step-item mb-3">
                                        <div class="d-flex align-items-center">
                                            <div class="step-indicator me-2"
                                                 :class="getStepClass(step.step)">
                                                <span v-if="isStepCompleted(step.step)">
                                                    <b-icon-check class="text-white"></b-icon-check>
                                                </span>
                                                <span v-else-if="isStepCurrent(step.step)">
                                                    {{ step.step }}
                                                </span>
                                                <span v-else class="text-muted">
                                                    {{ step.step }}
                                                </span>
                                            </div>
                                            <div class="flex-grow-1">
                                                <div class="fw-bold small"
                                                     :class="{ 'text-primary': isStepCurrent(step.step) }">
                                                    {{ step.name }}
                                                </div>
                                                <div class="text-muted small">{{ step.description }}</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Workflow Info -->
                                <div class="border-top pt-3 mt-3">
                                    <div class="mb-2">
                                        <small class="text-muted">Started:</small>
                                        <div class="fw-bold">{{ formatDateTime(workflowInstance.started_at) }}</div>
                                    </div>
                                    <div v-if="workflowInstance.estimated_completion" class="mb-2">
                                        <small class="text-muted">Estimated completion:</small>
                                        <div class="fw-bold">{{ formatDateTime(workflowInstance.estimated_completion) }}</div>
                                    </div>
                                    <div v-if="workflowDefinition">
                                        <small class="text-muted">Category:</small>
                                        <div class="fw-bold">{{ workflowDefinition.category }}</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </BaseLayout>
</template>

<script>
import * as BIcons from "bootstrap-icons-vue";
import BaseLayout from "@/components/BaseLayout.vue";
import { mapState, mapActions } from 'vuex';
import { getWorkflow, getWorkflowComponent } from '@/workflows.js';

export default {
    name: 'WorkflowDetail',
    components: {
        ...BIcons,
        BaseLayout
    },
    props: {
        id: {
            type: [String, Number],
            required: true
        },
        step: {
            type: String,
            default: "1"
        }
    },
    data() {
        return {
            loading: false,
            error: null,
            workflowInstance: null,
            refreshInterval: null
        }
    },
    computed: {
        ...mapState(['active_workflows']),

        currentStep() {
            return this.step || "1";
        },

        workflowDefinition() {
            // `name` doubles as the workflow type identifier (e.g. 'import-items').
            if (!this.workflowInstance?.slug) return null;
            return getWorkflow(this.workflowInstance.slug);
        },

        getWorkflowDisplayName() {
            return getWorkflow(this.workflowInstance.slug)?.title;
        },

        stepDefinitions() {
            return this.workflowDefinition?.stepDefinitions || [];
        },

        totalSteps() {
            return this.stepDefinitions.length || this.workflowInstance?.total_steps || 1;
        },

        currentStepDefinition() {
            return this.stepDefinitions.find(step => step.step === this.currentStep);
        },

        canAbort() {
            return this.workflowInstance?.state === 'running';
        },

        workflowComponent() {
            // The returned component decides what to render itself, based on the `step` prop it receives.
            const workflowType = this.workflowInstance?.slug;
            return workflowType ? getWorkflowComponent(workflowType) : null;
        },

        currentStepIndex() {
            // Find the index of the current step in the stepDefinitions array
            return this.stepDefinitions.findIndex(step => step.step === this.currentStep);
        },

        canNavigateNext() {
            // Check if we can navigate to the next step
            return this.currentStepIndex >= 0 && this.currentStepIndex < this.stepDefinitions.length - 1;
        },

        canNavigatePrev() {
            // Check if we can navigate to the previous step
            return this.currentStepIndex > 0;
        },

        hasCustomComponent() {
            // Check if the current workflow has a custom component defined
            return this.workflowComponent !== null;
        },

        componentStatusClass() {
            return this.hasCustomComponent ? 'bg-light border-success' : 'bg-light border-muted';
        },

        componentStatusText() {
            return this.hasCustomComponent ? 'Using custom component' : 'Using default view';
        }
    },

    watch: {
        step(newStep) {
            // Update route when step changes - no need for parseInt since both are strings
            if (newStep !== this.currentStep) {
                this.$router.push({
                    name: 'workflow-detail',
                    params: { id: this.id, step: newStep }
                });
            }
        }
    },

    async mounted() {
        await this.loadWorkflowInstance();
    },

    methods: {
        ...mapActions([
            'fetchActiveWorkflows',
            'updateWorkflow',
            'deleteWorkflow'
        ]),

        async loadWorkflowInstance() {
            try {
                this.loading = true;
                this.error = null;

                await this.fetchActiveWorkflows();

                // Try to get from store first
                this.workflowInstance = this.active_workflows?.find(w => w.id == this.id);
                
                if (!this.workflowInstance) {
                    throw new Error('Workflow not found');
                }
            } catch (error) {
                console.error('Error loading workflow:', error);
                this.error = error.message || 'Failed to load workflow details';
            } finally {
                this.loading = false;
            }
        },

        navigateToStep(step) {
            const stepStr = String(step);
            // For navigation, we need to validate the step exists in step definitions
            const stepExists = this.stepDefinitions.some(step => step.step === stepStr);
            if (stepExists || (step >= 1 && step <= this.totalSteps)) {
                this.$router.push({
                    name: 'workflow-detail',
                    params: { id: this.id, step: stepStr }
                });
            }
        },

        handleNextStep() {
            // Find the next step in stepDefinitions
            const currentIndex = this.stepDefinitions.findIndex(step => step.step === this.currentStep);
            if (currentIndex >= 0 && currentIndex < this.stepDefinitions.length - 1) {
                const nextStep = this.stepDefinitions[currentIndex + 1].step;
                this.navigateToStep(nextStep);
            }
        },

        handlePrevStep() {
            // Find the previous step in stepDefinitions
            const currentIndex = this.stepDefinitions.findIndex(step => step.step === this.currentStep);
            if (currentIndex > 0) {
                const prevStep = this.stepDefinitions[currentIndex - 1].step;
                this.navigateToStep(prevStep);
            }
        },

        async handleStepUpdate(payload) {
            try {
                // Update the workflow instance with new payload data
                const updatedWorkflow = {
                    ...this.workflowInstance,
                    payload: {
                        ...this.workflowInstance.payload,
                        ...payload
                    }
                };

                await this.updateWorkflow(updatedWorkflow);
                this.workflowInstance = updatedWorkflow;
            } catch (error) {
                console.error('Error updating workflow step:', error);
                this.error = 'Failed to update workflow step';
            }
        },

        async completeWorkflow() {
            try {
                this.loading = true;
                const updatedWorkflow = {
                    ...this.workflowInstance,
                    state: 'completed'
                };

                await this.updateWorkflow(updatedWorkflow);
                this.$router.push('/workflows');
            } catch (error) {
                console.error('Error completing workflow:', error);
                this.error = 'Failed to complete workflow';
            } finally {
                this.loading = false;
            }
        },

        async abortWorkflow() {
            try {
                this.loading = true;
                await this.deleteWorkflow(this.workflowInstance.id);
                this.$router.push('/workflows');
            } catch (error) {
                console.error('Error aborting workflow:', error);
                this.error = 'Failed to abort workflow';
            } finally {
                this.loading = false;
            }
        },

        isStepCompleted(stepNumber) {
            // Check if a step is completed based on current step
            const currentStepNum = parseInt(this.currentStep) || 1;
            return parseInt(stepNumber) < currentStepNum;
        },

        isStepCurrent(stepNumber) {
            // Check if a step is the current active step
            return String(stepNumber) === String(this.currentStep);
        },

        getStepClass(stepNumber) {
            if (this.isStepCompleted(stepNumber)) {
                return 'step-indicator-completed bg-success';
            } else if (this.isStepCurrent(stepNumber)) {
                return 'step-indicator-current bg-primary text-white';
            } else {
                return 'step-indicator-pending bg-light border';
            }
        },

        getProgressBarClass(state) {
            const classMap = {
                'running': 'bg-primary',
                'completed': 'bg-success',
                'failed': 'bg-danger',
                'aborted': 'bg-warning'
            };
            return classMap[state] || 'bg-secondary';
        },

        getStatusBadgeClass(state) {
            const classMap = {
                'running': 'badge bg-primary',
                'completed': 'badge bg-success',
                'failed': 'badge bg-danger',
                'aborted': 'badge bg-warning text-dark'
            };
            return classMap[state] || 'badge bg-secondary';
        },

        formatDateTime(dateString) {
            if (!dateString) return 'N/A';
            return new Date(dateString).toLocaleString();
        }
    }
}
</script>

<style scoped>
.workflow-steps {
    counter-reset: step-counter;
}

.step-item {
    position: relative;
    padding-left: 2rem;
}

.step-indicator {
    position: absolute;
    left: 0;
    top: 0.5rem;
    width: 1.5rem;
    height: 1.5rem;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    color: #fff;
}

.step-indicator-completed {
    background-color: #28a745;
}

.step-indicator-current {
    background-color: #007bff;
}

.step-indicator-pending {
    background-color: #6c757d;
}

.step-navigation {
    min-width: 120px;
}

.btn-group.breadcrumb{
    padding: calc(0.5rem - 1px) 1rem;
}
</style>
