import React, { useMemo, Suspense } from 'react';
import { Loader2 } from 'lucide-react';

// Lazy load the ExcelTable to avoid hard dependency if possible, 
// though regular import is fine for dev-tools which knows about peers.
// We use the one from prafrot as the "Reference Implementation"
const ExcelTable = React.lazy(() => import('@/features/prafrot/components/ExcelTable'));

const SmartTable = ({ data, columns: userColumns, loading, ...props }) => {
  
  const generatedColumns = useMemo(() => {
    if (userColumns && userColumns.length > 0) return userColumns;
    if (!data || data.length === 0) return [];

    // Scan the first few rows to collect all possible keys (in case of optional fields)
    const keys = new Set();
    data.slice(0, 10).forEach(item => {
      Object.keys(item).forEach(k => keys.add(k));
    });

    return Array.from(keys).map(key => {
        const isDate = key.includes('date') || key.includes('created_at') || key.includes('data');
        const isMoney = key.includes('valor') || key.includes('price') || key.includes('custo') || key.includes('total');
        const isStatus = key === 'status';

        return {
            header: key.replace(/_/g, ' ').replace(/([A-Z])/g, ' $1').trim().replace(/\b\w/g, c => c.toUpperCase()),
            field: key,
            width: isDate ? 120 : (key === 'id' ? 80 : 150),
            render: (row) => {
                const val = row[key];
                if (val === null || val === undefined) return <span className="text-slate-300">-</span>;
                
                if (typeof val === 'boolean') {
                    return (
                        <span className={`px-2 py-0.5 rounded text-[10px] font-bold uppercase ${val ? 'bg-emerald-500/10 text-emerald-600' : 'bg-rose-500/10 text-rose-600'}`}>
                            {val ? 'Sim' : 'Não'}
                        </span>
                    );
                }

                if (isStatus) {
                     return (
                        <span className="px-2 py-0.5 rounded text-[10px] bg-slate-100 text-slate-600 font-bold uppercase">
                            {String(val)}
                        </span>
                    );
                }

                if (isMoney && typeof val === 'number') {
                    return val.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
                }

                if (isDate) {
                    try {
                        const d = new Date(val);
                        if (!isNaN(d.getTime())) return d.toLocaleDateString('pt-BR');
                    } catch (e) {}
                }

                if (typeof val === 'object') {
                    return <code className="text-[10px] text-slate-400 truncate max-w-[100px]">{JSON.stringify(val)}</code>;
                }

                return String(val);
            }
        };
    });
  }, [data, userColumns]);

  if (!data && !loading) {
     return <div className="p-8 text-center text-muted-foreground border border-dashed rounded-lg">Sem dados para visualizar.</div>
  }

  return (
    <Suspense fallback={
        <div className="flex items-center justify-center p-12 w-full h-[300px] bg-slate-50 border border-dashed rounded-xl">
            <Loader2 className="animate-spin text-emerald-500" />
        </div>
    }>
        <div className="h-full w-full">
            <ExcelTable 
                data={data || []}
                columns={generatedColumns}
                loading={loading}
                {...props}
            />
        </div>
    </Suspense>
  );
};

export default SmartTable;
