import { Badge } from "@/Components/ui/badge";
import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from "@/Components/ui/popover";

import { JsonTree, isEmpty } from "./jsonDisplay";
import { originStyle } from "./originStyles";

export default function EntryBadge({ origin }) {
    const label = origin?.label;
    const key = origin?.key;
    const details = origin?.details;

    const hasDetails = !isEmpty(details);

    if (!label && !key && !hasDetails) {
        return <span className="text-muted-foreground text-xs">-</span>;
    }

    const { Icon, iconClassName, displayLabel } = originStyle(origin);
    const text = displayLabel || label || key || "Origem";

    return (
        <Popover>
            <PopoverTrigger asChild>
                <button
                    type="button"
                    className="inline-flex focus:outline-none focus-visible:ring-2 focus-visible:ring-ring rounded-sm"
                    onClick={(e) => e.stopPropagation()}
                >
                    <Badge
                        variant="outline"
                        className="gap-1 px-1.5 rounded-full font-normal text-muted-foreground cursor-pointer hover:bg-muted"
                    >
                        <Icon className={`h-3 w-3 shrink-0 ${iconClassName}`} size={12} />
                        {text}
                    </Badge>
                </button>
            </PopoverTrigger>
            <PopoverContent
                align="end"
                side="bottom"
                className="w-96 max-h-[60vh] overflow-y-auto p-3 text-xs"
                onClick={(e) => e.stopPropagation()}
            >
                <div className="space-y-2">
                    <div className="space-y-0.5">
                        <p className="text-[10px] uppercase tracking-wide text-muted-foreground">
                            Entrada
                        </p>
                        <p className="font-medium text-sm break-words">
                            {label || "-"}
                        </p>
                        {key && (
                            <p className="font-mono text-[10px] text-muted-foreground break-all">
                                {key}
                            </p>
                        )}
                    </div>

                    {hasDetails && (
                        <div className="border-t pt-2">
                            <JsonTree value={details} labelCols="120px" />
                        </div>
                    )}
                </div>
            </PopoverContent>
        </Popover>
    );
}
