<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Card, Typography, Button, Spin, Tag, List, message } from 'ant-design-vue'
import { apiClient, API } from '../router/api'
import type { Role } from '../types/organization'
import type { ProgressSessionApi } from '../types/onboarding'

const route = useRoute()
const router = useRouter()
const roleId = computed(() => route.params.roleId as string)

const loading = ref(false)
const monitoring = ref(false)
const role = ref<Role | null>(null)
const sessions = ref<ProgressSessionApi[]>([])
const feedback = ref<string>('')
const monitorLogs = ref<string[]>([])

const latestSession = computed(() => sessions.value[0] || null)

const websocketUrl = (id: string) => {
    const protocol = window.location.protocol === 'https:' ? 'wss' : 'ws'
    return `${protocol}://${window.location.host}/ws/onboarding/${id}/`
}

const runProgressMonitor = async () => {
    monitoring.value = true
    monitorLogs.value = []

    try {
        const ws = new WebSocket(websocketUrl(roleId.value))

        await new Promise<void>((resolve, reject) => {
            const timeout = window.setTimeout(() => {
                ws.close()
                reject(new Error('Progress monitor timed out'))
            }, 30000)

            ws.onopen = () => {
                ws.send(JSON.stringify({ action: 'progress_monitor', role_uuid: roleId.value }))
            }

            ws.onmessage = (event) => {
                try {
                    const payload = JSON.parse(event.data)
                    if (payload.message) {
                        monitorLogs.value.push(String(payload.message))
                    }

                    if (payload.type === 'completed') {
                        feedback.value = String(
                            payload.content?.feedback || payload.message || 'No feedback returned.',
                        )
                        window.clearTimeout(timeout)
                        ws.close()
                        resolve()
                    }

                    if (payload.type === 'error') {
                        window.clearTimeout(timeout)
                        ws.close()
                        reject(new Error(payload.message || 'Progress monitor failed'))
                    }
                } catch {
                    window.clearTimeout(timeout)
                    ws.close()
                    reject(new Error('Invalid monitor response'))
                }
            }

            ws.onerror = () => {
                window.clearTimeout(timeout)
                ws.close()
                reject(new Error('Progress monitor websocket error'))
            }
        })
    } catch (error) {
        message.error(error instanceof Error ? error.message : 'Failed to run progress monitor')
    } finally {
        monitoring.value = false
    }
}

const loadData = async () => {
    loading.value = true
    try {
        const [rolesRes, sessionsRes] = await Promise.all([
            apiClient.get<Role[]>(API.organization.roles.mine()),
            apiClient.get<ProgressSessionApi[]>(API.onboarding.sessions.list()),
        ])

        const roles = Array.isArray(rolesRes.data) ? rolesRes.data : []
        role.value = roles.find((r) => r.uuid === roleId.value) || null

        const allSessions = Array.isArray(sessionsRes.data) ? sessionsRes.data : []
        sessions.value = allSessions
            .filter((session) => session.role?.uuid === roleId.value)
            .sort(
                (a, b) =>
                    new Date(b.updated_at || 0).getTime() - new Date(a.updated_at || 0).getTime(),
            )

        await runProgressMonitor()
    } catch {
        message.error('Failed to load role progress')
    } finally {
        loading.value = false
    }
}

onMounted(() => {
    loadData()
})
</script>

<template>
    <div class="page">
        <div class="head-row">
            <Typography.Title :level="2">Progress Details</Typography.Title>
            <Button @click="router.push('/progress')">Back to All Progress</Button>
        </div>

        <Card class="panel" :bordered="false">
            <Spin :spinning="loading" tip="Loading role progress...">
                <Typography.Title :level="4">{{ role?.name || 'Unknown Role' }}</Typography.Title>

                <div class="status-row">
                    <Typography.Text strong>Latest Status:</Typography.Text>
                    <Tag
                        :color="
                            latestSession?.status === 'completed'
                                ? 'green'
                                : latestSession?.status === 'active'
                                  ? 'blue'
                                  : 'default'
                        "
                    >
                        {{ latestSession?.status || 'not_started' }}
                    </Tag>
                    <Button type="primary" :loading="monitoring" @click="runProgressMonitor">
                        Refresh Monitor Feedback
                    </Button>
                </div>

                <Typography.Title :level="5" style="margin-top: 1.2rem">
                    Progress Monitor Feedback
                </Typography.Title>
                <Typography.Paragraph class="feedback">
                    {{ feedback || 'No feedback yet.' }}
                </Typography.Paragraph>

                <Typography.Title :level="5">Monitor Activity</Typography.Title>
                <List
                    size="small"
                    :data-source="monitorLogs.length ? monitorLogs : ['No monitor logs yet.']"
                >
                    <template #renderItem="{ item }">
                        <List.Item>{{ item }}</List.Item>
                    </template>
                </List>

                <Typography.Title :level="5" style="margin-top: 1.2rem">
                    Session History
                </Typography.Title>
                <List :data-source="sessions">
                    <template #renderItem="{ item }">
                        <List.Item>
                            <List.Item.Meta
                                :title="`Session ${item.uuid}`"
                                :description="item.updated_at || ''"
                            />
                            <Tag
                                :color="
                                    item.status === 'completed'
                                        ? 'green'
                                        : item.status === 'active'
                                          ? 'blue'
                                          : 'default'
                                "
                            >
                                {{ item.status }}
                            </Tag>
                        </List.Item>
                    </template>
                </List>
            </Spin>
        </Card>
    </div>
</template>

<style scoped>
.page {
    max-width: 960px;
    margin: 0 auto;
    padding: 2rem 1rem;
}
.panel {
    background: #0f172a;
    border: 1px solid #1f2937;
}
.head-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 1rem;
}
.status-row {
    display: flex;
    align-items: center;
    gap: 0.8rem;
    flex-wrap: wrap;
}
.feedback {
    white-space: pre-wrap;
    color: #cbd5e1;
}
</style>
