<template>
    <div class="contenthidden">
        <StatusBar ref="statusBar" />
        <div class="contentscroll">
            <h2>{{ $t('falukant.branch.title') }}</h2>

            <BranchSelection :branches="branches" :selectedBranch="selectedBranch" @branchSelected="onBranchSelected"
                @createBranch="createBranch" @upgradeBranch="upgradeBranch" ref="branchSelection" />

            <DirectorInfo v-if="selectedBranch" :branchId="selectedBranch.id" ref="directorInfo" />

            <SaleSection v-if="selectedBranch" :branchId="selectedBranch.id" ref="saleSection" />

            <ProductionSection v-if="selectedBranch" :branchId="selectedBranch.id" :products="products"
                ref="productionSection" />

            <StorageSection v-if="selectedBranch" :branchId="selectedBranch.id" ref="storageSection" />

            <RevenueSection v-if="selectedBranch" :products="products"
                :calculateProductRevenue="calculateProductRevenue" :calculateProductProfit="calculateProductProfit"
                ref="revenueSection" />
        </div>
    </div>
</template>

<script>
import StatusBar from '@/components/falukant/StatusBar.vue';
import BranchSelection from '@/components/falukant/BranchSelection.vue';
import DirectorInfo from '@/components/falukant/DirectorInfo.vue';
import SaleSection from '@/components/falukant/SaleSection.vue';
import ProductionSection from '@/components/falukant/ProductionSection.vue';
import StorageSection from '@/components/falukant/StorageSection.vue';
import RevenueSection from '@/components/falukant/RevenueSection.vue';
import apiClient from '@/utils/axios.js';
import { mapState } from 'vuex';

export default {
    name: "BranchView",
    components: {
        StatusBar,
        BranchSelection,
        DirectorInfo,
        SaleSection,
        ProductionSection,
        StorageSection,
        RevenueSection,
    },

    data() {
        return {
            branches: [],
            selectedBranch: null,
            products: [],
        };
    },

    computed: {
        ...mapState(['socket', 'daemonSocket']),
    },

    async mounted() {
        await this.loadBranches();

        const branchId = this.$route.params.branchId;
        await this.loadProducts();

        if (branchId) {
            this.selectedBranch = this.branches.find(
                b => b.id === parseInt(branchId, 10)
            ) || null;
        } else {
            this.selectMainBranch();
        }

        // Daemon-Socket
        if (this.daemonSocket) {
            this.daemonSocket.addEventListener('message', this.handleDaemonMessage);
        }

        // Live-Socket-Events
        [
            "production_ready",
            "stock_change",
            "price_update",
            "director_death",
            "production_started",
            "selled_items",
            "falukantUpdateStatus",
            "falukantBranchUpdate",
            "knowledge_update"
        ].forEach(eventName => {
            if (this.socket) {
                this.socket.on(eventName, data => this.handleEvent({ event: eventName, ...data }));
            }
        });
    },

    beforeUnmount() {
        [
            "production_ready",
            "stock_change",
            "price_update",
            "director_death",
            "production_started",
            "selled_items",
            "falukantUpdateStatus",
            "falukantBranchUpdate",
            "knowledge_update"
        ].forEach(eventName => {
            if (this.socket) {
                this.socket.off(eventName, this.handleEvent);
            }
        });

        if (this.daemonSocket) {
            this.daemonSocket.removeEventListener('message', this.handleDaemonMessage);
        }
    },

    methods: {
        async loadBranches() {
            try {
                const result = await apiClient.get('/api/falukant/branches');
                this.branches = result.data.map(branch => ({
                    id: branch.id,
                    cityName: branch.region.name,
                    type: this.$t(`falukant.branch.types.${branch.branchType.labelTr}`),
                    isMainBranch: branch.isMainBranch,
                }));
                if (!this.selectedBranch) {
                    this.selectMainBranch();
                }
            } catch (error) {
                console.error('Error loading branches:', error);
            }
        },

        async loadProducts() {
            try {
                const productsResult = await apiClient.get('/api/falukant/products');
                this.products = productsResult.data;
            } catch (error) {
                console.error('Error loading products:', error);
            }
        },

        async onBranchSelected(newBranch) {
            this.selectedBranch = newBranch;
            await this.loadProducts();
            this.$nextTick(() => {
                this.$refs.directorInfo?.refresh();
                this.$refs.saleSection?.loadInventory();
                this.$refs.productionSection?.loadProductions();
                this.$refs.storageSection?.loadStorageData();
                this.$refs.revenueSection?.refresh && this.$refs.revenueSection.refresh();
            });
        },

        async createBranch() {
            await this.loadBranches();
        },

        upgradeBranch() {
            if (this.selectedBranch) {
                alert(
                    this.$t(
                        'falukant.branch.actions.upgradeAlert',
                        { branchId: this.selectedBranch.id }
                    )
                );
            }
        },

        selectMainBranch() {
            const main = this.branches.find(b => b.isMainBranch) || null;
            if (main && main !== this.selectedBranch) {
                this.selectedBranch = main;
            }
        },

        calculateProductRevenue(product) {
            if (!product.knowledges || product.knowledges.length === 0) {
                return { absolute: 0, perMinute: 0 };
            }
            const knowledgeFactor = product.knowledges[0].knowledge || 0;
            const maxPrice = product.sellCost;
            const minPrice = maxPrice * 0.6;
            const revenuePerUnit = minPrice + (maxPrice - minPrice) * (knowledgeFactor / 100);
            const perMinute = product.productionTime > 0
                ? revenuePerUnit / product.productionTime
                : 0;
            return {
                absolute: revenuePerUnit.toFixed(2),
                perMinute: perMinute.toFixed(2),
            };
        },

        calculateProductProfit(product) {
            const { absolute: revenueAbsoluteStr, perMinute: revenuePerMinuteStr }
                = this.calculateProductRevenue(product);
            const revenueAbsolute = parseFloat(revenueAbsoluteStr);
            const costPerUnit = 6 * product.category;
            const profitAbsolute = revenueAbsolute - costPerUnit;
            const costPerMinute = product.productionTime > 0
                ? costPerUnit / product.productionTime
                : 0;
            const profitPerMinute = parseFloat(revenuePerMinuteStr) - costPerMinute;
            return {
                absolute: profitAbsolute.toFixed(2),
                perMinute: profitPerMinute.toFixed(2),
            };
        },

        handleEvent(eventData) {
            switch (eventData.event) {
                case 'production_ready':
                    this.$refs.productionSection?.loadProductions();
                    this.$refs.storageSection?.loadStorageData();
                    this.$refs.saleSection?.loadInventory();
                    break;
                case 'stock_change':
                    this.$refs.storageSection?.loadStorageData();
                    this.$refs.saleSection?.loadInventory();
                    break;
                case 'price_update':
                    this.$refs.revenueSection?.refresh();
                    break;
                case 'director_death':
                    this.$refs.directorInfo?.loadDirector();
                    break;
                case 'production_started':
                    this.$refs.productionSection?.loadProductions();
                    break;
                case 'selled_items':
                    this.$refs.saleSection?.loadInventory();
                    this.$refs.storageSection?.loadStorageData();
                    break;
                case 'falukantUpdateStatus':
                case 'falukantBranchUpdate':
                    this.$refs.statusBar?.fetchStatus();
                    this.$refs.productionSection?.loadProductions();
                    this.$refs.storageSection?.loadStorageData();
                    this.$refs.saleSection?.loadInventory();
                    break;
                case 'knowledge_update':
                    this.loadProducts();
                    this.$refs.revenueSection.products = this.products;
                    break;
                default:
                    console.log('Unhandled event:', eventData);
            }
        },

        handleDaemonMessage(event) {
            if (event.data === 'ping') return;
            try {
                const message = JSON.parse(event.data);
                this.handleEvent(message);
            } catch (error) {
                console.error('Error processing daemon message:', error);
            }
        },
    },
};
</script>

<style scoped lang="scss">
h2 {
    padding-top: 20px;
}
</style>