import React, { useState, useEffect } from 'react';
import { Layers, Check, Settings, X, RotateCw } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { Recipe } from '../types';
import { TechButton } from './common/TechButton';
import { comms } from '../communication';

interface RecipePanelProps {
    isOpen: boolean;
    currentRecipe: Recipe;
    onSelectRecipe: (r: Recipe) => void;
    onClose: () => void;
}

export const RecipePanel: React.FC<RecipePanelProps> = ({ isOpen, currentRecipe, onSelectRecipe, onClose }) => {
    const navigate = useNavigate();
    const [recipes, setRecipes] = useState<Recipe[]>([]);
    const [isLoading, setIsLoading] = useState(false);
    const [selectedId, setSelectedId] = useState<string>(currentRecipe.id);

    // Fetch recipes when panel opens
    useEffect(() => {
        if (isOpen) {
            const fetchRecipes = async () => {
                setIsLoading(true);
                try {
                    const recipeStr = await comms.getRecipeList();
                    const recipeData: Recipe[] = JSON.parse(recipeStr);
                    setRecipes(recipeData);
                } catch (e) {
                    console.error('Failed to fetch recipes:', e);
                }
                setIsLoading(false);
            };
            fetchRecipes();
        }
    }, [isOpen]);

    // Update selected ID when currentRecipe changes
    useEffect(() => {
        setSelectedId(currentRecipe.id);
    }, [currentRecipe.id]);

    const handleConfirm = () => {
        const selected = recipes.find(r => r.id === selectedId);
        if (selected) {
            onSelectRecipe(selected);
            onClose();
        }
    };

    if (!isOpen) return null;

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm animate-in fade-in duration-200">
            <div className="w-[500px] bg-slate-950/90 border border-neon-blue/30 rounded-lg shadow-2xl flex flex-col overflow-hidden">
                {/* Header */}
                <div className="h-12 bg-white/5 flex items-center justify-between px-4 border-b border-white/10">
                    <div className="flex items-center gap-2 text-neon-blue font-tech font-bold tracking-wider">
                        <Layers className="w-4 h-4" /> RECIPE SELECTION
                    </div>
                    <button onClick={onClose} className="text-slate-400 hover:text-white transition-colors">
                        <X className="w-5 h-5" />
                    </button>
                </div>

                {/* List (Max height for ~5 items) */}
                <div className="p-4 max-h-[320px] overflow-y-auto custom-scrollbar">
                    {isLoading ? (
                        <div className="h-64 flex flex-col items-center justify-center gap-4 animate-pulse">
                            <RotateCw className="w-12 h-12 text-neon-blue animate-spin" />
                            <div className="text-lg font-tech text-neon-blue tracking-widest">LOADING RECIPES...</div>
                        </div>
                    ) : (
                        <div className="space-y-2">
                            {recipes.map(recipe => (
                                <div
                                    key={recipe.id}
                                    onClick={() => setSelectedId(recipe.id)}
                                    className={`
                                        p-3 rounded border cursor-pointer transition-all flex items-center justify-between
                                        ${selectedId === recipe.id
                                            ? 'bg-neon-blue/20 border-neon-blue text-white shadow-[0_0_10px_rgba(0,243,255,0.2)]'
                                            : 'bg-white/5 border-white/10 text-slate-400 hover:bg-white/10 hover:border-white/20'}
                                    `}
                                >
                                    <div>
                                        <div className="font-bold tracking-wide">{recipe.name}</div>
                                        <div className="text-[10px] font-mono opacity-70">ID: {recipe.id} | MOD: {recipe.lastModified}</div>
                                    </div>
                                    {selectedId === recipe.id && <Check className="w-4 h-4 text-neon-blue" />}
                                </div>
                            ))}
                        </div>
                    )}
                </div>

                {/* Footer Actions */}
                <div className="p-4 border-t border-white/10 flex justify-between gap-4 bg-black/20">
                    <TechButton
                        variant="default"
                        className="flex items-center gap-2 px-4"
                        onClick={() => navigate('/recipe')}
                    >
                        <Settings className="w-4 h-4" /> MANAGEMENT
                    </TechButton>

                    <TechButton
                        variant="blue"
                        className="flex items-center gap-2 px-8"
                        onClick={handleConfirm}
                    >
                        SELECT
                    </TechButton>
                </div>
            </div>
        </div>
    );
};
