<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import Button from 'primevue/button';
import Breadcrumb from 'primevue/breadcrumb';
import InputNumber from 'primevue/inputnumber';
import Card from 'primevue/card';
import StructureParentInfoCard from './StructureParentInfoCard.vue';
import StructureValuationSummary from './StructureValuationSummary.vue';
import StructureControlInfoCard from './StructureControlInfoCard.vue';
import StructureContentsTable from './StructureContentsTable.vue';
import { fixedAssetStructuresService } from '../../services/fixedAssetStructuresService';
import type { FixedAssetStructure } from '../../types/fixedAssetStructure';

const route = useRoute();
const router = useRouter();
const loading = ref(false);

const emptyStructure = (): FixedAssetStructure => ({
    id: '',
    code: 'NUEVA',
    name: '',
    containerCategory: 'Oficina Movil',
    containerSerial: '',
    location: '',
    containerValue: 0,
    status: 'BORRADOR',
    controlInfo: {
        statusLabel: 'Borrador / En proceso',
        createdAt: new Date().toLocaleDateString('es-MX', { day: '2-digit', month: 'long', year: 'numeric' }),
        owner: 'Usuario actual'
    },
    contents: []
});

const structure = ref<FixedAssetStructure>(emptyStructure());
const isEditing = computed(() => Boolean(route.params.id));

const title = computed(() =>
    isEditing.value ? 'Editar Estructura de Activo Compuesto' : 'Crear Estructura de Activo Compuesto'
);

const breadcrumbItems = computed(() => [
    { label: 'Inicio', route: '/' },
    { label: 'Gestion de Activos', route: '/fixed-assets' },
    { label: isEditing.value ? 'Editar Estructura' : 'Crear Estructura' }
]);

const home = { icon: 'pi pi-home', route: '/' };

const loadStructure = async () => {
    if (!route.params.id) return;

    loading.value = true;
    const found = await fixedAssetStructuresService.getStructureById(String(route.params.id));
    if (found) {
        structure.value = JSON.parse(JSON.stringify(found)) as FixedAssetStructure;
    }
    loading.value = false;
};

const saveStructure = () => {
    router.push('/fixed-assets/structures');
};

const cancel = () => {
    router.back();
};

onMounted(loadStructure);
</script>

<template>
    <section class="space-y-5">
        <Breadcrumb :home="home" :model="breadcrumbItems" />

        <div class="flex flex-wrap items-center justify-between gap-3">
            <div>
                <h1 class="text-3xl font-black tracking-tight text-surface-900 dark:text-surface-0">
                    {{ title }}
                </h1>
                <p class="mt-1 text-surface-500 dark:text-surface-400">
                    Configure la jerarquia de activos y asigne los elementos contenidos en el contenedor principal.
                </p>
            </div>
            <div class="flex gap-2">
                <Button label="Cancelar" outlined severity="secondary" @click="cancel" />
                <Button label="Guardar estructura" icon="pi pi-check" :loading="loading" @click="saveStructure" />
            </div>
        </div>

        <div class="grid grid-cols-1 gap-5 xl:grid-cols-12">
            <div class="space-y-5 xl:col-span-8">
                <StructureParentInfoCard :structure="structure" />

                <Card class="shadow-sm">
                    <template #title>
                        <div class="flex items-center gap-2 text-xl">
                            <i class="pi pi-wallet text-primary"></i>
                            <span>Valor del Activo Padre</span>
                        </div>
                    </template>
                    <template #content>
                        <div class="max-w-sm space-y-2">
                            <label class="text-xs font-semibold uppercase tracking-wide text-surface-500">
                                Valor de contenedor
                            </label>
                            <InputNumber
                                v-model="structure.containerValue"
                                mode="currency"
                                currency="MXN"
                                locale="es-MX"
                                class="w-full"
                            />
                        </div>
                    </template>
                </Card>

                <StructureContentsTable v-model="structure.contents" />
            </div>

            <div class="space-y-5 xl:col-span-4">
                <StructureValuationSummary :structure="structure" />
                <StructureControlInfoCard :structure="structure" />
            </div>
        </div>
    </section>
</template>
