import { useState, useEffect } from 'react';
import { useLayoutStore, ROOM_COLORS, LayoutRoom, LayoutSection, LayoutPosition } from '../../../stores/layoutStore';
import { Trash2, Copy, Move, Maximize2, Plus, LayoutGrid, Edit2, Sprout, MapPin, X, ArrowRight } from 'lucide-react';
import { AddSectionDialog } from './AddSectionDialog';

const PIXELS_PER_FOOT = 20;

export function InspectorPanel() {
    const { rooms, selectedIds, updateRoom, deleteRoom, selectedPosition, setSelectedPosition } = useLayoutStore();

    // Position inspector takes priority
    if (selectedPosition) {
        return <PositionInspector position={selectedPosition} onClose={() => setSelectedPosition(null)} />;
    }

    // Get selected room
    const selectedRoom = selectedIds.length === 1
        ? rooms.find(r => r.id === selectedIds[0])
        : null;

    if (selectedIds.length === 0) {
        return (
            <div className="p-4 text-center text-[var(--color-text-tertiary)] text-sm">
                <div className="w-16 h-16 mx-auto mb-4 bg-slate-800 rounded-full flex items-center justify-center">
                    <Move size={24} className="text-slate-600" />
                </div>
                <p>Select an element to view its properties</p>
            </div>
        );
    }

    if (selectedIds.length > 1) {
        return (
            <div className="p-4">
                <div className="bg-slate-800/50 rounded-xl p-4">
                    <p className="text-sm text-[var(--color-text-tertiary)] mb-2">
                        {selectedIds.length} items selected
                    </p>
                    <div className="flex gap-2">
                        <button className="flex-1 flex items-center justify-center gap-2 px-3 py-2 bg-slate-700 hover:bg-slate-600 rounded-lg text-xs text-white transition-colors">
                            <Copy size={14} />
                            Duplicate
                        </button>
                        <button
                            onClick={() => selectedIds.forEach(id => deleteRoom(id))}
                            className="flex-1 flex items-center justify-center gap-2 px-3 py-2 bg-red-600/20 hover:bg-red-600/30 rounded-lg text-xs text-red-400 transition-colors"
                        >
                            <Trash2 size={14} />
                            Delete
                        </button>
                    </div>
                </div>
            </div>
        );
    }

    if (!selectedRoom) return null;

    return <RoomInspector room={selectedRoom} />;
}

// Position Inspector Component
function PositionInspector({
    position,
    onClose
}: {
    position: LayoutPosition & { sectionName?: string; roomName?: string };
    onClose: () => void;
}) {
    const statusColors: Record<string, string> = {
        EMPTY: 'bg-slate-500',
        PLANTED: 'bg-[var(--color-primary)]',
        HARVESTED: 'bg-[var(--color-warning)]',
        ISSUE: 'bg-red-500',
        RESERVED: 'bg-[var(--color-accent)]',
    };

    return (
        <div className="h-full overflow-auto">
            {/* Header */}
            <div className="p-4 border-b border-white/10">
                <div className="flex items-center justify-between mb-3">
                    <div className="flex items-center gap-3">
                        <div className={`w-10 h-10 rounded-lg flex items-center justify-center text-white ${statusColors[position.status] || 'bg-slate-600'}`}>
                            {position.status === 'PLANTED' ? <Sprout size={20} /> : <MapPin size={20} />}
                        </div>
                        <div>
                            <h3 className="font-bold text-white">Position R{position.row}C{position.column}</h3>
                            <p className="text-xs text-[var(--color-text-tertiary)]">{position.sectionName || 'Section'}</p>
                        </div>
                    </div>
                    <button
                        onClick={onClose}
                        className="p-1 text-[var(--color-text-tertiary)] hover:text-white transition-colors"
                    >
                        <X size={18} />
                    </button>
                </div>
            </div>

            {/* Properties */}
            <div className="p-4 space-y-4">
                {/* Status */}
                <div>
                    <label className="block text-xs text-[var(--color-text-tertiary)] mb-2">Status</label>
                    <div className={`inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-sm font-medium ${statusColors[position.status] || 'bg-slate-600'} text-white`}>
                        {position.status}
                    </div>
                </div>

                {/* Location */}
                <div>
                    <label className="block text-xs text-[var(--color-text-tertiary)] mb-2">Location</label>
                    <div className="bg-slate-800 rounded-lg p-3 space-y-2">
                        <div className="flex justify-between text-sm">
                            <span className="text-[var(--color-text-tertiary)]">Row</span>
                            <span className="text-white font-mono">{position.row}</span>
                        </div>
                        <div className="flex justify-between text-sm">
                            <span className="text-[var(--color-text-tertiary)]">Column</span>
                            <span className="text-white font-mono">{position.column}</span>
                        </div>
                        <div className="flex justify-between text-sm">
                            <span className="text-[var(--color-text-tertiary)]">Slot</span>
                            <span className="text-white font-mono">{position.slot}</span>
                        </div>
                    </div>
                </div>

                {/* Plant Info (if planted) */}
                {position.status === 'PLANTED' && (position.plant || position.plantId) && (
                    <div>
                        <label className="block text-xs text-[var(--color-text-tertiary)] mb-2 flex items-center gap-2">
                            <Sprout size={12} />
                            Plant Info
                        </label>
                        <div className="bg-[var(--color-primary)]/10 border border-emerald-500/20 rounded-lg p-3 space-y-2">
                            {position.plant?.tagNumber && (
                                <div className="flex justify-between text-sm">
                                    <span className="text-[var(--color-text-tertiary)]">Tag #</span>
                                    <span className="text-emerald-400 font-mono text-xs">{position.plant.tagNumber}</span>
                                </div>
                            )}
                            {position.plant?.address && (
                                <div className="flex justify-between text-sm">
                                    <span className="text-[var(--color-text-tertiary)]">Address</span>
                                    <span className="text-white font-mono text-xs">{position.plant.address}</span>
                                </div>
                            )}
                            {position.plant?.batchId && (
                                <div className="flex justify-between text-sm">
                                    <span className="text-[var(--color-text-tertiary)]">Batch</span>
                                    <span className="text-blue-400 font-mono text-xs">{position.plant.batchId.slice(0, 8)}...</span>
                                </div>
                            )}
                            {!position.plant && position.plantId && (
                                <div className="flex justify-between text-sm">
                                    <span className="text-[var(--color-text-tertiary)]">Plant ID</span>
                                    <span className="text-emerald-400 font-mono text-xs">{position.plantId.slice(0, 8)}...</span>
                                </div>
                            )}
                        </div>
                    </div>
                )}

                {/* Actions */}
                {position.status === 'PLANTED' && (
                    <div className="pt-2 border-t border-white/10">
                        <button
                            className="w-full flex items-center justify-center gap-2 px-3 py-2 bg-[var(--color-warning)]/10 hover:bg-[var(--color-warning)]/20 rounded-lg text-sm text-amber-400 transition-colors"
                        >
                            <ArrowRight size={14} />
                            Move Plant
                        </button>
                    </div>
                )}
            </div>
        </div>
    );
}

function RoomInspector({ room }: { room: LayoutRoom }) {
    const { updateRoom, deleteRoom, sections, addSection, deleteSection, updateSection } = useLayoutStore();

    const [name, setName] = useState(room.name);
    const [code, setCode] = useState(room.code);
    const [width, setWidth] = useState(Math.round(room.size.width / PIXELS_PER_FOOT));
    const [height, setHeight] = useState(Math.round(room.size.height / PIXELS_PER_FOOT));

    // Dialog state
    const [isAddSectionOpen, setIsAddSectionOpen] = useState(false);
    const [editingSection, setEditingSection] = useState<LayoutSection | undefined>(undefined);

    // Filter sections for this room
    const roomSections = sections.filter(s => s.roomId === room.id);

    // Sync local state when room changes
    useEffect(() => {
        setName(room.name);
        setCode(room.code);
        setWidth(Math.round(room.size.width / PIXELS_PER_FOOT));
        setHeight(Math.round(room.size.height / PIXELS_PER_FOOT));
    }, [room]);

    const handleNameBlur = () => {
        if (name !== room.name) {
            updateRoom(room.id, { name });
        }
    };

    const handleCodeBlur = () => {
        if (code !== room.code) {
            updateRoom(room.id, { code });
        }
    };

    const handleSizeBlur = () => {
        const newWidth = width * PIXELS_PER_FOOT;
        const newHeight = height * PIXELS_PER_FOOT;

        if (newWidth !== room.size.width || newHeight !== room.size.height) {
            updateRoom(room.id, {
                size: { width: newWidth, height: newHeight }
            });
        }
    };

    const color = room.color || ROOM_COLORS[room.type];

    return (
        <div className="h-full overflow-auto relative">
            {/* Header */}
            <div className="p-4 border-b border-white/10">
                <div className="flex items-center gap-3 mb-3">
                    <div
                        className="w-10 h-10 rounded-lg flex items-center justify-center text-white font-bold"
                        style={{ backgroundColor: color }}
                    >
                        {room.type.slice(0, 1)}
                    </div>
                    <div>
                        <h3 className="font-bold text-white">{room.code}</h3>
                        <p className="text-xs text-[var(--color-text-tertiary)]">{room.type} Room</p>
                    </div>
                </div>
            </div>

            {/* Properties */}
            <div className="p-4 space-y-6">
                {/* Name & Code */}
                <div className="space-y-3">
                    <div>
                        <label className="block text-xs text-[var(--color-text-tertiary)] mb-1">Name</label>
                        <input
                            type="text"
                            value={name}
                            onChange={(e) => setName(e.target.value)}
                            onBlur={handleNameBlur}
                            className="w-full bg-slate-800 border border-slate-700 rounded-lg px-3 py-2 text-sm text-white focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 outline-none"
                        />
                    </div>
                    <div>
                        <label className="block text-xs text-[var(--color-text-tertiary)] mb-1">Code</label>
                        <input
                            type="text"
                            value={code}
                            onChange={(e) => setCode(e.target.value.toUpperCase())}
                            onBlur={handleCodeBlur}
                            className="w-full bg-slate-800 border border-slate-700 rounded-lg px-3 py-2 text-sm text-white font-mono focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 outline-none"
                        />
                    </div>
                </div>

                {/* Dimensions */}
                <div>
                    <label className="block text-xs text-[var(--color-text-tertiary)] mb-2 flex items-center gap-2">
                        <Maximize2 size={12} />
                        Dimensions
                    </label>
                    <div className="flex gap-2">
                        <div className="flex-1">
                            <div className="flex items-center bg-slate-800 border border-slate-700 rounded-lg overflow-hidden">
                                <input
                                    type="number"
                                    value={width}
                                    onChange={(e) => setWidth(parseInt(e.target.value) || 0)}
                                    onBlur={handleSizeBlur}
                                    className="flex-1 bg-transparent px-3 py-2 text-sm text-white outline-none min-w-0"
                                />
                                <span className="px-2 text-xs text-[var(--color-text-tertiary)]">ft</span>
                            </div>
                            <span className="text-xs text-[var(--color-text-tertiary)] mt-1 block text-center">Width</span>
                        </div>
                        <span className="text-slate-600 self-start mt-2">×</span>
                        <div className="flex-1">
                            <div className="flex items-center bg-slate-800 border border-slate-700 rounded-lg overflow-hidden">
                                <input
                                    type="number"
                                    value={height}
                                    onChange={(e) => setHeight(parseInt(e.target.value) || 0)}
                                    onBlur={handleSizeBlur}
                                    className="flex-1 bg-transparent px-3 py-2 text-sm text-white outline-none min-w-0"
                                />
                                <span className="px-2 text-xs text-[var(--color-text-tertiary)]">ft</span>
                            </div>
                            <span className="text-xs text-[var(--color-text-tertiary)] mt-1 block text-center">Height</span>
                        </div>
                    </div>
                    <div className="mt-2 text-center text-xs text-[var(--color-text-tertiary)]">
                        Area: {width * height} sq ft
                    </div>
                </div>

                {/* Sections List */}
                <div>
                    <div className="flex items-center justify-between mb-3">
                        <label className="text-xs text-[var(--color-text-tertiary)] flex items-center gap-2">
                            <LayoutGrid size={12} />
                            Sections ({roomSections.length})
                        </label>
                        <button
                            onClick={() => {
                                setEditingSection(undefined);
                                setIsAddSectionOpen(true);
                            }}
                            className="bg-[var(--color-primary)]/10 hover:bg-[var(--color-primary)]/20 text-emerald-400 p-1 rounded transition-colors"
                        >
                            <Plus size={14} />
                        </button>
                    </div>

                    <div className="space-y-2 max-h-48 overflow-y-auto pr-1">
                        {roomSections.map(section => (
                            <div
                                key={section.id}
                                className="bg-slate-800 border border-slate-700 rounded-lg p-3 group hover:border-emerald-500/50 transition-colors"
                            >
                                <div className="flex items-start justify-between">
                                    <div>
                                        <div className="text-sm text-white font-medium">{section.name}</div>
                                        <div className="text-xs text-[var(--color-text-tertiary)] font-mono">{section.code}</div>
                                    </div>
                                    <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                                        <button
                                            onClick={() => {
                                                setEditingSection(section);
                                                setIsAddSectionOpen(true);
                                            }}
                                            className="p-1 text-[var(--color-text-tertiary)] hover:text-white"
                                        >
                                            <Edit2 size={12} />
                                        </button>
                                        <button
                                            onClick={() => deleteSection(section.id)}
                                            className="p-1 text-[var(--color-text-tertiary)] hover:text-red-400"
                                        >
                                            <Trash2 size={12} />
                                        </button>
                                    </div>
                                </div>
                                <div className="mt-2 flex items-center justify-between text-xs text-[var(--color-text-tertiary)]">
                                    <span>{section.rows}x{section.columns} Grid</span>
                                    <span>{Math.round(section.size.width / PIXELS_PER_FOOT)}'×{Math.round(section.size.height / PIXELS_PER_FOOT)}'</span>
                                </div>
                            </div>
                        ))}
                        {roomSections.length === 0 && (
                            <div className="text-center py-6 border-2 border-dashed border-slate-800 rounded-lg">
                                <p className="text-xs text-[var(--color-text-tertiary)] mb-2">No sections defined</p>
                                <button
                                    onClick={() => setIsAddSectionOpen(true)}
                                    className="text-xs text-emerald-400 hover:text-emerald-300 font-medium"
                                >
                                    + Add Grow Table
                                </button>
                            </div>
                        )}
                    </div>
                </div>

                {/* Type */}
                <div>
                    <label className="block text-xs text-[var(--color-text-tertiary)] mb-2">Room Type</label>
                    <select
                        value={room.type}
                        onChange={(e) => updateRoom(room.id, { type: e.target.value as LayoutRoom['type'] })}
                        className="w-full bg-slate-800 border border-slate-700 rounded-lg px-3 py-2 text-sm text-white outline-none focus:border-emerald-500"
                    >
                        <option value="VEG">Vegetative</option>
                        <option value="FLOWER">Flower</option>
                        <option value="CLONE">Clone</option>
                        <option value="DRY">Drying</option>
                        <option value="CURE">Curing</option>
                        <option value="TRIM">Trim</option>
                        <option value="VAULT">Vault</option>
                        <option value="OTHER">Other</option>
                    </select>
                </div>

                {/* Position */}
                <div>
                    <label className="block text-xs text-[var(--color-text-tertiary)] mb-2 flex items-center gap-2">
                        <Move size={12} />
                        Position
                    </label>
                    <div className="grid grid-cols-2 gap-2 text-xs">
                        <div className="bg-slate-800 rounded-lg px-3 py-2 flex justify-between">
                            <span className="text-[var(--color-text-tertiary)]">X:</span>
                            <span className="text-white">{Math.round(room.position.x / PIXELS_PER_FOOT)} ft</span>
                        </div>
                        <div className="bg-slate-800 rounded-lg px-3 py-2 flex justify-between">
                            <span className="text-[var(--color-text-tertiary)]">Y:</span>
                            <span className="text-white">{Math.round(room.position.y / PIXELS_PER_FOOT)} ft</span>
                        </div>
                    </div>
                </div>
            </div>

            {/* Actions */}
            <div className="p-4 border-t border-white/10 space-y-2">
                <button className="w-full flex items-center justify-center gap-2 px-3 py-2 bg-slate-700 hover:bg-slate-600 rounded-lg text-sm text-white transition-colors">
                    <Copy size={14} />
                    Duplicate Room
                </button>
                <button
                    onClick={() => deleteRoom(room.id)}
                    className="w-full flex items-center justify-center gap-2 px-3 py-2 bg-red-600/20 hover:bg-red-600/30 rounded-lg text-sm text-red-400 transition-colors"
                >
                    <Trash2 size={14} />
                    Delete Room
                </button>
            </div>

            <AddSectionDialog
                room={room}
                isOpen={isAddSectionOpen}
                onClose={() => setIsAddSectionOpen(false)}
                onSave={(section) => {
                    if (editingSection) {
                        updateSection(editingSection.id, section);
                    } else {
                        addSection(section);
                    }
                }}
                editSection={editingSection}
            />
        </div>
    );
}
