import { RecoveryTracker } from './RecoveryTracker';

export class NicotineTracker extends RecoveryTracker {
    calculateMinutesFree(precise: boolean = false): number {
        // 1. Try to use precise timestamp from preferences first
        if (this.preferences?.lastNicotineUsageTime) {
            const now = new Date();
            const lastUsageTime = new Date(this.preferences.lastNicotineUsageTime);
            console.log('[NicotineTracker] Found timestamp:', this.preferences.lastNicotineUsageTime);

            const diffMs = now.getTime() - lastUsageTime.getTime();
            const minutes = this.msToMinutes(diffMs, precise);

            // Validation: Ensure the timestamp aligns with the last recorded usage date.
            // If the user manually edited usage for a LATER date, the timestamp might be stale.
            const lastRecordedDateStr = this.getLastRecordedDate();
            console.log('[NicotineTracker] Last recorded date:', lastRecordedDateStr);

            if (lastRecordedDateStr) {
                const lastRecordedDate = new Date(lastRecordedDateStr);
                lastRecordedDate.setHours(0, 0, 0, 0);

                // If the timestamp is older than the start of the last recorded day, 
                // it means we have a newer manual entry without a timestamp.
                // In this case, fall back to date-based logic.
                if (lastUsageTime < lastRecordedDate) {
                    console.log('[NicotineTracker] Timestamp is stale, falling back to date logic');
                    return this.calculateDateBasedMinutes(lastRecordedDateStr, precise);
                }
            }

            return minutes;
        }

        // 2. Fallback to date-based logic if no timestamp exists
        const lastDateStr = this.getLastRecordedDate();

        // 3. If no nicotine usage ever recorded, use tracking start date
        if (!lastDateStr) {
            if (this.preferences?.trackingStartDate) {
                const startDate = new Date(this.preferences.trackingStartDate);
                startDate.setHours(0, 0, 0, 0); // Count from start of tracking day
                const now = new Date();
                const diffMs = now.getTime() - startDate.getTime();
                return this.msToMinutes(diffMs, precise);
            }
            return 0; // No usage and no tracking start date
        }

        return this.calculateDateBasedMinutes(lastDateStr, precise);
    }

    private getLastRecordedDate(): string | null {
        const nicotineData = this.usageData
            .filter((e) => e.substance === 'nicotine' && e.count > 0)
            .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());

        return nicotineData.length > 0 ? nicotineData[0].date : null;
    }

    private calculateDateBasedMinutes(dateStr: string, precise: boolean): number {
        const now = new Date();
        const todayStr = now.toISOString().split('T')[0];

        // If the last usage was today but we have no timestamp, reset to 0
        if (dateStr === todayStr) {
            return 0;
        }

        // For past days, count from the END of that day (23:59:59)
        const lastUsageDate = new Date(dateStr);
        lastUsageDate.setHours(23, 59, 59, 999);

        const diffMs = now.getTime() - lastUsageDate.getTime();
        return this.msToMinutes(diffMs, precise);
    }
}
