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

interface RecipeData {
    idx?: number;
    Title?: string;
    Motion?: string;
    BCD_1D?: boolean;
    BCD_QR?: boolean;
    BCD_DM?: boolean;
    vOption?: number;
    vWMSInfo?: number;
    vSIDInfo?: number;
    vJobInfo?: number;
    vSIDConv?: number;
    Def_VName?: string;
    Def_MFG?: string;
    IgnoreOtherBarcode?: boolean;
    DisableCamera?: boolean;
    DisablePrinter?: boolean;
    CheckSIDExsit?: boolean;
    bOwnZPL?: boolean;
    IgnorePartNo?: boolean;
    IgnoreBatch?: boolean;
    BSave?: number;
    AutoOutConveyor?: number;
    [key: string]: any;
}

export const RecipePage: React.FC = () => {
    const navigate = useNavigate();
    const [recipes, setRecipes] = useState<Recipe[]>([]);
    const [selectedTitle, setSelectedTitle] = useState<string | null>(null);
    const [editedRecipe, setEditedRecipe] = useState<RecipeData | null>(null);
    const [isLoading, setIsLoading] = useState(true);
    const [hasChanges, setHasChanges] = useState(false);

    useEffect(() => {
        loadRecipes();
    }, []);

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

    const handleSelect = async (r: Recipe) => {
        if (hasChanges) {
            const confirmed = window.confirm("You have unsaved changes. Do you want to discard them?");
            if (!confirmed) return;
        }

        setSelectedTitle(r.name);
        try {
            const recipeStr = await comms.getRecipe(r.name);
            const recipeData = JSON.parse(recipeStr);
            setEditedRecipe(recipeData);
            setHasChanges(false);

            // Update recipes list with loaded data for preview
            setRecipes(prev => prev.map(recipe =>
                recipe.name === r.name ? { ...recipe, ...recipeData } : recipe
            ));
        } catch (e) {
            console.error("Failed to load recipe details", e);
            alert("Failed to load recipe details");
        }
    };

    const handleFieldChange = (field: string, value: any) => {
        if (!editedRecipe) return;
        setEditedRecipe({ ...editedRecipe, [field]: value });
        setHasChanges(true);
    };

    const handleSave = async () => {
        if (!editedRecipe || !selectedTitle) return;

        try {
            const result = await comms.saveRecipe(selectedTitle, JSON.stringify(editedRecipe));
            if (result.success) {
                setHasChanges(false);
                alert("Recipe saved successfully!");
                await loadRecipes();
            } else {
                alert(`Failed to save recipe: ${result.message}`);
            }
        } catch (error: any) {
            alert(`Error saving recipe: ${error.message || 'Unknown error'}`);
            console.error('Recipe save error:', error);
        }
    };

    const handleCopy = async () => {
        if (!selectedTitle) return;

        const selectedRecipe = recipes.find(r => r.name === selectedTitle);
        if (!selectedRecipe) return;

        const newName = prompt(`Copy "${selectedRecipe.name}" as:`, `${selectedRecipe.name}_Copy`);
        if (!newName || newName.trim() === '') return;

        try {
            const result = await comms.copyRecipe(selectedTitle, newName.trim());
            if (result.success && result.newRecipe) {
                await loadRecipes();
                await handleSelect(result.newRecipe);
                console.log("Recipe copied successfully:", result.newRecipe);
            } else {
                alert(`Failed to copy recipe: ${result.message}`);
            }
        } catch (error: any) {
            alert(`Error copying recipe: ${error.message || 'Unknown error'}`);
            console.error('Recipe copy error:', error);
        }
    };

    const handleDelete = async () => {
        if (!selectedTitle) return;

        const selectedRecipe = recipes.find(r => r.name === selectedTitle);
        if (!selectedRecipe) return;

        const confirmed = window.confirm(`Are you sure you want to delete "${selectedRecipe.name}"?`);
        if (!confirmed) return;

        try {
            const result = await comms.deleteRecipe(selectedTitle);
            if (result.success) {
                await loadRecipes();

                // Select first recipe or clear selection
                const newRecipeList = recipes.filter(r => r.name !== selectedTitle);
                if (newRecipeList.length > 0) {
                    await handleSelect(newRecipeList[0]);
                } else {
                    setSelectedTitle(null);
                    setEditedRecipe(null);
                }

                console.log("Recipe deleted successfully");
            } else {
                alert(`Failed to delete recipe: ${result.message}`);
            }
        } catch (error: any) {
            alert(`Error deleting recipe: ${error.message || 'Unknown error'}`);
            console.error('Recipe delete error:', error);
        }
    };

    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
                                        ${selectedTitle === r.name
                                            ? '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-2">{r.name}</div>

                                    {/* Motion Model */}
                                    {r.Motion && (
                                        <div className="text-[10px] font-mono opacity-70 mb-1">
                                            <span className="text-slate-500">Motion:</span> <span className="text-neon-green">{r.Motion}</span>
                                        </div>
                                    )}

                                    {/* Barcode Types */}
                                    {(r.BCD_1D !== undefined || r.BCD_QR !== undefined || r.BCD_DM !== undefined) && (
                                        <div className="flex gap-1 mb-1">
                                            {r.BCD_1D && (
                                                <span className="text-[9px] px-1.5 py-0.5 bg-neon-green/20 text-neon-green rounded border border-neon-green/30">1D</span>
                                            )}
                                            {r.BCD_QR && (
                                                <span className="text-[9px] px-1.5 py-0.5 bg-neon-blue/20 text-neon-blue rounded border border-neon-blue/30">QR</span>
                                            )}
                                            {r.BCD_DM && (
                                                <span className="text-[9px] px-1.5 py-0.5 bg-neon-yellow/20 text-neon-yellow rounded border border-neon-yellow/30">DM</span>
                                            )}
                                        </div>
                                    )}

                                    {/* Feature Flags */}
                                    {(r.DisableCamera || r.DisablePrinter || (r.AutoOutConveyor && r.AutoOutConveyor > 0)) && (
                                        <div className="flex flex-wrap gap-1 mb-1">
                                            {r.DisableCamera && (
                                                <span className="text-[8px] px-1 py-0.5 bg-red-500/20 text-red-400 rounded">No Cam</span>
                                            )}
                                            {r.DisablePrinter && (
                                                <span className="text-[8px] px-1 py-0.5 bg-red-500/20 text-red-400 rounded">No Print</span>
                                            )}
                                            {r.AutoOutConveyor && r.AutoOutConveyor > 0 && (
                                                <span className="text-[8px] px-1 py-0.5 bg-purple-500/20 text-purple-400 rounded">Auto Out</span>
                                            )}
                                        </div>
                                    )}

                                    {/* Last Modified */}
                                    <div className="text-[10px] font-mono opacity-50 flex items-center gap-1 mt-2 pt-2 border-t border-white/5">
                                        <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-2 gap-2">
                            <TechButton
                                variant="default"
                                className="flex justify-center"
                                title="Copy Selected"
                                onClick={handleCopy}
                                disabled={!selectedTitle}
                            >
                                <Copy className="w-4 h-4" />
                            </TechButton>
                            <TechButton
                                variant="danger"
                                className="flex justify-center"
                                title="Delete Selected"
                                onClick={handleDelete}
                                disabled={!selectedTitle}
                            >
                                <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.Title || selectedTitle}</span>}
                    </div>

                    <div className="flex-1 p-6 overflow-y-auto custom-scrollbar">
                        {editedRecipe ? (
                            <div className="max-w-3xl space-y-6">
                                {/* Basic Settings */}
                                <div className="space-y-4 p-4 border border-white/10 rounded-lg bg-white/5">
                                    <h3 className="text-xs font-bold text-neon-blue uppercase tracking-wider border-b border-white/10 pb-2">Basic Settings</h3>

                                    <div className="grid grid-cols-2 gap-4">
                                        <div className="space-y-2">
                                            <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Motion Model</label>
                                            <input
                                                type="text"
                                                value={editedRecipe.Motion || ''}
                                                onChange={(e) => handleFieldChange('Motion', e.target.value)}
                                                className="w-full bg-black/40 border border-white/10 rounded px-4 py-2 text-white focus:border-neon-blue focus:outline-none transition-colors font-mono text-sm"
                                            />
                                        </div>
                                        <div className="space-y-2">
                                            <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Auto Out Conveyor</label>
                                            <input
                                                type="number"
                                                value={editedRecipe.AutoOutConveyor || 0}
                                                onChange={(e) => handleFieldChange('AutoOutConveyor', parseInt(e.target.value) || 0)}
                                                className="w-full bg-black/40 border border-white/10 rounded px-4 py-2 text-white focus:border-neon-blue focus:outline-none transition-colors font-mono text-sm"
                                            />
                                        </div>
                                    </div>

                                    <div className="grid grid-cols-2 gap-4">
                                        <div className="space-y-2">
                                            <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Default Vendor Name</label>
                                            <input
                                                type="text"
                                                value={editedRecipe.Def_VName || ''}
                                                onChange={(e) => handleFieldChange('Def_VName', e.target.value)}
                                                className="w-full bg-black/40 border border-white/10 rounded px-4 py-2 text-white focus:border-neon-blue focus:outline-none transition-colors font-mono text-sm"
                                            />
                                        </div>
                                        <div className="space-y-2">
                                            <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Default MFG</label>
                                            <input
                                                type="text"
                                                value={editedRecipe.Def_MFG || ''}
                                                onChange={(e) => handleFieldChange('Def_MFG', e.target.value)}
                                                className="w-full bg-black/40 border border-white/10 rounded px-4 py-2 text-white focus:border-neon-blue focus:outline-none transition-colors font-mono text-sm"
                                            />
                                        </div>
                                    </div>
                                </div>

                                {/* Barcode Settings */}
                                <div className="space-y-4 p-4 border border-white/10 rounded-lg bg-white/5">
                                    <h3 className="text-xs font-bold text-neon-blue uppercase tracking-wider border-b border-white/10 pb-2">Barcode Settings</h3>
                                    <div className="grid grid-cols-3 gap-4">
                                        <label className="flex items-center gap-3 cursor-pointer">
                                            <div className={`w-5 h-5 rounded border transition-all flex items-center justify-center ${editedRecipe.BCD_1D ? 'bg-neon-green border-neon-green' : 'bg-black/40 border-white/20'}`}>
                                                {editedRecipe.BCD_1D && <Check className="w-3 h-3 text-black" />}
                                            </div>
                                            <span className="text-sm text-slate-300">1D Barcode</span>
                                            <input
                                                type="checkbox"
                                                checked={editedRecipe.BCD_1D || false}
                                                onChange={(e) => handleFieldChange('BCD_1D', e.target.checked)}
                                                className="hidden"
                                            />
                                        </label>
                                        <label className="flex items-center gap-3 cursor-pointer">
                                            <div className={`w-5 h-5 rounded border transition-all flex items-center justify-center ${editedRecipe.BCD_QR ? 'bg-neon-green border-neon-green' : 'bg-black/40 border-white/20'}`}>
                                                {editedRecipe.BCD_QR && <Check className="w-3 h-3 text-black" />}
                                            </div>
                                            <span className="text-sm text-slate-300">QR Code</span>
                                            <input
                                                type="checkbox"
                                                checked={editedRecipe.BCD_QR || false}
                                                onChange={(e) => handleFieldChange('BCD_QR', e.target.checked)}
                                                className="hidden"
                                            />
                                        </label>
                                        <label className="flex items-center gap-3 cursor-pointer">
                                            <div className={`w-5 h-5 rounded border transition-all flex items-center justify-center ${editedRecipe.BCD_DM ? 'bg-neon-green border-neon-green' : 'bg-black/40 border-white/20'}`}>
                                                {editedRecipe.BCD_DM && <Check className="w-3 h-3 text-black" />}
                                            </div>
                                            <span className="text-sm text-slate-300">Data Matrix</span>
                                            <input
                                                type="checkbox"
                                                checked={editedRecipe.BCD_DM || false}
                                                onChange={(e) => handleFieldChange('BCD_DM', e.target.checked)}
                                                className="hidden"
                                            />
                                        </label>
                                    </div>
                                </div>

                                {/* Feature Flags */}
                                <div className="space-y-4 p-4 border border-white/10 rounded-lg bg-white/5">
                                    <h3 className="text-xs font-bold text-neon-blue uppercase tracking-wider border-b border-white/10 pb-2">Feature Flags</h3>
                                    <div className="grid grid-cols-2 gap-3">
                                        {[
                                            { key: 'IgnoreOtherBarcode', label: 'Ignore Other Barcode' },
                                            { key: 'DisableCamera', label: 'Disable Camera' },
                                            { key: 'DisablePrinter', label: 'Disable Printer' },
                                            { key: 'CheckSIDExsit', label: 'Check SID Exist' },
                                            { key: 'bOwnZPL', label: 'Own ZPL' },
                                            { key: 'IgnorePartNo', label: 'Ignore Part No' },
                                            { key: 'IgnoreBatch', label: 'Ignore Batch' },
                                        ].map(({ key, label }) => (
                                            <label key={key} className="flex items-center gap-3 cursor-pointer">
                                                <div className={`w-5 h-5 rounded border transition-all flex items-center justify-center ${editedRecipe[key] ? 'bg-neon-green border-neon-green' : 'bg-black/40 border-white/20'}`}>
                                                    {editedRecipe[key] && <Check className="w-3 h-3 text-black" />}
                                                </div>
                                                <span className="text-sm text-slate-300">{label}</span>
                                                <input
                                                    type="checkbox"
                                                    checked={editedRecipe[key] || false}
                                                    onChange={(e) => handleFieldChange(key, e.target.checked)}
                                                    className="hidden"
                                                />
                                            </label>
                                        ))}
                                    </div>
                                </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-between items-center">
                        {hasChanges && (
                            <span className="text-xs text-neon-yellow font-mono animate-pulse">● UNSAVED CHANGES</span>
                        )}
                        <div className="ml-auto">
                            <TechButton
                                variant="green"
                                className="flex items-center gap-2 px-8"
                                onClick={handleSave}
                                disabled={!editedRecipe || !hasChanges}
                            >
                                <Save className="w-4 h-4" /> SAVE CHANGES
                            </TechButton>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};
