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

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: 'PZ_PICK', status: 'pending', progress: 0 },
        { name: 'PL_UPDN', status: 'pending', progress: 0 },
        { name: 'PR_UPDN', status: 'pending', progress: 0 },
        { name: 'PL_MOVE', status: 'pending', progress: 0 },
        { name: 'PR_MOVE', status: 'pending', progress: 0 },
        { name: 'Z_THETA', status: 'pending', progress: 0 },
        { name: 'PX_PICK', status: 'pending', progress: 0 },
    ]);
    const [isInitializing, setIsInitializing] = useState(false);
    const [errorMessage, setErrorMessage] = useState<string | null>(null);
    const [statusInterval, setStatusInterval] = useState<ReturnType<typeof setInterval> | null>(null);

    // Reset state when modal closes
    useEffect(() => {
        if (!isOpen) {
            setAxes([
                { name: 'PZ_PICK', status: 'pending', progress: 0 },
                { name: 'PL_UPDN', status: 'pending', progress: 0 },
                { name: 'PR_UPDN', status: 'pending', progress: 0 },
                { name: 'PL_MOVE', status: 'pending', progress: 0 },
                { name: 'PR_MOVE', status: 'pending', progress: 0 },
                { name: 'Z_THETA', status: 'pending', progress: 0 },
                { name: 'PX_PICK', status: 'pending', progress: 0 },
            ]);
            setIsInitializing(false);
            setErrorMessage(null);
            if (statusInterval) {
                clearInterval(statusInterval);
                setStatusInterval(null);
            }
        }
    }, [isOpen]);

    // Cleanup interval on unmount
    useEffect(() => {
        return () => {
            if (statusInterval) {
                clearInterval(statusInterval);
            }
        };
    }, [statusInterval]);

    const updateStatus = async () => {
        try {
            const statusJson = await comms.getInitializeStatus();
            const status = JSON.parse(statusJson);

            if (!status.isInitializing) {
                // Initialization complete
                if (statusInterval) {
                    clearInterval(statusInterval);
                    setStatusInterval(null);
                }
                setIsInitializing(false);

                // Check if all axes are home set
                const allComplete = status.axes.every((axis: any) => axis.isHomeSet);
                if (allComplete) {
                    // Auto close after 1 second
                    setTimeout(() => {
                        onClose();
                    }, 1000);
                }
            }

            // Update axis states
            setAxes(prev => {
                return prev.map(axis => {
                    const backendAxis = status.axes.find((a: any) => a.name === axis.name);
                    if (backendAxis) {
                        const progress = backendAxis.progress;
                        const isComplete = backendAxis.isHomeSet;
                        return {
                            ...axis,
                            progress,
                            status: isComplete ? 'completed' : progress > 0 ? 'initializing' : 'pending'
                        };
                    }
                    return axis;
                });
            });
        } catch (error) {
            console.error('[InitializeModal] Status update error:', error);
        }
    };

    const startInitialization = async () => {
        try {
            setErrorMessage(null);
            const result = await comms.initializeDevice();

            if (!result.success) {
                setErrorMessage(result.message);
                return;
            }

            setIsInitializing(true);

            // Start polling for status updates every 200ms
            const interval = setInterval(updateStatus, 200);
            setStatusInterval(interval);
        } catch (error: any) {
            setErrorMessage(error.message || 'Failed to start initialization');
            console.error('[InitializeModal] Initialization error:', error);
        }
    };

    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-[700px] max-h-[90vh] overflow-y-auto 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" /> DEVICE INITIALIZATION
                </h2>

                {errorMessage && (
                    <div className="mb-6 p-4 bg-red-500/10 border border-red-500 rounded flex items-start gap-3">
                        <AlertCircle className="w-5 h-5 text-red-500 flex-shrink-0 mt-0.5" />
                        <div className="flex-1">
                            <div className="font-tech font-bold text-red-500 mb-1">INITIALIZATION ERROR</div>
                            <pre className="text-sm text-slate-300 whitespace-pre-wrap font-mono">
                                {errorMessage}
                            </pre>
                        </div>
                    </div>
                )}

                <div className="space-y-4 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-base 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-2.5 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>
    );
};
