import { useMemo } from 'react';

import {
    Tooltip,
    TooltipContent,
    TooltipTrigger,
} from '@/components/ui/tooltip';
import { cn } from '@/lib/utils';

type ShortViewTextProps = {
    text: string | null | undefined;
    className?: string;
    maxLength?: number;
    type?: "tail" | "middle" | "head";
    truncateByWidth?: boolean;
}


const ShortViewText = ({ text, className, maxLength = 15, type = "tail", truncateByWidth }: ShortViewTextProps) => {

    const shortText = useMemo(() => {
        if (!text) return null;
        if (truncateByWidth) return text;
        if (text.length < maxLength) return text;

        if (type == "tail") {
            return text.slice(0, maxLength) + '...';
        }

        if (type == "middle") {
            return text.slice(0, maxLength / 2) + '...' + text.slice(-maxLength / 2);
        }

        if (type == "head") {
            return '...' + text.slice(-maxLength);
        }

    }, [text, truncateByWidth, maxLength, type]);

    if (!shortText) return null;

    return <Tooltip>
        <TooltipTrigger asChild>
            <span
                className={cn(truncateByWidth && 'block min-w-0 truncate', className)}
            >{shortText}</span>
        </TooltipTrigger>
        <TooltipContent>
            <p className='max-w-[300px] break-all whitespace-pre-wrap'>{text}</p>
        </TooltipContent>
    </Tooltip>
}

export default ShortViewText;