<script setup>
import { ref, computed } from 'vue'
import { usePage, router } from '@inertiajs/vue3'
import MetroCanvas from '@/Components/MetroMap/MetroCanvas.vue'
import Breadcrumb from '@/Components/MetroMap/Breadcrumb.vue'
import NodePreview from '@/Components/MetroMap/NodePreview.vue'
import FloatingActions from '@/Components/MetroMap/FloatingActions.vue'
import ProjectForm from '@/Components/Forms/ProjectForm.vue'
import CommitmentForm from '@/Components/Forms/CommitmentForm.vue'
import CliBar from '@/Components/Cli/CliBar.vue'

const page = usePage()

const props = defineProps({
    mapData: { type: Object, default: () => ({ lines: [], nodes: [], connections: [], level: 1 }) },
    users: { type: Array, default: () => [] },
    speerpunten: { type: Array, default: () => [] },
})

// Canvas ref
const canvasRef = ref(null)

// Navigation state
const selectedNode = ref(null)
const showPreview = ref(false)

// Dimension tracking (synced from canvas zoom transitions)
const canvasDepth = ref(1)
const canvasDimension = ref(null)

// Reactive breadcrumb based on both page-level and canvas-level navigation
const breadcrumbPath = computed(() => {
    const pageLevel = props.mapData.level ?? 1
    const project = props.mapData.project ?? null
    const path = [{ label: 'Strategie', level: 1, data: null }]

    if (pageLevel === 2 && project) {
        // Page-level project view
        path.push({ label: project.naam ?? project.name ?? 'Project', level: 2, data: project })
    } else if (canvasDepth.value > 1 && canvasDimension.value) {
        // Canvas zoom-in dimension
        path.push({
            label: canvasDimension.value.parentName ?? 'Detail',
            level: 2,
            data: canvasDimension.value,
        })
    }
    return path
})

// Dimension-aware project ID: from page props OR from canvas zoom
const currentProjectId = computed(() => {
    // Page-level project
    if (props.mapData.project?.id) return props.mapData.project.id
    // Canvas zoom-level project
    if (canvasDimension.value?.parentEntityType === 'project') {
        return canvasDimension.value.parentEntityId
    }
    return null
})

// Entity type in current dimension (for FAB awareness)
const currentParentEntityType = computed(() => {
    if (props.mapData.level === 2) return 'project'
    return canvasDimension.value?.parentEntityType ?? null
})

// Handlers
const handleNodeClick = (node) => {
    selectedNode.value = node
    showPreview.value = true
}

const handleNodeHover = (node) => {}
const handleNodeLeave = () => {}

const handleZoomIn = (node) => {
    showPreview.value = false
    if (node.entityType === 'project') {
        router.visit(`/map/project/${node.entityId}`)
    }
}

const handleBreadcrumbNavigate = (item, index) => {
    showPreview.value = false
    selectedNode.value = null
    if (index === 0) {
        router.visit('/map')
    }
}

const handleDimensionChange = (event) => {
    canvasDepth.value = event.depth
    canvasDimension.value = event.dimension ?? null

    // Close preview when dimension changes
    showPreview.value = false
    selectedNode.value = null
}

const handleCliCommand = (command) => {
    console.log('CLI command:', command)
}

const logout = () => {
    router.post('/logout')
}

const user = computed(() => page.props.auth?.user)
const hasNodes = computed(() => props.mapData.nodes && props.mapData.nodes.length > 0)

// Modal state
const showProjectForm = ref(false)
const showCommitmentForm = ref(false)
const editingProject = ref(null)

const handleCreateProject = () => {
    editingProject.value = null
    showProjectForm.value = true
}

const handleCreateCommitment = () => {
    showCommitmentForm.value = true
}

const handleCreateDocument = () => {
    // Future: document upload modal
    console.log('Create document in project:', currentProjectId.value)
}
</script>

<template>
    <div class="metro-map-page">
        <!-- Top bar: breadcrumb left, user/logout right -->
        <div class="top-bar">
            <Breadcrumb
                :path="breadcrumbPath"
                @navigate="handleBreadcrumbNavigate"
            />
            <div class="user-controls">
                <span v-if="user" class="user-name">{{ user.name }}</span>
                <button @click="logout" class="logout-btn">[LOGOUT]</button>
            </div>
        </div>

        <template v-if="hasNodes">
            <MetroCanvas
                ref="canvasRef"
                :nodes="props.mapData.nodes"
                :lines="props.mapData.lines"
                :connections="props.mapData.connections"
                :current-level="props.mapData.level ?? 1"
                @node-click="handleNodeClick"
                @node-hover="handleNodeHover"
                @node-leave="handleNodeLeave"
                @dimension-change="handleDimensionChange"
            />

            <NodePreview
                :node="selectedNode"
                :visible="showPreview"
                @close="showPreview = false"
                @zoom-in="handleZoomIn"
            />
        </template>

        <div v-else class="empty-state">
            <span class="empty-message">Nog geen projecten. Gebruik het + icoon om een thema toe te voegen.</span>
        </div>

        <FloatingActions
            :depth="canvasDepth"
            :parent-entity-type="currentParentEntityType"
            :parent-project-id="currentProjectId"
            @create-project="handleCreateProject"
            @create-theme="handleCreateProject"
            @create-commitment="handleCreateCommitment"
            @create-document="handleCreateDocument"
        />

        <ProjectForm
            :show="showProjectForm"
            :project="editingProject"
            :speerpunten="speerpunten"
            @close="showProjectForm = false"
        />

        <CommitmentForm
            v-if="currentProjectId"
            :show="showCommitmentForm"
            :project-id="currentProjectId"
            :users="users"
            @close="showCommitmentForm = false"
        />

        <CliBar @command="handleCliCommand" />
    </div>
</template>

<style scoped>
.metro-map-page {
    width: 100vw;
    height: 100vh;
    overflow: hidden;
    position: relative;
    background: #1a1a2e;
}

.top-bar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 50;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 16px;
    background: rgba(26, 26, 46, 0.85);
    border-bottom: 1px solid rgba(0, 210, 255, 0.15);
    backdrop-filter: blur(8px);
}

.user-controls {
    display: flex;
    align-items: center;
    gap: 12px;
}

.user-name {
    font-family: 'VT323', monospace;
    font-size: 16px;
    color: #8892b0;
}

.logout-btn {
    font-family: 'VT323', monospace;
    font-size: 14px;
    color: #e94560;
    background: none;
    border: 1px solid rgba(233, 69, 96, 0.3);
    padding: 4px 10px;
    border-radius: 3px;
    cursor: pointer;
    transition: all 0.2s;
}

.logout-btn:hover {
    background: rgba(233, 69, 96, 0.15);
    border-color: #e94560;
    box-shadow: 0 0 10px rgba(233, 69, 96, 0.2);
}

.empty-state {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    padding-top: 48px;
}

.empty-message {
    font-family: 'VT323', monospace;
    font-size: 20px;
    color: #8892b0;
    text-align: center;
    opacity: 0.7;
}
</style>
