import { useEffect, useState } from 'react';
import { Package, Sprout, Flower2, Loader2 } from 'lucide-react';
import { batchesApi, Batch } from '../../../lib/batchesApi';

export function PlantInventory() {
    const [batches, setBatches] = useState<Batch[]>([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        loadBatches();
    }, []);

    const loadBatches = async () => {
        try {
            const data = await batchesApi.getAll();
            // Filter active batches
            const active = data.filter(b => b.status !== 'COMPLETED' && b.status !== 'HARVESTED' && b.status !== 'DESTROYED');
            setBatches(active);
        } catch (e) {
            console.error("Failed to load batches", e);
        } finally {
            setLoading(false);
        }
    };

    const handleDragStart = (e: React.DragEvent, batch: Batch) => {
        // Set drag data
        e.dataTransfer.setData('application/json', JSON.stringify({
            type: 'BATCH',
            id: batch.id,
            name: batch.name,
            strain: batch.strain,
            color: getStageColorHex(batch.stage || 'VEGETATIVE')
        }));
        e.dataTransfer.effectAllowed = 'copy';
    };

    if (loading) {
        return (
            <div className="flex items-center justify-center p-8 text-[var(--color-text-tertiary)]">
                <Loader2 className="animate-spin" size={20} />
            </div>
        );
    }

    return (
        <div className="flex-1 overflow-auto">
            <div className="p-3 border-b border-white/10">
                <h3 className="text-xs font-semibold text-[var(--color-text-tertiary)] uppercase tracking-wider">
                    Inventory (Batches)
                </h3>
            </div>
            <div className="p-2 space-y-2">
                {batches.length === 0 ? (
                    <div className="text-center p-4 text-xs text-[var(--color-text-tertiary)]">
                        No active batches found.
                    </div>
                ) : (
                    batches.map(batch => (
                        <div
                            key={batch.id}
                            draggable
                            onDragStart={(e) => handleDragStart(e, batch)}
                            className="bg-slate-800/80 p-3 rounded-lg border border-slate-700 hover:border-emerald-500/50 hover:bg-slate-800 cursor-grab active:cursor-grabbing group transition-all shadow-sm"
                        >
                            <div className="flex items-start justify-between mb-2">
                                <div className="font-medium text-sm text-slate-200 group-hover:text-emerald-400 transition-colors">
                                    {batch.name}
                                </div>
                                <span className={`text-[10px] px-1.5 py-0.5 rounded font-medium border ${getStageBadgeStyle(batch.stage)}`}>
                                    {batch.stage?.split('_')[0] || 'UNK'}
                                </span>
                            </div>

                            <div className="flex items-center gap-2 text-xs text-[var(--color-text-tertiary)] mb-1">
                                <Sprout size={12} className="text-[var(--color-primary)]/70" />
                                <span className="font-medium text-slate-300">{batch.strain}</span>
                            </div>

                            <div className="flex items-center justify-between text-[10px] text-[var(--color-text-tertiary)] mt-2 pt-2 border-t border-white/5">
                                <div className="flex items-center gap-1">
                                    <Package size={10} />
                                    <span>{batch.plantCount} plants</span>
                                </div>
                                <div>
                                    {new Date(batch.startDate).toLocaleDateString()}
                                </div>
                            </div>
                        </div>
                    ))
                )}
            </div>
        </div>
    );
}

function getStageBadgeStyle(stage?: string) {
    if (!stage) return 'bg-slate-500/10 text-[var(--color-text-tertiary)] border-slate-500/20';
    if (stage.includes('VEG')) return 'bg-[var(--color-primary)]/10 text-emerald-400 border-emerald-500/20';
    if (stage.includes('FLOWER')) return 'bg-purple-500/10 text-purple-400 border-purple-500/20';
    if (stage.includes('CLONE')) return 'bg-[var(--color-accent)]/10 text-blue-400 border-blue-500/20';
    if (stage.includes('DRY') || stage.includes('CURE')) return 'bg-[var(--color-warning)]/10 text-amber-400 border-amber-500/20';
    return 'bg-slate-500/10 text-[var(--color-text-tertiary)] border-slate-500/20';
}

function getStageColorHex(stage: string): string {
    if (stage.includes('VEG')) return '#10b981';
    if (stage.includes('FLOWER')) return '#a855f7';
    if (stage.includes('CLONE')) return '#3b82f6';
    if (stage.includes('DRY')) return '#f59e0b';
    return '#64748b';
}
