import { ProductMetric, ProductStatus } from "@/types/products";

//Calculates the product status based on various metrics

export function getProductStatus(product: ProductMetric): ProductStatus {
    if (!product.isReplenishable) {
        return "Healthy"; // Non-replenishable items default to Healthy
    }

    const {
        currentStock,
        stockCoverInDays,
        sellsOutInDays,
        overstockedUnits,
        configLeadTime,
        avgLeadTimeDays,
        dateLastSold,
        ageDays,
        isOldStock
    } = product;

    const leadTime = configLeadTime ?? avgLeadTimeDays ?? 30; // Default lead time if none configured
    const safetyThresholdDays = leadTime * 0.5; // Safety threshold is 50% of lead time

    // Check for overstock first
    if (overstockedUnits != null && overstockedUnits > 0) {
        return "Overstock";
    }

    // Check for critical stock
    if (stockCoverInDays != null) {
        // Stock is <= 0 or very low compared to lead time
        if (currentStock <= 0 || stockCoverInDays <= 0) {
            return "Critical";
        }
        if (stockCoverInDays < safetyThresholdDays) {
            return "Critical";
        }
    }

    // Check for products that will need reordering soon
    if (sellsOutInDays != null && sellsOutInDays < (leadTime + 7)) { // Within lead time + 1 week
        // If also critically low, keep Critical status
        if (stockCoverInDays != null && stockCoverInDays < safetyThresholdDays) {
            return "Critical";
        }
        return "Reorder Soon";
    }

    // Check for 'At Risk' - e.g., old stock or hasn't sold in a long time
    const ninetyDaysAgo = new Date();
    ninetyDaysAgo.setDate(ninetyDaysAgo.getDate() - 90);
    
    if (isOldStock) {
        return "At Risk";
    }
    
    if (dateLastSold && new Date(dateLastSold) < ninetyDaysAgo && (ageDays ?? 0) > 180) {
        return "At Risk";
    }
    
    // Very high stock cover (more than a year) is at risk too
    if (stockCoverInDays != null && stockCoverInDays > 365) {
        return "At Risk";
    }

    // If none of the above, assume Healthy
    return "Healthy";
}

//Returns a Badge component HTML string for a given product status
export function getStatusBadge(status: ProductStatus): string {
    switch (status) {
        case 'Critical':
            return '<div class="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 border-transparent bg-red-600 text-white">Critical</div>';
        case 'Reorder Soon':
            return '<div class="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 border-secondary bg-yellow-500 text-black">Reorder Soon</div>';
        case 'Healthy':
            return '<div class="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 border-transparent bg-green-600 text-white">Healthy</div>';
        case 'Overstock':
            return '<div class="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 border-secondary bg-blue-600 text-white">Overstock</div>';
        case 'At Risk':
            return '<div class="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 border-orange-500 text-orange-600">At Risk</div>';
        case 'New':
            return '<div class="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 border-transparent bg-purple-600 text-white">New</div>';
        default:
            return '<div class="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2">Unknown</div>';
    }
}

//Formatting utilities for displaying metrics
export const formatCurrency = (value: number | null | undefined, digits = 2): string => {
    if (value == null) return 'N/A';
    return new Intl.NumberFormat('en-US', { 
        style: 'currency', 
        currency: 'USD', 
        minimumFractionDigits: digits, 
        maximumFractionDigits: digits 
    }).format(value);
};

export const formatNumber = (value: number | null | undefined, digits = 0): string => {
    if (value == null) return 'N/A';
    return value.toLocaleString(undefined, { 
        minimumFractionDigits: digits, 
        maximumFractionDigits: digits 
    });
};

export const formatPercentage = (value: number | null | undefined, digits = 1): string => {
    if (value == null) return 'N/A';
    return `${value.toFixed(digits)}%`;
};

export const formatDays = (value: number | null | undefined, digits = 0): string => {
    if (value == null) return 'N/A';
    return `${value.toFixed(digits)} days`;
};

export const formatDate = (dateString: string | null | undefined): string => {
    if (!dateString) return 'N/A';
    try {
        return new Date(dateString).toLocaleDateString('en-US', { 
            year: 'numeric', 
            month: 'short', 
            day: 'numeric' 
        });
    } catch (e) {
        return 'Invalid Date';
    }
};

export const formatBoolean = (value: boolean | null | undefined): string => {
    if (value == null) return 'N/A';
    return value ? 'Yes' : 'No';
}; 