/**
 * LayoutEditor - Main 2D room/floor editor with drag-and-drop
 * Focused on intuitive UX for facility layout management
 */

import { useState, useEffect, useCallback } from 'react';
import { Move, Trash2, ShieldCheck, Sprout } from 'lucide-react';
import { toast } from 'sonner';
import { TypeLibrary } from './TypeLibrary';
import { RackVisualizer, RackData, PlantSlotData } from './RackVisualizer';
import { PlantHistoryTimeline } from './PlantHistoryTimeline';
import { RackConfigModal } from './RackConfigModal';
import { cn } from '../../lib/utils';
import { layoutApi, LayoutPlantType, Floor3DData } from '../../lib/layoutApi';

interface LayoutEditorProps {
    floorId: string;
    className?: string;
}

export function LayoutEditor({ floorId, className }: LayoutEditorProps) {
    const [floorData, setFloorData] = useState<Floor3DData | null>(null);
    const [plantTypes, setPlantTypes] = useState<LayoutPlantType[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const [selectedSlot, setSelectedSlot] = useState<PlantSlotData | null>(null);
    const [draggingType, setDraggingType] = useState<LayoutPlantType | null>(null);
    const [configRack, setConfigRack] = useState<RackData | null>(null);

    // Load floor data and plant types
    const reloadFloorData = useCallback(async () => {
        try {
            const floor = await layoutApi.getFloor3D(floorId);
            setFloorData(floor);
        } catch (e) {
            console.error('Failed to reload floor:', e);
        }
    }, [floorId]);

    useEffect(() => {
        async function load() {
            try {
                setLoading(true);
                const [floor, types] = await Promise.all([
                    layoutApi.getFloor3D(floorId),
                    layoutApi.getPlantTypes(),
                ]);
                setFloorData(floor);
                setPlantTypes(types);
            } catch (e) {
                setError('Failed to load layout data');
                console.error(e);
            } finally {
                setLoading(false);
            }
        }
        load();
    }, [floorId]);

    // Convert floor data to rack format
    const racks: RackData[] = floorData?.rooms.flatMap(room =>
        room.sections.map(section => ({
            id: section.id,
            name: section.name,
            code: section.code,
            subtype: (section.type as RackData['subtype']) || 'RACK',
            rows: section.rows,
            columns: section.columns,
            tiers: 1, // TODO: get from section
            slots: section.positions.map(pos => {
                // Find plant type by ID (new way) or strain name (legacy way)
                const mappedPlantType = pos.plant
                    ? plantTypes.find(pt => pt.id === pos.plant?.plantTypeId) ||
                    plantTypes.find(pt => pt.strain === pos.plant?.strain)
                    : undefined;

                return {
                    id: pos.id,
                    row: pos.row,
                    column: pos.column,
                    tier: pos.tier,
                    status: pos.status as PlantSlotData['status'],
                    plantType: mappedPlantType,
                    tagNumber: pos.plant?.tagNumber,
                    plant: pos.plant ? { id: pos.plant.id, tagNumber: pos.plant.tagNumber } : undefined,
                };
            }),
        }))
    ) || [];

    const handleSlotClick = useCallback((slot: PlantSlotData) => {
        setSelectedSlot(slot);
    }, []);

    const handleSlotDrop = useCallback(async (slot: PlantSlotData, plantType: LayoutPlantType) => {
        try {
            await layoutApi.occupyPosition(slot.id, { plantTypeId: plantType.id });

            // Reload floor data to reflect changes
            const floor = await layoutApi.getFloor3D(floorId);
            setFloorData(floor);
        } catch (e) {
            console.error('Failed to place plant:', e);
            setError('Failed to place plant. Please try again.');
        }
    }, [floorId]);

    const handleDragStart = useCallback((plantType: LayoutPlantType) => {
        setDraggingType(plantType);
    }, []);

    const handleConfigClick = useCallback((rack: RackData) => {
        setConfigRack(rack);
    }, []);

    const handleConfigSave = useCallback(async (updates: Partial<RackData>) => {
        if (!configRack) return;

        try {
            // Call API to update section
            await layoutApi.updateSection(configRack.id, {
                name: updates.name,
                code: updates.code,
                type: updates.subtype,
                rows: updates.rows,
                columns: updates.columns,
            });

            // Reload floor data to get updated positions
            const floor = await layoutApi.getFloor3D(floorId);
            setFloorData(floor);

            console.log('Section updated:', configRack.id, updates);
        } catch (e) {
            console.error('Failed to update section:', e);
            throw e;
        }
    }, [configRack, floorId]);

    if (loading) {
        return (
            <div className={cn('flex items-center justify-center h-full', className)}>
                <div className="text-slate-400">Loading layout...</div>
            </div>
        );
    }

    if (error) {
        return (
            <div className={cn('flex items-center justify-center h-full', className)}>
                <div className="text-red-400">{error}</div>
            </div>
        );
    }

    return (
        <div className={cn('flex h-full bg-background font-sans', className)}>
            {/* Plant Type Sidebar */}
            <TypeLibrary
                plantTypes={plantTypes}
                onDragStart={handleDragStart}
                className="w-72 flex-shrink-0"
            />

            {/* Main Canvas */}
            <div className="flex-1 overflow-auto p-8 relative">
                {/* Header */}
                <div className="mb-8">
                    <h1 className="text-3xl font-display font-bold text-foreground tracking-tight">
                        {floorData?.floor.property} — {floorData?.floor.building}
                    </h1>
                    <p className="text-sm text-muted-foreground mt-1">
                        {floorData?.floor.name} • <span className="text-primary">{floorData?.stats.occupiedPositions}</span>/{floorData?.stats.totalPositions} positions filled
                    </p>
                </div>

                {/* Rooms */}
                {floorData?.rooms.map(room => (
                    <div key={room.id} className="mb-10">
                        <h2 className="text-xl font-display font-semibold text-foreground mb-4 flex items-center gap-3">
                            <span
                                className="w-2 h-2 rounded-full ring-2 ring-primary/20"
                                style={{ backgroundColor: room.color || 'var(--color-primary)' }}
                            />
                            {room.name}
                            <span className="text-xs text-muted-foreground font-mono bg-secondary px-2 py-0.5 rounded ml-auto">
                                {room.code}
                            </span>
                        </h2>

                        {/* Racks Grid */}
                        <div className="flex flex-wrap gap-6">
                            {racks
                                .filter(r => room.sections.some(s => s.id === r.id))
                                .map(rack => (
                                    <RackVisualizer
                                        key={rack.id}
                                        rack={rack}
                                        onSlotClick={handleSlotClick}
                                        onSlotDrop={handleSlotDrop}
                                        onConfigClick={handleConfigClick}
                                    />
                                ))}
                        </div>
                    </div>
                ))}

                {/* Empty state */}
                {(!floorData?.rooms || floorData.rooms.length === 0) && (
                    <div className="flex flex-col items-center justify-center h-64 text-muted-foreground/50 border-2 border-dashed border-border rounded-xl">
                        <svg className="w-12 h-12 mb-4 opacity-20" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M4 5a1 1 0 011-1h14a1 1 0 011 1v2a1 1 0 01-1 1H5a1 1 0 01-1-1V5zM4 13a1 1 0 011-1h6a1 1 0 011 1v6a1 1 0 01-1 1H5a1 1 0 01-1-1v-6zM16 13a1 1 0 011-1h2a1 1 0 011 1v6a1 1 0 01-1 1h-2a1 1 0 01-1-1v-6z" />
                        </svg>
                        <p className="text-lg font-medium">No rooms configured</p>
                        <p className="text-sm">Add rooms to this floor to start placing plants</p>
                    </div>
                )}
            </div>



            {/* Selected Slot Panel */}
            {
                selectedSlot && (
                    <div className="w-96 border-l border-border bg-card/95 backdrop-blur-xl absolute right-0 top-0 bottom-0 shadow-2xl z-20 transition-transform animate-in slide-in-from-right flex flex-col">
                        <div className="flex items-center justify-between p-6 border-b border-border">
                            <div>
                                <h3 className="text-lg font-display font-semibold text-foreground">Slot Details</h3>
                                <div className="flex items-center gap-2 mt-0.5 group">
                                    <p className="text-xs text-muted-foreground font-mono">{selectedSlot.plant?.tagNumber || 'No ID'}</p>
                                    {selectedSlot.plant?.id && (
                                        <button
                                            onClick={(e) => {
                                                e.stopPropagation();
                                                const newTag = prompt('Update Tag:', selectedSlot.plant?.tagNumber);
                                                if (newTag && newTag !== selectedSlot.plant?.tagNumber) {
                                                    layoutApi.updatePlant(selectedSlot.plant!.id, { tagNumber: newTag })
                                                        .then(() => {
                                                            toast.info('Tag Updated', { description: newTag });
                                                            reloadFloorData();
                                                            setSelectedSlot(prev => prev ? ({ ...prev, plant: { ...prev.plant!, tagNumber: newTag } }) : null);
                                                        });
                                                }
                                            }}
                                            className="opacity-0 group-hover:opacity-100 text-[10px] text-primary hover:underline"
                                        >
                                            Edit
                                        </button>
                                    )}
                                </div>
                            </div>
                            <button
                                onClick={() => setSelectedSlot(null)}
                                className="text-muted-foreground hover:text-foreground transition-colors p-2 hover:bg-secondary rounded-full"
                            >
                                ✕
                            </button>
                        </div>

                        <div className="flex-1 overflow-y-auto p-6 space-y-6">
                            {/* Status Tags */}
                            <div className="flex gap-2">
                                <span className={cn(
                                    'px-2 py-1 rounded font-medium text-xs border',
                                    selectedSlot.status === 'OCCUPIED' && 'bg-primary/10 text-primary border-primary/20',
                                    selectedSlot.status === 'EMPTY' && 'bg-secondary text-muted-foreground border-border',
                                    selectedSlot.status === 'DAMAGED' && 'bg-destructive/10 text-destructive border-destructive/20',
                                )}>
                                    {selectedSlot.status}
                                </span>
                                <span className="px-2 py-1 rounded font-medium text-xs bg-secondary border border-border text-foreground font-mono">
                                    R{selectedSlot.row} C{selectedSlot.column}
                                </span>
                            </div>

                            {/* Plant Details */}
                            {selectedSlot.plantType && (
                                <div className="space-y-3">
                                    <div>
                                        <label className="text-xs uppercase tracking-wider text-muted-foreground font-semibold">Genetics</label>
                                        <div className="mt-1 p-3 bg-secondary/30 rounded-lg border border-border">
                                            <div className="font-medium text-foreground">{selectedSlot.plantType.name}</div>
                                            {selectedSlot.plantType.strain && <div className="text-sm text-muted-foreground">{selectedSlot.plantType.strain}</div>}
                                        </div>
                                    </div>
                                </div>
                            )}

                            {/* Lifecycle History */}
                            {selectedSlot.status === 'OCCUPIED' && selectedSlot.plant?.id && (
                                <div className="space-y-3">
                                    <div className="flex items-center justify-between">
                                        <label className="text-xs uppercase tracking-wider text-muted-foreground font-semibold">Lifecycle History (METRC)</label>
                                        <button className="text-[10px] bg-primary/10 text-primary px-2 py-0.5 rounded hover:bg-primary/20 transition-colors">
                                            + Event
                                        </button>
                                    </div>
                                    <div className="relative">
                                        <PlantHistoryTimeline plantId={selectedSlot.plant.id} />
                                    </div>
                                </div>
                            )}

                            {/* DEBUG: Fallback if plant ID missing in slot data but it says occupied */}
                            {selectedSlot.status === 'OCCUPIED' && !selectedSlot.plant?.id && (
                                <div className="p-4 bg-warning/10 text-warning text-xs rounded border border-warning/20">
                                    Warning: Plant ID missing from slot data. History unavailable.
                                </div>
                            )}
                        </div>

                        {/* Actions Footer */}
                        <div className="p-6 border-t border-border bg-secondary/10">
                            {selectedSlot.status === 'EMPTY' ? (
                                <button className="w-full py-2.5 bg-primary hover:bg-primary-hover text-primary-foreground font-medium text-sm rounded-lg shadow-sm transition-all">
                                    Place Plant
                                </button>
                            ) : (
                                <div className="grid grid-cols-2 gap-3">
                                    <button
                                        className="py-2.5 bg-secondary hover:bg-secondary/80 text-foreground border border-border text-sm rounded-lg transition-colors font-medium flex items-center justify-center gap-2"
                                        onClick={() => toast.info('Move Plant', { description: 'Drag and drop plants on the grid to move them.' })}
                                    >
                                        <Move className="w-4 h-4" /> Move
                                    </button>

                                    {selectedSlot.plantType?.category === 'FLOWER' ? (
                                        <button
                                            onClick={() => {
                                                if (!selectedSlot.plant?.id) return;
                                                const weight = prompt('Enter Harvest Weight (g):');
                                                if (weight) {
                                                    layoutApi.harvestPlant(selectedSlot.plant.id, { weight: parseFloat(weight), unit: 'g' })
                                                        .then(() => {
                                                            toast.success('Plant Harvested');
                                                            reloadFloorData();
                                                            setSelectedSlot(null);
                                                        });
                                                }
                                            }}
                                            className="py-2.5 bg-emerald-500/10 hover:bg-emerald-500/20 text-emerald-500 border border-emerald-500/20 text-sm rounded-lg transition-colors font-medium flex items-center justify-center gap-2"
                                        >
                                            <Sprout className="w-4 h-4" /> Harvest
                                        </button>
                                    ) : (
                                        <button
                                            onClick={() => {
                                                if (!selectedSlot.plant?.id) return;
                                                if (confirm('DESTROY PLANT? This will log a METRC destruction event.')) {
                                                    layoutApi.destroyPlant(selectedSlot.plant.id, 'Manual Destruction')
                                                        .then(() => {
                                                            toast.error('Plant Destroyed');
                                                            reloadFloorData();
                                                            setSelectedSlot(null);
                                                        });
                                                }
                                            }}
                                            className="py-2.5 bg-destructive/10 hover:bg-destructive/20 text-destructive border border-destructive/20 text-sm rounded-lg transition-colors font-medium flex items-center justify-center gap-2"
                                        >
                                            <Trash2 className="w-4 h-4" /> Destroy
                                        </button>
                                    )}
                                    <button
                                        className="col-span-2 py-2.5 bg-primary hover:bg-primary-hover text-primary-foreground font-medium text-sm rounded-lg shadow-sm transition-all flex items-center justify-center gap-2"
                                        onClick={() => toast.info('Compliance', { description: 'Opening compliance manager...' })}
                                    >
                                        <ShieldCheck className="w-4 h-4" /> Manage Compliance
                                    </button>
                                </div>
                            )}
                        </div>
                    </div>
                )
            }

            {/* Rack Config Modal */}
            {
                configRack && (
                    <RackConfigModal
                        rack={configRack}
                        isOpen={!!configRack}
                        onClose={() => setConfigRack(null)}
                        onSave={handleConfigSave}
                    />
                )
            }
        </div >
    );
}

export default LayoutEditor;
