import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ChartsModule } from '@progress/kendo-angular-charts';
import { AuthService, UserInfo } from '../../../../shared/services/auth.service';
import { MealAttendanceApiService } from '../../../../features/meal-attendance/services/meal-attendance-api.service';

interface Transaction {
    id: string;
    title: string;
    amount: number;
    status: 'active' | 'pending' | 'completed';
    statusLabel: string;
    date: Date;
    progress: number;
}

@Component({
    selector: 'app-dashboard',
    standalone: true,
    imports: [CommonModule, ChartsModule],
    templateUrl: './dashboard.component.html',
    styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {
    currentUser: UserInfo | null = null;

    // Sunday attendance trend (last 8 weeks) for the chart.
    attendanceDates: string[] = [];
    attendanceAdult: number[] = [];
    attendanceYouth: number[] = [];
    attendanceKid: number[] = [];
    attendanceTotal: number[] = [];
    hasAttendanceData = false;

    activeTransactions = 5;
    pendingTasks = 12;
    completedTransactions = 23;
    totalValue = 1250000;

    recentTransactions: Transaction[] = [
        {
            id: 'RBJ-1001',
            title: 'Maple Street Purchase Escrow',
            amount: 425000,
            status: 'active',
            statusLabel: 'Open',
            date: new Date('2026-04-24'),
            progress: 68
        },
        {
            id: 'RBJ-1002',
            title: 'Oak Ridge Refinance',
            amount: 310000,
            status: 'pending',
            statusLabel: 'Review',
            date: new Date('2026-04-20'),
            progress: 42
        },
        {
            id: 'RBJ-1003',
            title: 'Cedar Lane Closing',
            amount: 515000,
            status: 'completed',
            statusLabel: 'Closed',
            date: new Date('2026-04-12'),
            progress: 100
        }
    ];

    constructor(
        private authService: AuthService,
        private attendanceApi: MealAttendanceApiService,
    ) { }

    ngOnInit(): void {
        this.authService.currentUser$.subscribe(user => {
            this.currentUser = user;
        });
        this.loadAttendance();
    }

    getDisplayName(): string {
        const member = this.currentUser?.memberInfo;
        if (member) {
            return `${member.nickName ?? member.firstName_en} ${member.lastName_en}`;
        }
        return this.currentUser?.email || '';
    }

    // Per-segment label: show the count inside its colored block, but hide zeros to avoid clutter.
    segmentLabelContent = (args: { value: number }): string => {
        return args.value > 0 ? String(args.value) : '';
    };

    // Total label sitting on top of each stacked bar.
    totalLabelContent = (args: { value: number }): string => {
        return args.value > 0 ? String(args.value) : '';
    };

    private loadAttendance(): void {
        const today = new Date();
        const from = new Date();
        from.setDate(today.getDate() - 56);   // last ~8 weeks

        this.attendanceApi.getRange(this.toLocalIso(from), this.toLocalIso(today)).subscribe({
            next: rows => {
                this.attendanceDates = rows.map(r => this.toShortLabel(r.date));
                this.attendanceAdult = rows.map(r => r.adult);
                this.attendanceYouth = rows.map(r => r.youth);
                this.attendanceKid = rows.map(r => r.kid);
                this.attendanceTotal = rows.map(r => r.adult + r.youth + r.kid);
                this.hasAttendanceData = rows.length > 0;
            },
            error: () => { this.hasAttendanceData = false; },
        });
    }

    // Local yyyy-MM-dd (never toISOString — it shifts the day by timezone).
    private toLocalIso(d: Date): string {
        const month = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        return `${d.getFullYear()}-${month}-${day}`;
    }

    // 'yyyy-MM-dd' → 'M/d' for the axis label (split to avoid timezone parsing).
    private toShortLabel(isoDate: string): string {
        const [, month, day] = isoDate.split('-');
        return `${Number(month)}/${Number(day)}`;
    }
}
