import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Layers, Plus, Trash2, Copy, Save, ArrowLeft, FileText, Calendar } from 'lucide-react';
import { Recipe } from '../types';
import { comms } from '../communication';
import { TechButton } from '../components/common/TechButton';

export const RecipePage: React.FC = () => {
    const navigate = useNavigate();
    const [recipes, setRecipes] = useState<Recipe[]>([]);
    const [selectedId, setSelectedId] = useState<string | null>(null);
    const [editedRecipe, setEditedRecipe] = useState<Recipe | null>(null);
    const [isLoading, setIsLoading] = useState(true);

    useEffect(() => {
        const loadRecipes = async () => {
            try {
                const recipeStr = await comms.getRecipeList();
                const recipeData = JSON.parse(recipeStr);
                setRecipes(recipeData);
                if (recipeData.length > 0) {
                    setSelectedId(recipeData[0].id);
                    setEditedRecipe(recipeData[0]);
                }
            } catch (e) {
                console.error("Failed to load recipes", e);
            }
            setIsLoading(false);
        };
        loadRecipes();
    }, []);

    const handleSelect = (r: Recipe) => {
        setSelectedId(r.id);
        setEditedRecipe({ ...r });
    };

    const handleSave = async () => {
        // Mock Save Logic
        console.log("Saving recipe:", editedRecipe);
        // In real app: await comms.saveRecipe(editedRecipe);
    };

    return (
        <div className="w-full h-full p-6 flex flex-col gap-4">
            {/* Header */}
            <div className="flex items-center justify-between shrink-0">
                <div className="flex items-center gap-4">
                    <button
                        onClick={() => navigate('/')}
                        className="p-2 rounded-full hover:bg-white/10 text-slate-400 hover:text-white transition-colors"
                    >
                        <ArrowLeft className="w-6 h-6" />
                    </button>
                    <h1 className="text-2xl font-tech font-bold text-white tracking-wider flex items-center gap-3">
                        <Layers className="text-neon-blue" /> RECIPE MANAGEMENT
                    </h1>
                </div>
                <div className="text-sm font-mono text-slate-400">
                    TOTAL: <span className="text-neon-blue">{recipes.length}</span>
                </div>
            </div>

            <div className="flex-1 flex gap-6 min-h-0">
                {/* Left: Recipe List */}
                <div className="w-80 flex flex-col gap-4">
                    <div className="bg-slate-950/40 backdrop-blur-md border border-white/10 rounded-lg flex-1 overflow-hidden flex flex-col">
                        <div className="p-3 border-b border-white/10 bg-white/5 font-bold text-sm tracking-wider text-slate-300">
                            RECIPE LIST
                        </div>
                        <div className="flex-1 overflow-y-auto p-2 space-y-2 custom-scrollbar">
                            {recipes.map(r => (
                                <div
                                    key={r.id}
                                    onClick={() => handleSelect(r)}
                                    className={`
                                        p-3 rounded border cursor-pointer transition-all group
                                        ${selectedId === r.id
                                            ? 'bg-neon-blue/20 border-neon-blue text-white shadow-glow-blue'
                                            : 'bg-white/5 border-white/5 text-slate-400 hover:bg-white/10 hover:border-white/20'}
                                    `}
                                >
                                    <div className="font-bold text-sm mb-1">{r.name}</div>
                                    <div className="text-[10px] font-mono opacity-60 flex items-center gap-2">
                                        <Calendar className="w-3 h-3" /> {r.lastModified}
                                    </div>
                                </div>
                            ))}
                        </div>

                        {/* List Actions */}
                        <div className="p-3 border-t border-white/10 bg-black/20 grid grid-cols-3 gap-2">
                            <TechButton variant="default" className="flex justify-center" title="Add New">
                                <Plus className="w-4 h-4" />
                            </TechButton>
                            <TechButton variant="default" className="flex justify-center" title="Copy Selected">
                                <Copy className="w-4 h-4" />
                            </TechButton>
                            <TechButton variant="danger" className="flex justify-center" title="Delete Selected">
                                <Trash2 className="w-4 h-4" />
                            </TechButton>
                        </div>
                    </div>
                </div>

                {/* Right: Editor */}
                <div className="flex-1 bg-slate-950/40 backdrop-blur-md border border-white/10 rounded-lg flex flex-col overflow-hidden">
                    <div className="p-3 border-b border-white/10 bg-white/5 font-bold text-sm tracking-wider text-slate-300 flex justify-between items-center">
                        <span>RECIPE EDITOR</span>
                        {editedRecipe && <span className="text-neon-blue font-mono">{editedRecipe.id}</span>}
                    </div>

                    <div className="flex-1 p-6 overflow-y-auto custom-scrollbar">
                        {editedRecipe ? (
                            <div className="max-w-2xl space-y-6">
                                <div className="space-y-2">
                                    <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Recipe Name</label>
                                    <input
                                        type="text"
                                        value={editedRecipe.name}
                                        onChange={(e) => setEditedRecipe({ ...editedRecipe, name: e.target.value })}
                                        className="w-full bg-black/40 border border-white/10 rounded px-4 py-3 text-white focus:border-neon-blue focus:outline-none transition-colors font-mono"
                                    />
                                </div>

                                <div className="space-y-2">
                                    <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Description</label>
                                    <textarea
                                        className="w-full h-32 bg-black/40 border border-white/10 rounded px-4 py-3 text-white focus:border-neon-blue focus:outline-none transition-colors font-mono resize-none"
                                        placeholder="Enter recipe description..."
                                    ></textarea>
                                </div>

                                <div className="grid grid-cols-2 gap-6">
                                    <div className="space-y-2">
                                        <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Process Time (sec)</label>
                                        <input type="number" className="w-full bg-black/40 border border-white/10 rounded px-4 py-3 text-white focus:border-neon-blue focus:outline-none transition-colors font-mono" defaultValue="120" />
                                    </div>
                                    <div className="space-y-2">
                                        <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Temperature (°C)</label>
                                        <input type="number" className="w-full bg-black/40 border border-white/10 rounded px-4 py-3 text-white focus:border-neon-blue focus:outline-none transition-colors font-mono" defaultValue="24.5" />
                                    </div>
                                </div>

                                {/* Placeholder for more parameters */}
                                <div className="p-4 border border-dashed border-white/10 rounded bg-white/5 text-center text-slate-500 text-sm">
                                    Additional process parameters would go here...
                                </div>
                            </div>
                        ) : (
                            <div className="h-full flex flex-col items-center justify-center text-slate-500">
                                <FileText className="w-16 h-16 mb-4 opacity-20" />
                                <p>Select a recipe to edit</p>
                            </div>
                        )}
                    </div>

                    {/* Editor Actions */}
                    <div className="p-4 border-t border-white/10 bg-black/20 flex justify-end">
                        <TechButton
                            variant="green"
                            className="flex items-center gap-2 px-8"
                            onClick={handleSave}
                            disabled={!editedRecipe}
                        >
                            <Save className="w-4 h-4" /> SAVE CHANGES
                        </TechButton>
                    </div>
                </div>
            </div>
        </div>
    );
};
