import React, { memo } from 'react';
import type { GeIdResult } from '../types';
import UserResultItem from './UserResultItem';

interface GeIdResultItemProps {
    result: GeIdResult;
    onErrorClick: (details: string) => void;
}

const GeIdResultItem: React.FC<GeIdResultItemProps> = ({ result, onErrorClick }) => {
    const completionDate = result.completionTime ? (result.completionTime instanceof Date ? result.completionTime : new Date(result.completionTime)) : null;
    const timeString = completionDate ? completionDate.toLocaleTimeString('vi-VN') : '-';

    // Lấy URL từ detail đầu tiên (tất cả details trong cùng GE/lang đều có cùng URL)
    const tmsUrl = result.details?.[0]?.url;

    // Format hiển thị: "1000 DE (https://tms.../project/18?l=de_DE)"
    // geIdAndLang có dạng "1000 de" hoặc "1000 US" - cần in hoa lang
    const formatGeIdAndLang = () => {
        const parts = result.geIdAndLang.split(' ');
        if (parts.length >= 2) {
            const geId = parts[0];
            const lang = parts.slice(1).join(' ').toUpperCase();
            return `${geId} ${lang}`;
        }
        return result.geIdAndLang.toUpperCase();
    };

    return (
        <div className="bg-slate-900/50 border border-slate-700 rounded-lg p-4">
            <div className="flex justify-between items-center mb-3 pb-3 border-b border-slate-700">
                <h4 className="font-mono font-semibold text-indigo-300">
                    {formatGeIdAndLang()}
                    {tmsUrl && (
                        <>
                            {' '}
                            <span className="text-slate-400">(</span>
                            <a
                                href={tmsUrl}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="text-cyan-400 hover:text-cyan-300 hover:underline transition-colors"
                                title={tmsUrl}
                            >
                                {tmsUrl}
                            </a>
                            <span className="text-slate-400">)</span>
                        </>
                    )}
                </h4>
                <span className="text-xs text-slate-400 font-mono">{timeString}</span>
            </div>
            <div className="space-y-2">
                {(result.details || []).map((detail, index) => (
                    <UserResultItem key={index} detail={detail} onErrorClick={onErrorClick} />
                ))}
            </div>
        </div>
    );
};

export default memo(GeIdResultItem);