import { cx } from '@/utils/cx';
import type { Campaign, Lead, HealthStatus } from '@/types/entities';

interface HealthIndicatorProps {
    campaign: Campaign;
    leads: Lead[];
}

const computeHealth = (campaign: Campaign, _leads: Lead[]): { status: HealthStatus; reason: string } => {
    if (campaign.campaignStatus === 'PAUSED') {
        return { status: 'UNHEALTHY', reason: 'Campaign is paused' };
    }

    const leadCount = campaign.leadCount ?? 0;
    const convertedCount = campaign.convertedCount ?? 0;
    const conversionRate = leadCount > 0 ? (convertedCount / leadCount) * 100 : 0;

    if (conversionRate < 5) {
        return { status: 'UNHEALTHY', reason: `Low conversion rate (${conversionRate.toFixed(1)}%)` };
    }

    if (conversionRate < 10) {
        return { status: 'WARNING', reason: `Moderate conversion rate (${conversionRate.toFixed(1)}%)` };
    }

    return { status: 'HEALTHY', reason: `Strong conversion rate (${conversionRate.toFixed(1)}%)` };
};

const statusStyles: Record<HealthStatus, { dot: string; text: string; label: string }> = {
    HEALTHY: { dot: 'bg-success-solid', text: 'text-success-primary', label: 'Healthy' },
    WARNING: { dot: 'bg-warning-solid', text: 'text-warning-primary', label: 'Warning' },
    UNHEALTHY: { dot: 'bg-error-solid', text: 'text-error-primary', label: 'Unhealthy' },
};

export const HealthIndicator = ({ campaign, leads }: HealthIndicatorProps) => {
    const { status, reason } = computeHealth(campaign, leads);
    const style = statusStyles[status];

    return (
        <div className="flex items-center gap-2">
            <span className={cx('h-2.5 w-2.5 shrink-0 rounded-full', style.dot)} />
            <p className="text-xs text-tertiary">
                <span className={cx('font-bold', style.text)}>{style.label}</span>
                {' \u2014 '}
                {reason}
            </p>
        </div>
    );
};
