"use client";

import { useSafeIntl } from "@kopexa/i18n";
import { Tooltip } from "@kopexa/sight";
import { riskRating } from "@kopexa/theme";
import { messages } from "./messages";
import {
	getRiskLevelFromRating,
	isRatingUnrated,
	type RiskLevel,
	type RiskRating,
} from "./types";

export interface RiskRatingDisplayProps {
	/** The risk rating to display */
	rating: RiskRating | null | undefined;
	/** Show the rating value badge */
	showBadge?: boolean;
	/** Show the level label text */
	showLabel?: boolean;
	/** Size variant */
	size?: "sm" | "md";
}

/**
 * Display component for risk ratings.
 * Shows a colored badge with the rating value and level label.
 * Handles "not rated" state gracefully.
 */
export function RiskRatingDisplay({
	rating,
	showBadge = true,
	showLabel = true,
	size = "md",
}: RiskRatingDisplayProps) {
	const intl = useSafeIntl();

	// Handle unrated state
	if (isRatingUnrated(rating)) {
		const styles = riskRating({ size, level: "unrated" });
		const levelLabel = intl.formatMessage(messages.level_unrated);

		return (
			<Tooltip content={intl.formatMessage(messages.not_rated_hint)}>
				<div className={styles.base()}>
					{showBadge && <div className={styles.badge()}>—</div>}
					{showLabel && <span className={styles.label()}>{levelLabel}</span>}
				</div>
			</Tooltip>
		);
	}

	// At this point, rating is guaranteed to be non-null with valid values
	const ratedValue = rating as RiskRating;
	const level = getRiskLevelFromRating(ratedValue.rating);
	const styles = riskRating({
		size,
		level: level as Exclude<RiskLevel, "unrated">,
	});
	const levelLabelKey = `level_${level}` as keyof typeof messages;
	const levelLabel = intl.formatMessage(messages[levelLabelKey]);

	return (
		<Tooltip
			content={
				<div className="text-xs space-y-1">
					<div>
						{intl.formatMessage(messages.likelihood)}: {ratedValue.likelihood}/5
					</div>
					<div>
						{intl.formatMessage(messages.consequence)}: {ratedValue.consequence}
						/5
					</div>
					{ratedValue.comment && (
						<div className="text-muted-foreground">{ratedValue.comment}</div>
					)}
				</div>
			}
		>
			<div className={styles.base()}>
				{showBadge && <div className={styles.badge()}>{ratedValue.rating}</div>}
				{showLabel && <span className={styles.label()}>{levelLabel}</span>}
			</div>
		</Tooltip>
	);
}
