import { cn } from '../../../lib/cn';
import { IconError, IconSuccess } from '../../../assets/icons/missions';
import { useNavigate } from 'react-router-dom';
import { useLocation } from 'react-router-dom';

export interface MissionItemProps {
    id: number;
    name: string;
    timeLimit?: number;
    memoryLimit?: number;
    type?: 'first' | 'second';
    status?: 'empty' | 'success' | 'error';
}

export function formatMilliseconds(ms: number): string {
    const rounded = Math.round(ms) / 1000;
    const formatted = rounded.toString().replace(/\.?0+$/, '');
    return `${formatted} c`;
}

export function formatBytesToMB(bytes: number): string {
    const megabytes = Math.floor(bytes / (1024 * 1024));
    return `${megabytes} МБ`;
}

const MissionItem: React.FC<MissionItemProps> = ({
    id,
    name,
    timeLimit = 1000,
    memoryLimit = 256 * 1024 * 1024,
    type,
    status,
}) => {
    const navigate = useNavigate();
    const location = useLocation();
    const path = location.pathname + location.search;

    return (
        <div
            className={cn(
                'min-h-[44px] w-full relative rounded-[10px] text-liquid-white',
                type == 'first' ? 'bg-liquid-lighter' : 'bg-liquid-background',
                'grid grid-cols-[80px,2fr,300px,24px] grid-flow-col gap-[20px] px-[20px] box-border items-center',
                status == 'error' &&
                    'border-l-[11px] border-l-liquid-red pl-[9px]',
                status == 'success' &&
                    'border-l-[11px] border-l-liquid-green pl-[9px]',
                'cursor-pointer brightness-100 hover:brightness-125 transition-all duration-300',
            )}
            onClick={() => {
                navigate(`/mission/${id}?back=${path}`);
            }}
        >
            <div className="text-[18px] font-bold">#{id}</div>
            <div className="text-[18px] font-bold">{name}</div>
            <div className="text-[12px] text-right">
                стандартный ввод/вывод {formatMilliseconds(timeLimit)},{' '}
                {formatBytesToMB(memoryLimit)}
            </div>
            <div className="h-[24px] w-[24px]">
                {status == 'error' && <img src={IconError} />}
                {status == 'success' && <img src={IconSuccess} />}
            </div>
        </div>
    );
};

export default MissionItem;
