import { Info } from "lucide-react";
import { TraceabilityNode } from "./TreeView";

interface TraceabilitySummaryProps {
    data: TraceabilityNode;
    direction: 'forward' | 'backward';
}

export function TraceabilitySummary({ data, direction }: TraceabilitySummaryProps) {
    if (!data) return null;

    // --- Helper to extract unqiue names/codes from children ---
    const getUniqueLabels = (nodes: TraceabilityNode[], prefixToStrip: string = '') => {
        const labels = nodes
            .map(n => n.label.replace(prefixToStrip, '').trim())
            .filter(Boolean);
        return Array.from(new Set(labels));
    };

    // --- Logic for Backward Tracing ---
    if (direction === 'backward') {
        const poNodes = data.children?.filter(c => c.type === 'production_order') || [];
        const poNames = getUniqueLabels(poNodes, '生產工單:');

        let materialNodes: TraceabilityNode[] = [];
        let grNodes: TraceabilityNode[] = [];

        poNodes.forEach(po => {
            const materials = po.children?.filter(c => c.type === 'material_batch') || [];
            materialNodes = [...materialNodes, ...materials];

            materials.forEach(mat => {
                const grs = mat.children?.filter(c => c.type === 'goods_receipt') || [];
                grNodes = [...grNodes, ...grs];
            });
        });

        const materialNames = getUniqueLabels(materialNodes, '原料批號:');
        const grNames = getUniqueLabels(grNodes, '進貨單:');

        // Handle case where batch is directly from Goods Receipt (no PO)
        const directGrNodes = data.children?.filter(c => c.type === 'goods_receipt') || [];
        if (directGrNodes.length > 0) {
            grNodes = [...grNodes, ...directGrNodes];
            const directGrNames = getUniqueLabels(directGrNodes, '進貨單:');

            return (
                <div className="bg-blue-50/50 border border-blue-100 rounded-xl p-4 mb-6 flex gap-3 text-gray-700 leading-relaxed shadow-sm">
                    <Info className="w-5 h-5 text-blue-500 shrink-0 mt-0.5" />
                    <div>
                        <p>
                            查詢的批號 <strong className="text-gray-900">{data.batch_number}</strong>
                            {data.product_name && <span> ({data.product_name})</span>}
                            主要是由進貨單 {directGrNames.map(n => <strong key={n} className="text-gray-900 mx-1">{n}</strong>).reduce((prev, curr) => [prev, '、', curr] as any)} 採購進貨。
                        </p>
                    </div>
                </div>
            );
        }

        return (
            <div className="bg-blue-50/50 border border-blue-100 rounded-xl p-4 mb-6 flex gap-3 text-gray-700 leading-relaxed shadow-sm">
                <Info className="w-5 h-5 text-blue-500 shrink-0 mt-0.5" />
                <div className="space-y-1.5">
                    <p>
                        查詢的成品批號 <strong className="text-gray-900">{data.batch_number}</strong>
                        {data.product_name && <span> ({data.product_name})</span>} 是由
                        {poNames.length > 0 ? (
                            <>
                                生產工單 {poNames.slice(0, 3).map(n => <strong key={n} className="text-gray-900 mx-1">{n}</strong>).reduce((prev, curr) => [prev, '、', curr] as any)}
                                {poNames.length > 3 && ` 等 ${poNames.length} 張工單`} 產出。
                            </>
                        ) : (
                            '未知的生產工單產出。'
                        )}
                    </p>
                    {materialNodes.length > 0 && (
                        <p>
                            這些工單總共使用了 <strong className="text-gray-900">{materialNodes.length}</strong> 批原料
                            （包含原料批號 {materialNames.slice(0, 3).map(n => <strong key={n} className="text-gray-900 mx-1">{n}</strong>).reduce((prev, curr) => [prev, '、', curr] as any)}
                            {materialNames.length > 3 && ' 等'}）。
                        </p>
                    )}
                    {grNodes.length > 0 && (
                        <p>
                            而這些原料主要來自於進貨單 {grNames.slice(0, 3).map(n => <strong key={n} className="text-gray-900 mx-1">{n}</strong>).reduce((prev, curr) => [prev, '、', curr] as any)}
                            {grNames.length > 3 && ` 等 ${grNames.length} 張單據`}。
                        </p>
                    )}
                </div>
            </div>
        );
    }

    // --- Logic for Forward Tracing ---
    if (direction === 'forward') {
        const poNodes = data.children?.filter(c => c.type === 'production_order') || [];
        const poNames = getUniqueLabels(poNodes, '投入工單:');

        let targetNodes: TraceabilityNode[] = [];
        let outNodes: TraceabilityNode[] = [];

        poNodes.forEach(po => {
            const targets = po.children?.filter(c => c.type === 'target_batch') || [];
            targetNodes = [...targetNodes, ...targets];

            targets.forEach(tgt => {
                const outs = tgt.children?.filter(c => c.type === 'outbound_transaction') || [];
                outNodes = [...outNodes, ...outs];
            });
        });

        const targetNames = getUniqueLabels(targetNodes, '產出成品:');
        const outNames = getUniqueLabels(outNodes, '出庫單據:');

        return (
            <div className="bg-blue-50/50 border border-blue-100 rounded-xl p-4 mb-6 flex gap-3 text-gray-700 leading-relaxed shadow-sm">
                <Info className="w-5 h-5 text-blue-500 shrink-0 mt-0.5" />
                <div className="space-y-1.5">
                    <p>
                        查詢的原料批號 <strong className="text-gray-900">{data.batch_number}</strong>
                        {data.product_name && <span> ({data.product_name})</span>} 被投入了
                        {poNames.length > 0 ? (
                            <>
                                生產工單 {poNames.slice(0, 3).map(n => <strong key={n} className="text-gray-900 mx-1">{n}</strong>).reduce((prev, curr) => [prev, '、', curr] as any)}
                                {poNames.length > 3 && ` 等 ${poNames.length} 張工單`}。
                            </>
                        ) : (
                            ' 未知的生產工單。'
                        )}
                    </p>
                    {targetNodes.length > 0 && (
                        <p>
                            這些工單隨後產出了成品批號 {targetNames.slice(0, 3).map(n => <strong key={n} className="text-gray-900 mx-1">{n}</strong>).reduce((prev, curr) => [prev, '、', curr] as any)}
                            {targetNames.length > 3 && ` 等 ${targetNodes.length} 批成品`}。
                        </p>
                    )}
                    {outNodes.length > 0 && (
                        <p>
                            最終，這些成品透過 {outNames.slice(0, 3).map(n => <strong key={n} className="text-gray-900 mx-1">{n}</strong>).reduce((prev, curr) => [prev, '、', curr] as any)}
                            {outNames.length > 3 && ` 等 ${outNodes.length} 張單據`} 離開了倉庫。
                        </p>
                    )}
                </div>
            </div>
        );
    }

    return null;
}
