/**
 * Layout Editor Page - 2D facility layout management
 * Now with persistent floor dropdown and proper app shell integration
 */

import { useParams, useNavigate } from 'react-router-dom';
import { useState, useEffect, useMemo } from 'react';
import { LayoutEditor } from '../components/layout-editor';
import { layoutApi, LayoutProperty, LayoutFloor } from '../lib/layoutApi';

interface FloorOption {
    id: string;
    name: string;
    propertyName: string;
    buildingName: string;
}

export function LayoutEditorPage() {
    const { floorId } = useParams<{ floorId: string }>();
    const navigate = useNavigate();
    const [properties, setProperties] = useState<LayoutProperty[]>([]);
    const [selectedFloorId, setSelectedFloorId] = useState<string | undefined>(floorId);
    const [loading, setLoading] = useState(true);
    const [dropdownOpen, setDropdownOpen] = useState(false);

    // Load properties for floor selector
    useEffect(() => {
        async function load() {
            try {
                const props = await layoutApi.getProperties();
                setProperties(props);

                // Auto-select first floor if none specified
                if (!floorId && props.length > 0 && props[0].buildings?.length > 0) {
                    const firstFloor = props[0].buildings[0]?.floors?.[0];
                    if (firstFloor) {
                        setSelectedFloorId(firstFloor.id);
                        navigate(`/layout-editor/${firstFloor.id}`, { replace: true });
                    }
                }
            } catch (e) {
                console.error('Failed to load properties:', e);
            } finally {
                setLoading(false);
            }
        }
        load();
    }, [floorId, navigate]);

    // Flatten floors for dropdown
    const floorOptions = useMemo<FloorOption[]>(() => {
        const options: FloorOption[] = [];
        for (const prop of properties) {
            for (const building of prop.buildings || []) {
                for (const floor of building.floors || []) {
                    options.push({
                        id: floor.id,
                        name: floor.name,
                        propertyName: prop.name,
                        buildingName: building.name,
                    });
                }
            }
        }
        return options;
    }, [properties]);

    const selectedFloor = floorOptions.find(f => f.id === selectedFloorId);

    const handleFloorChange = (newFloorId: string) => {
        setSelectedFloorId(newFloorId);
        setDropdownOpen(false);
        navigate(`/layout-editor/${newFloorId}`);
    };

    if (loading) {
        return (
            <div className="flex items-center justify-center h-full bg-slate-900">
                <div className="animate-spin w-8 h-8 border-2 border-emerald-500 border-t-transparent rounded-full" />
            </div>
        );
    }

    // No floors available
    if (floorOptions.length === 0) {
        return (
            <div className="flex flex-col items-center justify-center h-full bg-slate-900 text-white">
                <svg className="w-16 h-16 mb-4 text-slate-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
                </svg>
                <h2 className="text-xl font-semibold mb-2">No Facility Layouts</h2>
                <p className="text-slate-400 text-sm">Create a property with a floor first to use the layout editor.</p>
            </div>
        );
    }

    return (
        <div className="flex flex-col h-full bg-slate-900">
            {/* Header with Floor Selector */}
            <div className="flex-shrink-0 border-b border-slate-700 bg-slate-800 px-4 py-3">
                <div className="flex items-center justify-between">
                    <div className="flex items-center gap-4">
                        <h1 className="text-lg font-semibold text-white">Layout Editor</h1>

                        {/* Floor Dropdown */}
                        <div className="relative">
                            <button
                                onClick={() => setDropdownOpen(!dropdownOpen)}
                                className="flex items-center gap-2 px-3 py-1.5 bg-slate-700 hover:bg-slate-600 rounded border border-slate-600 text-sm text-white transition-colors"
                            >
                                <span className="text-slate-300">Floor:</span>
                                <span className="font-medium">
                                    {selectedFloor?.name || 'Select floor'}
                                </span>
                                <svg className={`w-4 h-4 transition-transform ${dropdownOpen ? 'rotate-180' : ''}`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                                </svg>
                            </button>

                            {dropdownOpen && (
                                <>
                                    <div className="fixed inset-0 z-10" onClick={() => setDropdownOpen(false)} />
                                    <div className="absolute left-0 top-full mt-1 w-72 bg-slate-800 border border-slate-600 rounded-lg shadow-xl z-20 max-h-80 overflow-y-auto">
                                        {properties.map(prop => (
                                            <div key={prop.id}>
                                                <div className="px-3 py-2 text-xs font-semibold text-slate-400 bg-slate-900/50">
                                                    {prop.name}
                                                </div>
                                                {prop.buildings?.map(building => (
                                                    <div key={building.id}>
                                                        <div className="px-3 py-1 text-xs text-slate-500 border-l-2 border-slate-600 ml-2">
                                                            {building.name}
                                                        </div>
                                                        {building.floors?.map(floor => (
                                                            <button
                                                                key={floor.id}
                                                                onClick={() => handleFloorChange(floor.id)}
                                                                className={`w-full text-left px-4 py-2 text-sm hover:bg-slate-700 transition-colors ${floor.id === selectedFloorId
                                                                        ? 'bg-emerald-600/20 text-emerald-400'
                                                                        : 'text-white'
                                                                    }`}
                                                            >
                                                                {floor.name}
                                                            </button>
                                                        ))}
                                                    </div>
                                                ))}
                                            </div>
                                        ))}
                                    </div>
                                </>
                            )}
                        </div>
                    </div>

                    {/* Quick stats */}
                    {selectedFloor && (
                        <div className="text-sm text-slate-400">
                            {selectedFloor.propertyName} — {selectedFloor.buildingName}
                        </div>
                    )}
                </div>
            </div>

            {/* Editor Canvas */}
            <div className="flex-1 overflow-hidden">
                {selectedFloorId ? (
                    <LayoutEditor floorId={selectedFloorId} className="h-full" />
                ) : (
                    <div className="flex items-center justify-center h-full text-slate-400">
                        Select a floor to start editing
                    </div>
                )}
            </div>
        </div>
    );
}

export default LayoutEditorPage;
