
import React, { useRef } from 'react';
import { useDisplayMode } from '@/context/DisplayModeContext';
import { Plus, GripVertical, FilePlus, Package, PenLine, Trash2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import ArticleSearchInput from '../molecules/ArticleAutocomplete';

// Helper for currency formatting
const formatCurrency = (amount) => {
    if (amount === undefined || amount === null) return '0,00 €';
    return new Intl.NumberFormat('fr-FR', { style: 'currency', currency: 'EUR' }).format(amount);
};

const DocumentLinesTable = ({ 
    lines, 
    onChangeLine, 
    onRemoveLine, 
    onAddLine, 
    onAddManualLine,
    onArticleSelect,
    onCreateArticle,
    readOnly = false 
}) => {
    const { displayMode } = useDisplayMode();
    const isCompact = displayMode === 'compact';

    const toggleMode = (line) => {
        const isCurrentlyManual = line.type === 'manual' || (!line.code && !line.type); 
        const newType = isCurrentlyManual ? 'article' : 'manual';
        onChangeLine(line.id, 'type', newType);
        if (newType === 'manual') onChangeLine(line.id, 'code', '');
    };

    return (
        <TooltipProvider>
            <div className="flex flex-col h-full w-full">
                {/* Table Header - Sticky */}
                <div className="sticky top-0 z-20 bg-[#F9FAFB] dark:bg-gray-900 border-b border-gray-200 dark:border-gray-800">
                     <div className="flex items-center px-4 py-3 text-xs font-bold text-gray-500 uppercase tracking-wider">
                        {!readOnly && <div className="w-8"></div>} {/* Grip */}
                        <div className="w-10"></div> {/* Mode Toggle */}
                        <div className="w-[220px]">Désignation</div>
                        <div className="flex-1 min-w-[200px] pl-4">Description détaillée</div>
                        <div className="w-20 text-right">Qté</div>
                        <div className="w-28 text-right">P.U. HT</div>
                        <div className="w-20 text-right">Rem. %</div>
                        <div className="w-24 text-right">TVA</div>
                        <div className="w-28 text-right">Total HT</div>
                        <div className="w-10"></div> {/* Actions */}
                     </div>
                </div>

                {/* Table Body */}
                <div className="flex-1 divide-y divide-gray-100 dark:divide-gray-800 bg-white dark:bg-gray-950">
                    {lines.map((line, index) => {
                        const isManual = line.type === 'manual' || (!line.code && line.type === 'manual'); 
                        
                        return (
                            <div 
                                key={line.id} 
                                className={cn(
                                    "flex items-start px-4 py-3 group transition-colors",
                                    isManual ? "bg-gray-50/50 dark:bg-gray-900/20" : "hover:bg-gray-50 dark:hover:bg-gray-900/50",
                                    "focus-within:bg-green-50/30 dark:focus-within:bg-green-900/10 focus-within:ring-1 focus-within:ring-inset focus-within:ring-[#2A6F4F]/20"
                                )}
                            >
                                {/* Drag Handle */}
                                {!readOnly && (
                                    <div className="w-8 pt-2 text-gray-300 cursor-move opacity-0 group-hover:opacity-100 transition-opacity">
                                        <GripVertical className="w-4 h-4" />
                                    </div>
                                )}

                                {/* Mode Toggle */}
                                {!readOnly && (
                                    <div className="w-10 pt-1.5 mr-2">
                                        <Tooltip>
                                            <TooltipTrigger asChild>
                                                <button 
                                                    onClick={() => toggleMode(line)}
                                                    className={cn(
                                                        "p-1.5 rounded-md transition-all duration-200",
                                                        isManual 
                                                            ? "text-gray-400 hover:text-gray-600 hover:bg-gray-200" 
                                                            : "text-[#2A6F4F] bg-green-50 hover:bg-green-100"
                                                    )}
                                                >
                                                    {isManual ? <PenLine className="w-4 h-4" /> : <Package className="w-4 h-4" />}
                                                </button>
                                            </TooltipTrigger>
                                            <TooltipContent side="right">
                                                <p>Mode: {isManual ? 'Libre' : 'Article'}</p>
                                            </TooltipContent>
                                        </Tooltip>
                                    </div>
                                )}

                                {/* Designation (Article or Manual Title) */}
                                <div className="w-[220px]">
                                    {readOnly ? (
                                        <div className="py-1 font-medium text-gray-900 dark:text-white truncate">
                                            {line.designation || line.code || '—'}
                                        </div>
                                    ) : (
                                        isManual ? (
                                            <input
                                                type="text"
                                                value={line.designation || ''}
                                                onChange={(e) => onChangeLine(line.id, 'designation', e.target.value)}
                                                className="w-full bg-transparent border-b border-transparent focus:border-[#2A6F4F] focus:ring-0 p-0 py-1 text-sm font-medium"
                                                placeholder="Titre..."
                                            />
                                        ) : (
                                            <ArticleSearchInput 
                                                value={line.designation} 
                                                onChange={(val) => onChangeLine(line.id, 'designation', val)}
                                                onArticleSelect={(article) => onArticleSelect(line.id, article)}
                                                onCreateArticle={onCreateArticle}
                                                placeholder="Rechercher article..."
                                            />
                                        )
                                    )}
                                </div>

                                {/* Description (Textarea) */}
                                <div className="flex-1 min-w-[200px] px-4">
                                    {readOnly ? (
                                        <div className="py-1 text-sm text-gray-600 dark:text-gray-400 whitespace-pre-wrap">
                                            {line.description}
                                        </div>
                                    ) : (
                                        <textarea
                                            value={line.description || ''}
                                            onChange={(e) => onChangeLine(line.id, 'description', e.target.value)}
                                            className="w-full bg-transparent border-none p-0 text-sm text-gray-600 dark:text-gray-400 placeholder:text-gray-300 focus:ring-0 resize-none overflow-hidden"
                                            placeholder="Description détaillée (visible sur PDF)..."
                                            rows={Math.max(1, (line.description?.match(/\n/g) || []).length + 1)}
                                            style={{ fieldSizing: 'content' }}
                                        />
                                    )}
                                </div>

                                {/* Quantity */}
                                <div className="w-20 px-2">
                                    {!readOnly ? (
                                        <input 
                                            type="number" 
                                            value={line.quantity} 
                                            onChange={(e) => onChangeLine(line.id, 'quantity', e.target.value)}
                                            className="w-full text-right bg-transparent border-b border-transparent focus:border-[#2A6F4F] focus:ring-0 p-0 py-1 font-mono text-sm"
                                            min="0"
                                        />
                                    ) : (
                                        <div className="text-right font-mono text-sm py-1">{line.quantity}</div>
                                    )}
                                </div>

                                {/* Unit Price */}
                                <div className="w-28 px-2">
                                    {!readOnly ? (
                                        <input 
                                            type="number" 
                                            value={line.unitPrice} 
                                            onChange={(e) => onChangeLine(line.id, 'unitPrice', e.target.value)}
                                            className="w-full text-right bg-transparent border-b border-transparent focus:border-[#2A6F4F] focus:ring-0 p-0 py-1 font-mono text-sm"
                                            step="0.01"
                                        />
                                    ) : (
                                        <div className="text-right font-mono text-sm py-1">{formatCurrency(line.unitPrice)}</div>
                                    )}
                                </div>

                                {/* Discount % */}
                                <div className="w-20 px-2">
                                    {!readOnly ? (
                                        <div className="relative">
                                            <input 
                                                type="number" 
                                                value={line.discount} 
                                                onChange={(e) => onChangeLine(line.id, 'discount', e.target.value)}
                                                className="w-full text-right bg-transparent border-b border-transparent focus:border-[#2A6F4F] focus:ring-0 p-0 py-1 font-mono text-sm text-gray-500 focus:text-gray-900 pr-3"
                                                placeholder="0"
                                                min="0"
                                                max="100"
                                            />
                                            <span className="absolute right-0 top-1 text-xs text-gray-400">%</span>
                                        </div>
                                    ) : (
                                        <div className="text-right font-mono text-sm py-1 text-gray-500">{line.discount > 0 ? `${line.discount}%` : '-'}</div>
                                    )}
                                </div>

                                {/* Tax - MULTI RATE VAT IMPLEMENTATION */}
                                <div className="w-24 px-2">
                                    {!readOnly ? (
                                        <div className="relative">
                                            <select
                                                value={line.vat}
                                                onChange={(e) => onChangeLine(line.id, 'vat', parseFloat(e.target.value))}
                                                className="w-full text-right bg-transparent border-b border-transparent focus:border-[#2A6F4F] focus:ring-0 p-0 py-1 font-mono text-sm appearance-none pr-4 cursor-pointer"
                                            >
                                                <option value={0}>0 %</option>
                                                <option value={2.1}>2.1 %</option>
                                                <option value={5.5}>5.5 %</option>
                                                <option value={10}>10 %</option>
                                                <option value={20}>20 %</option>
                                            </select>
                                            <span className="absolute right-0 top-1.5 text-[10px] text-gray-400 pointer-events-none">▼</span>
                                        </div>
                                    ) : (
                                        <div className="text-right font-mono text-sm py-1 text-gray-500">{line.vat}%</div>
                                    )}
                                </div>

                                {/* Total */}
                                <div className="w-28 px-2 text-right py-1 font-mono font-bold text-sm text-gray-900 dark:text-white">
                                    {formatCurrency(line.totalHT)}
                                </div>

                                {/* Actions */}
                                {!readOnly && (
                                    <div className="w-10 flex justify-end opacity-0 group-hover:opacity-100 transition-opacity">
                                        <button 
                                            onClick={() => onRemoveLine(line.id)}
                                            className="p-1.5 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded transition-colors"
                                        >
                                            <Trash2 className="w-4 h-4" />
                                        </button>
                                    </div>
                                )}
                            </div>
                        );
                    })}
                </div>
                
                {/* Manual Add Actions - hidden if we rely on auto-add, but kept for explicit actions */}
                {!readOnly && (
                    <div className="p-4 border-t border-gray-100 dark:border-gray-800 bg-gray-50/30 opacity-60 hover:opacity-100 transition-opacity">
                        <div className="flex gap-3">
                            <button 
                                onClick={onAddLine}
                                className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-[#2A6F4F] bg-white border border-[#2A6F4F] rounded-lg hover:bg-green-50 transition-all shadow-sm"
                            >
                                <Plus className="w-4 h-4" /> Ajouter une ligne
                            </button>
                        </div>
                    </div>
                )}
            </div>
        </TooltipProvider>
    );
};

export default DocumentLinesTable;
