Files
Alberto-Audrix 32a36cceff
CI / lint-and-test (push) Canceled after 0s
first commit
2026-07-28 08:55:05 +07:00

238 lines
7.2 KiB
TypeScript

import React from 'react';
import { LineChart, Line, ResponsiveContainer, Tooltip } from 'recharts';
import { Kpi } from '../types.ts';
import { formatNumber, formatTruncatedRatio } from '../utils/formatters.ts';
type TrendPoint = {
name: number;
value: number;
dateLabel: string;
};
const statusStyles = {
ok: {
bg: 'bg-green-100',
text: 'text-green-800',
icon: 'text-green-600',
line: '#16a34a',
},
warning: {
bg: 'bg-yellow-100',
text: 'text-yellow-800',
icon: 'text-yellow-600',
line: '#f59e0b',
},
critical: {
bg: 'bg-red-100',
text: 'text-red-800',
icon: 'text-red-600',
line: '#dc2626',
},
na: {
bg: 'bg-blue-50',
text: 'text-blue-900',
icon: 'text-blue-600',
line: '#3b82f6',
},
};
interface KpiCardProps extends Kpi {
onClick?: () => void;
isLoading?: boolean;
effectiveDate?: Date;
showDateDisclaimer?: boolean;
}
const sparklineDateFormatter = new Intl.DateTimeFormat('en-GB', {
weekday: 'short',
day: 'numeric',
month: 'short',
timeZone: 'Asia/Jakarta',
});
const formatSparklineDate = (date: Date): string =>
sparklineDateFormatter.format(date).replace(',', '');
const KpiCard: React.FC<KpiCardProps> = ({
title,
value,
unit,
icon,
trend,
trendDates,
status,
onClick,
disclaimer,
isLoading = false,
showDateDisclaimer: _showDateDisclaimer = false,
effectiveDate,
}) => {
// Map all historical points to chart format (handles variable-length arrays)
const trendData = React.useMemo(() => {
if (!trend || trend.length === 0) return [];
const hasExplicitDates = trendDates && trendDates.length === trend.length;
const fallbackStart = effectiveDate ? new Date(effectiveDate) : null;
return trend.map((value, index) => {
const labelFromData = hasExplicitDates ? trendDates?.[index] : undefined;
let dateLabel = labelFromData || '';
if (!dateLabel && fallbackStart) {
const offset = trend.length - 1 - index;
const derivedDate = new Date(fallbackStart);
derivedDate.setDate(derivedDate.getDate() - offset);
dateLabel = formatSparklineDate(derivedDate);
}
if (!dateLabel) {
dateLabel = `Point ${index + 1}`;
}
return {
name: index, // Day index (0-based for chart)
value,
dateLabel,
} satisfies TrendPoint;
});
}, [effectiveDate, trend, trendDates]);
const isNA = unit === 'N/A' || value === undefined || value === null;
// Use grey/neutral style for N/A, otherwise use the provided status
const styles = isNA ? statusStyles.na : statusStyles[status];
// Format value based on unit type
const formatValue = (val: number, unitType: string): string => {
const normalizedTitle = title.toUpperCase();
const isRatioMetric =
unitType === '' && (normalizedTitle.includes('FCR') || normalizedTitle.includes('EEF'));
if (isRatioMetric) {
// Keep ratio cards at 3 decimals, truncated instead of rounded.
return formatTruncatedRatio(val, 3);
}
if (unitType === '%') {
// For percentages, show 2-3 decimals without thousand separator
const fixed = val.toFixed(3).replace(/\.?0+$/, '');
return fixed;
}
// For weight in grams, convert to kg if > 999g
if (unitType === 'gram' && val > 999) {
return formatNumber(val / 1000, { maxDecimals: 2 });
}
// For other numbers, round to at most 2 decimals without dropping precision to integers
return formatNumber(val, { maxDecimals: 2 });
};
// Get display unit based on value and unit type
const getDisplayUnit = (val: number, unitType: string): string => {
if (unitType === 'gram' && val > 999) {
return 'kg';
}
return unitType;
};
const CustomTooltip = ({
active,
payload,
}: {
active?: boolean;
payload?: Array<{ payload: TrendPoint }>;
}) => {
if (!active || !payload || payload.length === 0) {
return null;
}
const point = payload[0]?.payload;
if (!point) {
return null;
}
return (
<div className="rounded-xl border border-white/10 bg-slate-950/90 px-3 py-2 shadow-2xl backdrop-blur-sm">
<div className="flex items-baseline gap-2">
<span className="text-sm font-semibold text-white">
{formatValue(point.value, unit)}
{!isNA && (
<span className="ml-1 text-xs font-medium text-white/70">
{getDisplayUnit(point.value, unit)}
</span>
)}
</span>
</div>
<p className="mt-0.5 text-[11px] font-medium tracking-wide text-white/65">
{point.dateLabel}
</p>
</div>
);
};
return (
<div
className={`p-4 sm:p-5 rounded-xl shadow-sm transition-all duration-300 hover:shadow-lg ${styles.bg} ${
onClick ? 'cursor-pointer hover:scale-105' : ''
} flex flex-col h-full`}
onClick={onClick}
>
<div className="flex justify-between items-start mb-2">
<div className="flex flex-col flex-1 min-w-0">
<div className={`text-2xl sm:text-3xl font-bold ${styles.text} truncate`}>
{isLoading ? (
<div className="flex items-center gap-2">
<i className="fa-solid fa-spinner fa-spin text-xl sm:text-2xl"></i>
<span className="text-base sm:text-xl">Memuat...</span>
</div>
) : (
<>
{isNA ? 'N/A' : formatValue(value, unit)}{' '}
{!isNA && (
<span className="text-lg sm:text-xl font-medium">
{getDisplayUnit(value, unit)}
</span>
)}
</>
)}
</div>
<p className={`text-xs sm:text-sm font-semibold mt-1 ${styles.text}`}>{title}</p>
{disclaimer && <p className={`text-xs mt-1 opacity-70 ${styles.text}`}>{disclaimer}</p>}
</div>
<div className={`text-2xl sm:text-3xl ${styles.icon} flex-shrink-0 ml-2`}>{icon}</div>
</div>
<div className="h-12 sm:h-14 lg:h-16 mt-auto">
{!isNA && trend && trend.length > 0 ? (
<ResponsiveContainer width="100%" height="100%">
<LineChart data={trendData} margin={{ top: 2, right: 2, bottom: 2, left: 2 }}>
<Line
type="monotone"
dataKey="value"
stroke={styles.line}
strokeWidth={2}
dot={false}
activeDot={{ r: 4, stroke: '#fff', strokeWidth: 2, fill: styles.line }}
isAnimationActive={false}
strokeLinecap="round"
/>
<Tooltip
content={<CustomTooltip />}
cursor={{
stroke: 'rgba(107, 114, 128, 0.35)',
strokeWidth: 1,
strokeDasharray: '4 4',
}}
wrapperStyle={{ outline: 'none', pointerEvents: 'none' }}
/>
</LineChart>
</ResponsiveContainer>
) : (
<div className="flex items-center justify-center h-full text-xs sm:text-sm text-gray-400">
{isNA ? 'Data tidak tersedia' : ''}
</div>
)}
</div>
</div>
);
};
export default KpiCard;