import React, { useState, useEffect } from 'react';
import { Target, CheckCircle2, Loader2 } from 'lucide-react';
import { TechButton } from './common/TechButton';

interface InitializeModalProps {
    isOpen: boolean;
    onClose: () => void;
}

type AxisStatus = 'pending' | 'initializing' | 'completed';

interface AxisState {
    name: string;
    status: AxisStatus;
    progress: number;
}

export const InitializeModal: React.FC<InitializeModalProps> = ({ isOpen, onClose }) => {
    const [axes, setAxes] = useState<AxisState[]>([
        { name: 'X-Axis', status: 'pending', progress: 0 },
        { name: 'Y-Axis', status: 'pending', progress: 0 },
        { name: 'Z-Axis', status: 'pending', progress: 0 },
    ]);
    const [isInitializing, setIsInitializing] = useState(false);

    // Reset state when modal closes
    useEffect(() => {
        if (!isOpen) {
            setAxes([
                { name: 'X-Axis', status: 'pending', progress: 0 },
                { name: 'Y-Axis', status: 'pending', progress: 0 },
                { name: 'Z-Axis', status: 'pending', progress: 0 },
            ]);
            setIsInitializing(false);
        }
    }, [isOpen]);

    const startInitialization = () => {
        setIsInitializing(true);

        // Initialize each axis with 3 second delay between them
        axes.forEach((axis, index) => {
            const delay = index * 3000; // 0s, 3s, 6s

            // Start initialization after delay
            setTimeout(() => {
                setAxes(prev => {
                    const next = [...prev];
                    next[index] = { ...next[index], status: 'initializing', progress: 0 };
                    return next;
                });

                // Progress animation (3 seconds)
                const startTime = Date.now();
                const duration = 3000;
                const interval = setInterval(() => {
                    const elapsed = Date.now() - startTime;
                    const progress = Math.min((elapsed / duration) * 100, 100);

                    setAxes(prev => {
                        const next = [...prev];
                        next[index] = { ...next[index], progress };
                        return next;
                    });

                    if (progress >= 100) {
                        clearInterval(interval);
                        setAxes(prev => {
                            const next = [...prev];
                            next[index] = { ...next[index], status: 'completed', progress: 100 };
                            return next;
                        });

                        // Check if all axes are completed
                        setAxes(prev => {
                            if (prev.every(a => a.status === 'completed')) {
                                // Auto close after 500ms
                                setTimeout(() => {
                                    onClose();
                                }, 500);
                            }
                            return prev;
                        });
                    }
                }, 50);
            }, delay);
        });
    };

    if (!isOpen) return null;

    const allCompleted = axes.every(a => a.status === 'completed');

    return (
        <div className="absolute inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm">
            <div className="w-[600px] glass-holo p-8 border border-neon-blue shadow-glow-blue relative flex flex-col">
                <button
                    onClick={onClose}
                    disabled={isInitializing}
                    className="absolute top-4 right-4 text-slate-400 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed"
                >
                    ✕
                </button>

                <h2 className="text-2xl font-tech font-bold text-neon-blue mb-8 border-b border-white/10 pb-4 flex items-center gap-3">
                    <Target className="animate-pulse" /> AXIS INITIALIZATION
                </h2>

                <div className="space-y-6 mb-8">
                    {axes.map((axis, index) => (
                        <div key={axis.name} className="space-y-2">
                            <div className="flex items-center justify-between">
                                <div className="flex items-center gap-3">
                                    {axis.status === 'completed' ? (
                                        <CheckCircle2 className="w-5 h-5 text-neon-green" />
                                    ) : axis.status === 'initializing' ? (
                                        <Loader2 className="w-5 h-5 text-neon-blue animate-spin" />
                                    ) : (
                                        <div className="w-5 h-5 border-2 border-slate-600 rounded-full" />
                                    )}
                                    <span className="font-tech font-bold text-lg text-white tracking-wider">
                                        {axis.name}
                                    </span>
                                </div>
                                <span
                                    className={`font-mono text-sm font-bold ${
                                        axis.status === 'completed'
                                            ? 'text-neon-green'
                                            : axis.status === 'initializing'
                                            ? 'text-neon-blue'
                                            : 'text-slate-500'
                                    }`}
                                >
                                    {axis.status === 'completed'
                                        ? 'COMPLETED'
                                        : axis.status === 'initializing'
                                        ? `${Math.round(axis.progress)}%`
                                        : 'WAITING'}
                                </span>
                            </div>

                            {/* Progress Bar */}
                            <div className="h-3 bg-black/50 border border-slate-700 overflow-hidden">
                                <div
                                    className={`h-full transition-all duration-100 ${
                                        axis.status === 'completed'
                                            ? 'bg-neon-green shadow-[0_0_10px_rgba(10,255,0,0.5)]'
                                            : 'bg-neon-blue shadow-[0_0_10px_rgba(0,243,255,0.5)]'
                                    }`}
                                    style={{ width: `${axis.progress}%` }}
                                />
                            </div>
                        </div>
                    ))}
                </div>

                {allCompleted && (
                    <div className="mb-6 p-4 bg-neon-green/10 border border-neon-green rounded text-center">
                        <span className="font-tech font-bold text-neon-green tracking-wider">
                            ✓ ALL AXES INITIALIZED SUCCESSFULLY
                        </span>
                    </div>
                )}

                <div className="flex justify-end gap-4">
                    <TechButton onClick={onClose} disabled={isInitializing}>
                        CANCEL
                    </TechButton>
                    <TechButton
                        variant="blue"
                        active
                        onClick={startInitialization}
                        disabled={isInitializing || allCompleted}
                    >
                        {isInitializing ? 'INITIALIZING...' : 'START INITIALIZATION'}
                    </TechButton>
                </div>
            </div>
        </div>
    );
};
