import { renderBarChart } from '../utils/charts';

export function registerLiveAnalysisPage(Alpine) {
    Alpine.data('liveAnalysisPage', () => ({
        uploading: false,
        fileSelected: false,
        fileName: '',
        fileSize: '',
        file: null,
        dragOver: false,
        errorMessage: '',
        result: null,
        loading: false,
        selectedCreator: '',

        init() {
            // Khôi phục dữ liệu từ session khi load trang
            this.loadSessionData();
            // Tự động render biểu đồ khi result thay đổi (kể cả null → empty state)
            this.$watch('result', () => {
                this.selectedCreator = '';
                this.$nextTick(() => this.renderLiveCharts());
            });
            // Đổi creator trọng tâm → render lại biểu đồ
            this.$watch('selectedCreator', () => {
                this.$nextTick(() => this.renderLiveCharts());
            });
        },

        /**
         * Render tất cả biểu đồ của trang. Khi chưa có dữ liệu (result null)
         * vẫn render frame rỗng để các thành phần luôn hiển thị.
         */
        renderLiveCharts() {
            this.renderHourChart();
            this.renderDailyChart();
        },

        renderHourChart() {
            const m = this.metrics;
            const items = (m.hour_stats ?? []).map(h => ({ label: h.label, gmv: h.gmv, orders: h.orders }));
            renderBarChart('live-hour-chart-svg', 'live-hour-chart-tooltip', items, {
                color: '#14b8a6',
                lineColor: '#2563eb',
                legendId: 'live-hour-chart-legend',
            });
        },

        renderDailyChart() {
            const m = this.metrics;
            const items = (m.daily_stats ?? []).map(d => ({ label: d.label, gmv: d.gmv, orders: d.orders }));
            renderBarChart('live-daily-chart-svg', 'live-daily-chart-tooltip', items, {
                color: '#6366f1',
                lineColor: '#2563eb',
                legendId: 'live-daily-chart-legend',
            });
},

        /**
         * KPI tổng hợp cho các card tính toán phía trên.
         * Khi người dùng chọn 1 creator từ bảng "Top creator theo GMV",
         * toàn bộ trang (cards, biểu đồ, các bảng khác) tính toán lại theo creator đó.
         * Riêng bảng "Top creator theo GMV" vẫn giữ nguyên toàn bộ để chọn đổi creator.
         */
        get metrics() {
            const full = this.result?.live_metrics || {};
            if (!this.selectedCreator) return full;
            return this.buildCreatorMetrics(full, this.selectedCreator);
        },

        /**
         * Tính lại metrics cho 1 creator từ chi tiết từng buổi LIVE.
         */
        buildCreatorMetrics(full, creator) {
            const rows = (full.session_details ?? []).filter(r => r.creator === creator);

            let gmv = 0, orders = 0, refund = 0, commission = 0, imp = 0, mins = 0, items = 0;
            let productImp = 0, productClicks = 0, productViewers = 0, likes = 0, comments = 0, shares = 0;
            let engagementViews = 0;
            const hourMap = {};
            const dayMap = {};

            rows.forEach(row => {
                const gmvV = Number(row.gmv) || 0;
                const ordersV = Number(row.orders) || 0;
                const refundV = Number(row.refund) || 0;
                const commissionV = Number(row.commission) || 0;
                const impV = Number(row.impressions) || 0;
                const itemsV = Number(row.items) || 0;
                const productImpV = Number(row.product_imp) || 0;
                const productClicksV = Number(row.product_clicks) || 0;
                const productViewersV = Number(row.product_viewers) || 0;
                const likesV = Number(row.likes) || 0;
                const commentsV = Number(row.comments) || 0;
                const sharesV = Number(row.shares) || 0;
                const durMin = Number(row.duration_min) || 0;

                gmv += gmvV;
                orders += ordersV;
                refund += refundV;
                commission += commissionV;
                imp += impV;
                mins += durMin;
                items += itemsV;
                productImp += productImpV;
                productClicks += productClicksV;
                productViewers += productViewersV;
                likes += likesV;
                comments += commentsV;
                shares += sharesV;

                const engagementV = Number(row.engagement) || 0;
                const sessionViews = engagementV > 0 ? (likesV + commentsV + sharesV) / engagementV : 0;
                engagementViews += sessionViews;

                if (row.hour !== null && row.hour !== undefined && row.hour !== '') {
                    const hour = Number(row.hour);
                    hourMap[hour] = hourMap[hour] || { gmv: 0, orders: 0 };
                    hourMap[hour].gmv += gmvV;
                    hourMap[hour].orders += ordersV;
                }

                if (row.start_date) {
                    dayMap[row.start_date] = dayMap[row.start_date] || { gmv: 0, orders: 0, refund: 0, commission: 0, sessions: 0 };
                    dayMap[row.start_date].gmv += gmvV;
                    dayMap[row.start_date].orders += ordersV;
                    dayMap[row.start_date].refund += refundV;
                    dayMap[row.start_date].commission += commissionV;
                    dayMap[row.start_date].sessions += 1;
                }
            });

            const sessionCount = rows.length;
            const aov = orders > 0 ? gmv / orders : 0;
            const gmvHour = mins > 0 ? gmv / (mins / 60) : 0;
            const refundRate = gmv > 0 ? refund / gmv : 0;
            const commissionRate = gmv > 0 ? commission / gmv : 0;
            const netGmv = gmv - refund;
            const netRevenue = netGmv - commission;
            const interactions = likes + comments + shares;

            const hourStats = Object.keys(hourMap).sort((a, b) => a - b).map(h => ({
                hour: Number(h),
                label: String(h).padStart(2, '0') + ':00',
                gmv: hourMap[h].gmv,
                orders: hourMap[h].orders,
            }));

            const dailyStats = Object.keys(dayMap).sort().map(d => {
                const parts = d.split('-');
                const label = parts.length === 3 ? `${parts[2]}/${parts[1]}` : d;
                return {
                    date: d,
                    label,
                    gmv: dayMap[d].gmv,
                    orders: dayMap[d].orders,
                    refund: dayMap[d].refund,
                    commission: dayMap[d].commission,
                    sessions: dayMap[d].sessions,
                };
            });

            const interactionsTotal = interactions;

            return {
                session_count: sessionCount,
                gmv,
                orders,
                items,
                aov,
                commission,
                commission_rate: commissionRate,
                net_gmv: netGmv,
                net_revenue: netRevenue,
                gmv_hour: gmvHour,
                ref_hours: mins / 60,
                refund,
                refund_rate: refundRate,
                imp,
                product_imp: productImp,
                product_clicks: productClicks,
                product_viewers: productViewers,
                likes,
                comments,
                shares,
                interactions,

                top_creators: full.top_creators ?? [],
                top_products: full.top_products ?? [],
                hour_stats: hourStats,
                daily_stats: dailyStats,
                funnel: [
                    { label: 'Hiển thị LIVE', value: imp },
                    { label: 'Hiển thị sản phẩm', value: productImp },
                    { label: 'Click sản phẩm', value: productClicks },
                    { label: 'Người xem sản phẩm', value: productViewers },
                    { label: 'Đơn hàng', value: orders },
                ],
                funnel_metrics: {
                    ctr: productImp > 0 ? productClicks / productImp : 0,
                    click_conv: productClicks > 0 ? orders / productClicks : 0,
                },
                refund_ranking: [{
                    creator: creator,
                    sessions: sessionCount,
                    gmv,
                    refund,
                    refund_rate: refundRate,
                }],
                engagement_ranking: [{
                    creator: creator,
                    sessions: sessionCount,
                    likes,
                    comments,
                    shares,
                    interactions: interactionsTotal,
                    engagement_rate: engagementViews > 0 ? interactionsTotal / engagementViews : 0,
                }],
                product_metrics: [{
                    creator: creator,
                    sessions: sessionCount,
                    product_imp: productImp,
                    product_clicks: productClicks,
                    product_viewers: productViewers,
                    likes,
                    comments,
                    shares,
                    interactions: interactionsTotal,
                    ctr: productImp > 0 ? productClicks / productImp : 0,
                }],
                session_details: rows,
                creator_filter_options: full.creator_filter_options ?? [],
            };
        },

        /**
         * Toggle chọn creator trọng tâm. Bấm vào đúng creator đang chọn → bỏ lọc.
         */
        toggleCreator(creator) {
            this.selectedCreator = this.selectedCreator === creator ? '' : creator;
        },

        // ───── Sub text cho các card KPI ─────
        subSessions() {
            const m = this.metrics;
            return (m.session_count ?? 0) + ' buổi LIVE';
        },

        subAov() {
            return 'AOV ' + this.formatLiveMoney(this.metrics.aov);
        },

        subNetGmv() {
            return 'Hoàn tiền ' + this.formatLiveMoney(this.metrics.refund) + ' (' + this.formatRate(this.metrics.refund_rate) + ')';
        },

        subNetRevenue() {
            return 'Hoa hồng ' + this.formatLiveMoney(this.metrics.commission) + ' (' + this.formatRate(this.metrics.commission_rate) + ')';
        },

        subHours() {
            const m = this.metrics;
            return this.formatLiveNumber(m.ref_hours) + ' giờ live';
        },

        // ───── Định dạng số cho KPI ─────
        formatLiveMoney(value) {
            if (value === null || value === undefined || value === '') return '-';
            return Number(value).toLocaleString('vi-VN', { maximumFractionDigits: 0 });
        },

        formatLiveNumber(value) {
            if (value === null || value === undefined || value === '') return '-';
            const n = Number(value);
            if (Number.isInteger(n)) return n.toLocaleString('vi-VN');
            return n.toLocaleString('vi-VN', { minimumFractionDigits: 1, maximumFractionDigits: 1 });
        },

        async loadSessionData() {
            try {
                const resp = await fetch('/analysis/live/session-data', {
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                    },
                });
                const data = await resp.json();
                if (resp.ok && data.success && data.data) {
                    this.result = data.data;
                }
            } catch (e) {
                // Không có session — im lặng
            }
        },

        handleFileSelect(e) {
            const file = e.target.files?.[0];
            if (!file) return;
            this.setFile(file);
        },

        handleDrop(e) {
            this.dragOver = false;
            const file = e.dataTransfer?.files?.[0];
            if (!file) return;
            this.setFile(file);
        },

        setFile(file) {
            const valid = ['.xlsx', '.xls', '.csv'];
            const ext = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
            if (!valid.includes(ext)) {
                this.errorMessage = 'Chỉ chấp nhận file Excel (.xlsx, .xls) hoặc CSV (.csv).';
                return;
            }
            this.errorMessage = '';
            this.file = file;
            this.fileName = file.name;
            this.fileSize = this.formatFileSize(file.size);
            this.fileSelected = true;
            this.result = null;
        },

        resetUpload() {
            this.file = null;
            this.fileSelected = false;
            this.fileName = '';
            this.fileSize = '';
            this.errorMessage = '';
            this.result = null;
            const fileInput = this.$el.querySelector('input[type="file"]'); if (fileInput) fileInput.value = '';
        },

        async handleUpload() {
            if (!this.file) return;
            this.uploading = true;
            this.errorMessage = '';

            try {
                const formData = new FormData();
                formData.append('file', this.file);

                const resp = await fetch('/analysis/live/upload', {
                    method: 'POST',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || '',
                    },
                    body: formData,
                });

                const data = await resp.json();
                if (!resp.ok || !data.success) {
                    throw new Error(data.message || 'Xử lý file thất bại.');
                }

                this.result = data;
                this.fileSelected = false;
                this.file = null;
                showSuccess('Thành công', 'Phân tích file hoàn tất.');
            } catch (e) {
                this.errorMessage = e.message || 'Có lỗi xảy ra khi xử lý file.';
                showError('Lỗi', this.errorMessage);
            } finally {
                this.uploading = false;
            }
        },

        async clearData() {
            try {
                const resp = await fetch('/analysis/live/clear', {
                    method: 'POST',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || '',
                    },
                });

                const data = await resp.json();
                if (!resp.ok || !data.success) {
                    throw new Error(data.message || 'Xoá dữ liệu thất bại.');
                }

                this.result = null;
                this.fileSelected = false;
                this.fileName = '';
                this.fileSize = '';
                this.file = null;
                this.errorMessage = '';
                const fileInput = this.$el.querySelector('input[type="file"]'); if (fileInput) fileInput.value = '';
                showSuccess('Đã xoá', 'Dữ liệu phân tích đã được xoá.');
            } catch (e) {
                showError('Lỗi', e.message || 'Có lỗi xảy ra khi xoá dữ liệu.');
            }
        },

        formatFileSize(bytes) {
            if (bytes < 1024) return bytes + ' B';
            if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB';
            return (bytes / 1048576).toFixed(1) + ' MB';
        },

        // ───── Getter dữ liệu cho các phần phân tích bên dưới ─────
        get topCreators() {
            return this.metrics.top_creators ?? [];
        },

        get sessionDetails() {
            return this.metrics.session_details ?? [];
        },

        get funnelSteps() {
            return this.metrics.funnel ?? [];
        },

        get funnelMetrics() {
            return this.metrics.funnel_metrics ?? {};
        },

        get refundRanking() {
            return this.metrics.refund_ranking ?? [];
        },

        get engagementRanking() {
            return this.metrics.engagement_ranking ?? [];
        },

        get productRanking() {
            return this.metrics.product_metrics ?? [];
        },

        /**
         * Chiều rộng ô thanh phễu tính theo phần trăm so với bước lớn nhất
         */
        funnelBarWidth(value) {
            const max = Math.max(...this.funnelSteps.map(s => Number(s.value) || 0), 1);
            return max > 0 ? Math.max(1, (Number(value) || 0) / max * 100) : 0;
        },

        // ───── Bộ lọc bảng chi tiết từng buổi LIVE ─────
        orderSearchCreatorInput: '',
        orderSearchCreator: '',
        orderDateFrom: '',
        orderDateTo: '',

        get creatorFilterOptions() {
            return this.metrics.creator_filter_options ?? [];
        },

        get filteredSessionDetails() {
            const all = this.sessionDetails;
            const sc = (this.orderSearchCreator || '').toLowerCase().trim();

            let fromDate = null, toDate = null;
            if (this.orderDateFrom) {
                const d = new Date(this.orderDateFrom + 'T00:00:00');
                if (!isNaN(d)) fromDate = d;
            }
            if (this.orderDateTo) {
                const d = new Date(this.orderDateTo + 'T00:00:00');
                if (!isNaN(d)) toDate = d;
            }
            if (toDate) {
                toDate.setHours(23, 59, 59, 999);
            }

            return all.filter(row => {
                if (sc && !(row.creator || '').toLowerCase().includes(sc)) return false;
                if (fromDate || toDate) {
                    if (!row.start_date) {
                        if (fromDate || toDate) return false;
                    } else {
                        const rowDate = new Date(row.start_date);
                        if (isNaN(rowDate)) {
                            if (fromDate || toDate) return false;
                        } else {
                            if (fromDate && rowDate < fromDate) return false;
                            if (toDate && rowDate > toDate) return false;
                        }
                    }
                }
                return true;
            });
        },

        applySearchCreator() {
            this.orderSearchCreator = this.orderSearchCreatorInput;
        },

        applySearchCreatorOnEnter(e) {
            if (e.key === 'Enter') { this.applySearchCreator(); }
        },

        resetOrderFilters() {
            this.orderSearchCreator = '';
            this.orderSearchCreatorInput = '';
            this.orderDateFrom = '';
            this.orderDateTo = '';
        },

        formatDuration(min) {
            if (min === null || min === undefined || min === '') return '-';
            const n = Number(min);
            if (n < 60) return this.formatLiveNumber(n) + ' phút';
            const h = Math.floor(n / 60);
            const r = Math.round(n % 60);
            return r > 0 ? `${h}g${r}p` : `${h} giờ`;
        },

        formatRate(value) {
            if (value === null || value === undefined || value === '') return '-';
            return (Number(value) * 100).toLocaleString('vi-VN', { maximumFractionDigits: 2 }) + '%';
        },

/**
         * Đánh giá cột % Hoàn bằng ký hiệu (thay vì tạo SVG thủ công).
         * Chỉ đánh giá khi có GMV (có dữ liệu tính % hoàn).
         * 0–3%: Tốt ✓ xanh   4–8.99%: Cân nhắc ⚠ vàng   ≥9%: Cảnh báo ✗ đỏ
         */
        refundRateIcon(value, gmv) {
            if (Number(gmv || 0) <= 0) return '';
            const rate = (Number(value) || 0) * 100;
            if (rate < 4) return '<span style="color:#16a34a;font-size:14px">&check;</span>';
            if (rate < 9) return '<span style="color:#f59e0b;font-size:14px">&#9888;&#65039;</span>';
            return '<span style="color:#dc2626;font-size:14px">&cross;</span>';
        },
    }));
}
