import { RiBankCard2Line } from "@remixicon/react";
import Image from "next/image";
import MoneyValues from "@/components/money-values";
import { CardContent } from "@/components/ui/card";
import { WidgetEmptyState } from "@/components/widget-empty-state";
import type { PagadorCardUsageItem } from "@/lib/pagadores/details";

const resolveLogoPath = (logo?: string | null) => {
	if (!logo) return null;
	if (
		logo.startsWith("http://") ||
		logo.startsWith("https://") ||
		logo.startsWith("data:")
	) {
		return logo;
	}
	return logo.startsWith("/") ? logo : `/logos/${logo}`;
};

const buildInitials = (value: string) => {
	const parts = value.trim().split(/\s+/).filter(Boolean);
	if (parts.length === 0) return "CC";
	if (parts.length === 1) {
		const firstPart = parts[0];
		return firstPart ? firstPart.slice(0, 2).toUpperCase() : "CC";
	}
	const firstChar = parts[0]?.[0] ?? "";
	const secondChar = parts[1]?.[0] ?? "";
	return `${firstChar}${secondChar}`.toUpperCase() || "CC";
};

type PagadorCardUsageCardProps = {
	items: PagadorCardUsageItem[];
};

export function PagadorCardUsageCard({ items }: PagadorCardUsageCardProps) {
	if (items.length === 0) {
		return (
			<CardContent className="px-0">
				<WidgetEmptyState
					icon={<RiBankCard2Line className="size-6 text-muted-foreground" />}
					title="Nenhum lançamento com cartão de crédito"
					description="Quando houver despesas registradas com cartão, elas aparecerão aqui."
				/>
			</CardContent>
		);
	}

	return (
		<CardContent className="flex flex-col gap-4 px-0">
			<ul className="flex flex-col">
				{items.map((item) => {
					const logoPath = resolveLogoPath(item.logo);
					const initials = buildInitials(item.name);
					return (
						<li
							key={item.id}
							className="flex items-center justify-between border-b border-dashed last:border-b-0 last:pb-0"
						>
							<div className="flex min-w-0 flex-1 items-center gap-2 py-2">
								<div className="flex size-9 shrink-0 items-center justify-center overflow-hidden rounded-full">
									{logoPath ? (
										<Image
											src={logoPath}
											alt={`Logo do cartão ${item.name}`}
											width={36}
											height={36}
											className="h-full w-full object-contain"
										/>
									) : (
										<span className="text-sm font-semibold uppercase text-muted-foreground">
											{initials}
										</span>
									)}
								</div>
								<div className="min-w-0">
									<span className="block truncate text-sm font-medium text-foreground">
										{item.name}
									</span>
									<span className="text-xs text-muted-foreground">
										Despesas no mês
									</span>
								</div>
							</div>
							<MoneyValues amount={item.amount} />
						</li>
					);
				})}
			</ul>
		</CardContent>
	);
}
