import { Grid, type GridSize, Typography } from "@mui/material";
import { getLocalizedString } from "@olenbetong/appframe-core";
import { Link } from "@olenbetong/appframe-mui";
import type { DamagesRecord } from "../../data";

type SummaryItemProps = {
	col: GridSize;
	label?: string;
	children?: React.ReactNode;
	em?: boolean;
	align?: "center" | "left" | "right";
	padding?: string | number;
};

function SummaryItem({ col, label, children, em, align, padding }: SummaryItemProps) {
	return (
		<Grid size={col} sx={{ p: padding ?? 2, borderBottom: (t) => `1px solid ${t.palette.divider}` }}>
			{label && (
				<Typography variant="body1" sx={{ fontSize: "0.9rem", fontWeight: 500, mb: 1, textAlign: align }}>
					{getLocalizedString(label)}
				</Typography>
			)}
			{children && (
				<Typography
					sx={{
						fontSize: em ? "1.4rem" : "0.9rem",
						fontWeight: em ? 600 : undefined,
						textAlign: align,
						whiteSpace: "pre-line",
					}}
				>
					{children}
				</Typography>
			)}
		</Grid>
	);
}

type ElementDamagesItemProps = {
	record: DamagesRecord;
	linkToDamage: boolean;
};

export function ElementDamagesItem({ record, linkToDamage }: ElementDamagesItemProps) {
	return (
		<>
			<SummaryItem col={1.5}>
				{linkToDamage ? (
					<Link
						href="#"
						onClick={(e) => {
							e.preventDefault();
							window.location.href = `${record.ID}`;
						}}
					>
						{record.ID}
					</Link>
				) : (
					<span>{record.ID}</span>
				)}
			</SummaryItem>
			<SummaryItem col={2.5} align="right">
				{record.Date.toISOString().split("T")[0]}
			</SummaryItem>
			<SummaryItem col={3}>{record.Description}</SummaryItem>
			<SummaryItem col={2.5}>{record.Cause}</SummaryItem>
			<SummaryItem col={2.5}>{record.Action}</SummaryItem>
		</>
	);
}

export function ElementDamagesHeader() {
	return (
		<>
			<SummaryItem col={1.5} label="ID" />
			<SummaryItem col={2.5} label="Date" align="right" />
			<SummaryItem col={3} label="Description" />
			<SummaryItem col={2.5} label="Cause" />
			<SummaryItem col={2.5} label="Action" />
		</>
	);
}
