<template>
    <BaseLayout>
        <main class="content">
            <div class="container-fluid p-0">
                <h1 class="h3 mb-3">Workflows</h1>

                <!-- Active/Unfinished Workflows Section - Only show if there are active workflows -->
                <div v-if="activeWorkflows.length > 0" class="row mb-4">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5 class="card-title mb-0">Workflows in progress</h5>
                                <span class="badge bg-primary">{{ activeWorkflows.length }}</span>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead>
                                            <tr>
                                                <th>Workflow</th>
                                                <th>Status</th>
                                                <th>Progress</th>
                                                <th>Started</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr v-for="workflow in activeWorkflows" :key="workflow.id">
                                                <td>
                                                    <strong>{{ getWorkflowDisplayName(workflow) }}</strong>
                                                    <br>
                                                    <small class="text-muted">{{ workflow.payload?.workflow_config?.category || 'System' }}</small>
                                                </td>
                                                <td>
                                                    <span :class="getStatusBadgeClass(workflow.state)">
                                                        {{ workflow.status_display || workflow.state }}
                                                    </span>
                                                </td>
                                                <td>
                                                    <div class="progress" style="height: 8px;">
                                                        <div class="progress-bar"
                                                             :style="{ width: workflow.progress_percentage + '%' }"
                                                             :class="getProgressBarClass(workflow.state)">
                                                        </div>
                                                    </div>
                                                    <small class="text-muted">{{ workflow.progress_percentage }}%</small>
                                                </td>
                                                <td>{{ formatDate(workflow.started_at) }}</td>
                                                <td>
                                                    <button class="btn btn-sm btn-outline-primary me-1"
                                                            @click="viewWorkflowDetails(workflow)"
                                                            :disabled="loading">
                                                        <b-icon-eye></b-icon-eye>
                                                    </button>
                                                    <button class="btn btn-sm btn-outline-danger"
                                                            @click="abortWorkflowInstance(workflow)"
                                                            :disabled="loading">
                                                        <b-icon-x-circle></b-icon-x-circle>
                                                    </button>
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Available System Workflows Section -->
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">Available Workflows</h5>
                                <small class="text-muted">Start a new workflow instance</small>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div v-for="workflow in availableWorkflows" :key="workflow.id" class="col-lg-4 col-md-6 mb-3">
                                        <div class="card h-100 workflow-card">
                                            <div class="card-body d-flex flex-column">
                                                <div class="d-flex align-items-center mb-3">
                                                    <template v-for="(icon, index) in workflow.icons" :key="icon">
                                                        <div class="workflow-icon me-3">
                                                            <component :is="icon" class="text-primary" style="font-size: 1.5rem;"></component>
                                                        </div>
                                                        <!-- Add arrow between icons, but not after the last one -->
                                                        <div v-if="index < workflow.icons.length - 1" class="workflow-arrow me-3">
                                                            <b-icon-arrow-right class="text-muted" style="font-size: 1rem;"></b-icon-arrow-right>
                                                        </div>
                                                    </template>
                                                    <div class="workflow-header">
                                                        <h6 class="card-title mb-1">{{ workflow.name }}</h6>
                                                        <small class="text-muted">{{ workflow.category }}</small>
                                                    </div>
                                                </div>
                                                <p class="card-text flex-grow-1">{{ workflow.description }}</p>
                                                <div class="mt-auto">
                                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                                        <small class="text-muted">
                                                            <b-icon-clock class="me-1"></b-icon-clock>
                                                            ~{{ workflow.estimatedDuration }}
                                                        </small>
                                                        <span class="badge bg-light text-dark">{{ workflow.steps }} steps</span>
                                                    </div>
                                                    <button class="btn btn-primary w-100"
                                                            @click="startWorkflow(workflow)"
                                                            :disabled="isWorkflowRunning(workflow.id)">
                                                        <b-icon-play-fill class="me-1"></b-icon-play-fill>
                                                        {{ isWorkflowRunning(workflow.id) ? 'Running...' : 'Start Workflow' }}
                                                    </button>
                                                </div>
                                            </div>
                                        </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 { workflowRegistry } from '@/workflows.js';

export default {
    name: 'Workflows',
    components: {
        ...BIcons,
        BaseLayout
    },
    data() {
        return {
            loading: false,
            error: null
        }
    },
    computed: {
        ...mapState(['active_workflows']),
        activeWorkflows() {
            return this.active_workflows;
        },
        availableWorkflows() {
            return workflowRegistry.getAll();
        }
    },
    async mounted() {
        await this.loadActiveWorkflows();
    },
    methods: {
        ...mapActions([
            'fetchActiveWorkflows',
            'createWorkflow',
            'updateWorkflow',
            'deleteWorkflow'
        ]),
        async loadActiveWorkflows() {
            try {
                this.loading = true;
                this.error = null;
                await this.fetchActiveWorkflows();
            } catch (error) {
                console.error('Error loading active workflows:', error);
                this.error = 'Failed to load active workflows';
            } finally {
                this.loading = false;
            }
        },
        getStatusBadgeClass(status) {
            const classes = {
                'running': 'badge bg-success',
                'paused': 'badge bg-warning',
                'failed': 'badge bg-danger',
                'completed': 'badge bg-primary',
                'cancelled': 'badge bg-secondary'
            };
            return classes[status] || 'badge bg-secondary';
        },
        getProgressBarClass(status) {
            const classes = {
                'running': 'bg-success',
                'paused': 'bg-warning',
                'failed': 'bg-danger',
                'completed': 'bg-primary',
                'cancelled': 'bg-secondary'
            };
            return classes[status] || 'bg-secondary';
        },
        formatDate(dateString) {
            if (!dateString) {
                return 'N/A';
            }

            const date = new Date(dateString);

            // Check if the date is valid
            if (isNaN(date.getTime())) {
                console.warn('Invalid date string received:', dateString);
                return 'Invalid Date';
            }

            return new Intl.DateTimeFormat('en-US', {
                month: 'short',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            }).format(date);
        },
        isWorkflowRunning(workflowId) {
            return this.activeWorkflows.some(active =>
                active.name === workflowId &&
                active.state === 'running'
            );
        },
        getWorkflowDisplayName(workflow) {
            // `name` doubles as the workflow type identifier (e.g. 'import-items').
            return workflowRegistry.get(workflow.name)?.name || workflow.name;
        },
        async startWorkflow(workflow) {
            try {
                this.loading = true;
                this.error = null;

                // Use the workflow's toApiFormat method to get properly formatted data
                const workflowData = workflow.toApiFormat();

                const newWorkflow = await this.createWorkflow(workflowData);
                console.log('Workflow started successfully:', newWorkflow);

                // Immediately navigate to the workflow detail view
                // Get the first step from the workflow definition
                const firstStep = workflow.getStepDefinitions()?.[0]?.step || "initial";
                this.$router.push({
                    name: 'workflow-detail',
                    params: {
                        id: newWorkflow.id,
                        step: firstStep
                    }
                });

            } catch (error) {
                console.error('Error starting workflow:', error);
                this.error = `Failed to start ${workflow.name}`;
            } finally {
                this.loading = false;
            }
        },
        async viewWorkflowDetails(workflow) {
            console.log('Viewing details for workflow:', workflow);
            // Navigate to the workflow detail view
            // Use the workflow's current step if available, otherwise use the first step
            const currentStep = workflow.current_step ||
                                workflow.payload?.current_step ||
                                workflow.getStepDefinitions?.()?.[0]?.step ||
                                "initial";

            this.$router.push({
                name: 'workflow-detail',
                params: {
                    id: workflow.id,
                    step: currentStep
                }
            });
        },
        async abortWorkflowInstance(workflow) {
            const displayName = this.getWorkflowDisplayName(workflow);
            if (confirm(`Are you sure you want to abort "${displayName}"?`)) {
                try {
                    this.loading = true;
                    this.error = null;
                    await this.deleteWorkflow(workflow.id);
                    await this.loadActiveWorkflows();
                    console.log('Workflow aborted successfully:', displayName);
                } catch (error) {
                    console.error('Error aborting workflow:', error);
                    this.error = `Failed to abort ${displayName}`;
                } finally {
                    this.loading = false;
                }
            }
        }
    }
}
</script>

<style scoped>
.workflow-card {
    transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
    border: 1px solid #e9ecef;
}

.workflow-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 48px;
    height: 48px;
    background-color: rgba(13, 110, 253, 0.1);
    border-radius: 8px;
    flex-shrink: 0;
}

.workflow-header {
    margin-left: 1rem;
}

.workflow-arrow {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    margin-left: 0.25rem;
    margin-right: 0.25rem;
}

.progress {
    border-radius: 4px;
    background-color: #e9ecef;
}

.progress-bar {
    border-radius: 4px;
    transition: width 0.3s ease;
}

.table th {
    border-top: none;
    font-weight: 600;
    color: #495057;
    font-size: 0.875rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.table td {
    vertical-align: middle;
}

.badge {
    font-size: 0.75rem;
    font-weight: 500;
}

.btn-sm {
    padding: 0.25rem 0.5rem;
    font-size: 0.875rem;
}

.card-header {
    background-color: #f8f9fa;
    border-bottom: 1px solid #e9ecef;
}

.workflow-card .btn {
    border-radius: 6px;
    font-weight: 500;
    transition: all 0.2s ease;
}

.workflow-card .btn:hover {
    transform: translateY(-1px);
}

.workflow-card .btn:disabled {
    opacity: 0.6;
    transform: none;
}
</style>
