import { useEffect, useRef } from 'react';
import { CameraControls } from '@react-three/drei';

export type CameraPreset = 'OVERHEAD' | 'ISOMETRIC';

interface CameraPresetsProps {
    preset: CameraPreset;
    floorWidth: number;
    floorHeight: number;
    focusTarget?: { x: number; z: number } | null;
    onReady?: (controls: CameraControls) => void;
}

// Camera preset configurations
const getPresetConfig = (
    preset: CameraPreset,
    floorWidth: number,
    floorHeight: number,
    focusTarget?: { x: number; z: number } | null
) => {
    const maxDim = Math.max(floorWidth, floorHeight);

    // If we have a focus target, use it as center, otherwise use floor center
    const centerX = focusTarget?.x ?? 0;
    const centerZ = focusTarget?.z ?? 0;

    switch (preset) {
        case 'OVERHEAD':
            // Top-down view - camera height based on floor size, but closer
            const overheadDist = focusTarget ? 8 : maxDim * 0.6;
            return {
                position: [centerX, overheadDist, centerZ + 0.1] as [number, number, number],
                target: [centerX, 0, centerZ] as [number, number, number],
            };

        case 'ISOMETRIC':
            // 3/4 isometric view - closer for better visibility
            const isoDistance = focusTarget ? 12 : maxDim * 0.5;
            return {
                position: [centerX + isoDistance * 0.7, isoDistance * 0.6, centerZ + isoDistance * 0.7] as [number, number, number],
                target: [centerX, 0, centerZ] as [number, number, number],
            };

        default:
            return {
                position: [0, 20, 25] as [number, number, number],
                target: [0, 0, 0] as [number, number, number],
            };
    }
};

export function CameraPresets({
    preset,
    floorWidth,
    floorHeight,
    focusTarget,
    onReady,
}: CameraPresetsProps) {
    const controlsRef = useRef<CameraControls>(null);
    const lastPresetRef = useRef<string>('');

    // Notify parent when controls are ready
    useEffect(() => {
        if (controlsRef.current && onReady) {
            onReady(controlsRef.current);
        }
    }, [onReady]);

    // Apply preset when it changes
    useEffect(() => {
        if (!controlsRef.current) return;

        const presetKey = `${preset}-${focusTarget?.x ?? 0}-${focusTarget?.z ?? 0}`;
        if (presetKey === lastPresetRef.current) return;
        lastPresetRef.current = presetKey;

        const config = getPresetConfig(preset, floorWidth, floorHeight, focusTarget);

        // Smooth transition to new position
        controlsRef.current.setLookAt(
            config.position[0],
            config.position[1],
            config.position[2],
            config.target[0],
            config.target[1],
            config.target[2],
            true // Enable smooth transition
        );
    }, [preset, floorWidth, floorHeight, focusTarget]);

    const maxDim = Math.max(floorWidth, floorHeight);

    return (
        <CameraControls
            ref={controlsRef}
            enabled={true}
            // Zoom limits
            minDistance={2}
            maxDistance={maxDim * 2}
            // Polar angle limits (don't go below floor)
            minPolarAngle={0.1}
            maxPolarAngle={Math.PI / 2.1}
            // Enable panning for exploration
            dollySpeed={1}
            truckSpeed={0.8}
            // Smooth damping
            smoothTime={0.25}
            makeDefault
        />
    );
}

// UI Component for preset selector buttons - just two options now
interface CameraPresetSelectorProps {
    current: CameraPreset;
    onChange: (preset: CameraPreset) => void;
}

export function CameraPresetSelector({ current, onChange }: CameraPresetSelectorProps) {
    const presets: { id: CameraPreset; label: string; icon: string }[] = [
        { id: 'OVERHEAD', label: 'Overhead', icon: '⬇️' },
        { id: 'ISOMETRIC', label: 'Isometric', icon: '📐' },
    ];

    return (
        <div className="flex gap-1 bg-slate-800/80 rounded-lg p-1">
            {presets.map(({ id, label, icon }) => (
                <button
                    key={id}
                    onClick={() => onChange(id)}
                    className={`
                        px-3 py-1.5 rounded text-xs font-medium transition-all
                        ${current === id
                            ? 'bg-blue-600 text-white'
                            : 'text-slate-300 hover:bg-slate-700'
                        }
                    `}
                    title={label}
                >
                    <span className="mr-1">{icon}</span>
                    {label}
                </button>
            ))}
        </div>
    );
}
