import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { getProduct, createProduct, updateProduct, uploadImage } from '../api';
import { ArrowLeft, Save, Plus, X, Upload, Image as ImageIcon, Trash2 } from 'lucide-react';

export default function ProductEditor() {
    const { id } = useParams();
    const isNew = id === 'new';
    const navigate = useNavigate();

    const [loading, setLoading] = useState(!isNew); // If new, not loading
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState('');

    // Product State
    const [product, setProduct] = useState({
        name: '',
        type: 'simple',
        regular_price: '',
        description: '',
        short_description: '',
        sku: '',
        manage_stock: false,
        stock_quantity: 0,
        stock_status: 'instock',
        images: [],
        meta_data: []
    });

    useEffect(() => {
        if (!isNew) {
            fetchProduct();
        }
    }, [id]);

    const fetchProduct = async () => {
        try {
            const data = await getProduct(id);
            setProduct(data);
        } catch (err) {
            setError('Failed to load product');
        } finally {
            setLoading(false);
        }
    };

    const handleChange = (field, value) => {
        setProduct(prev => ({ ...prev, [field]: value }));
    };

    const handleMetaChange = (index, key, value) => {
        const newMeta = [...product.meta_data];
        newMeta[index] = { ...newMeta[index], key, value };
        setProduct(prev => ({ ...prev, meta_data: newMeta }));
    };

    const addMeta = () => {
        setProduct(prev => ({
            ...prev,
            meta_data: [...prev.meta_data, { key: '', value: '' }]
        }));
    };

    const removeMeta = (index) => {
        setProduct(prev => ({
            ...prev,
            meta_data: prev.meta_data.filter((_, i) => i !== index)
        }));
    };

    const handleImageUpload = async (e) => {
        const file = e.target.files[0];
        if (!file) return;

        setSaving(true); // Reuse saving state for upload indicator
        try {
            const media = await uploadImage(file);
            setProduct(prev => ({
                ...prev,
                images: [...prev.images, { id: media.id, src: media.source_url }]
            }));
        } catch (err) {
            alert('Failed to upload image');
        } finally {
            setSaving(false);
        }
    };

    const removeImage = (index) => {
        setProduct(prev => ({
            ...prev,
            images: prev.images.filter((_, i) => i !== index)
        }));
    };

    const handleSave = async (e) => {
        e.preventDefault();
        setSaving(true);
        setError('');
        try {
            if (isNew) {
                await createProduct(product);
            } else {
                await updateProduct(id, product);
            }
            navigate('/dashboard');
        } catch (err) {
            setError(err.response?.data?.detail || 'Failed to save product');
        } finally {
            setSaving(false);
        }
    };

    if (loading) return <div className="text-center text-white mt-10">Loading...</div>;

    return (
        <div className="min-h-screen bg-gray-900 text-gray-100 p-8">
            <div className="max-w-4xl mx-auto">
                <div className="flex items-center justify-between mb-8">
                    <button onClick={() => navigate('/dashboard')} className="flex items-center text-gray-400 hover:text-white transition">
                        <ArrowLeft className="h-5 w-5 mr-1" />
                        Back to Dashboard
                    </button>
                    <h1 className="text-2xl font-bold">{isNew ? 'Create New Product' : 'Edit Product'}</h1>
                    <button
                        onClick={handleSave}
                        disabled={saving}
                        className="flex items-center bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-lg transition disabled:opacity-50"
                    >
                        <Save className="h-5 w-5 mr-2" />
                        {saving ? 'Saving...' : 'Save Product'}
                    </button>
                </div>

                {error && (
                    <div className="bg-red-900/50 border border-red-500 text-red-200 p-4 rounded-lg mb-6">
                        {error}
                    </div>
                )}

                <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
                    {/* Main Info */}
                    <div className="md:col-span-2 space-y-6">
                        <div className="bg-gray-800 p-6 rounded-xl border border-gray-700 shadow-lg">
                            <h2 className="text-lg font-semibold mb-4 text-blue-400">General Information</h2>
                            <div className="space-y-4">
                                <div>
                                    <label className="block text-sm font-medium text-gray-400 mb-1">Product Name</label>
                                    <input
                                        type="text"
                                        className="w-full bg-gray-700 border-gray-600 rounded-md p-2 text-white outline-none focus:ring-2 focus:ring-blue-500"
                                        value={product.name}
                                        onChange={(e) => handleChange('name', e.target.value)}
                                    />
                                </div>
                                <div className="grid grid-cols-2 gap-4">
                                    <div>
                                        <label className="block text-sm font-medium text-gray-400 mb-1">Regular Price</label>
                                        <input
                                            type="text"
                                            className="w-full bg-gray-700 border-gray-600 rounded-md p-2 text-white outline-none focus:ring-2 focus:ring-blue-500"
                                            value={product.regular_price}
                                            onChange={(e) => handleChange('regular_price', e.target.value)}
                                        />
                                    </div>
                                    <div>
                                        <label className="block text-sm font-medium text-gray-400 mb-1">SKU</label>
                                        <input
                                            type="text"
                                            className="w-full bg-gray-700 border-gray-600 rounded-md p-2 text-white outline-none focus:ring-2 focus:ring-blue-500"
                                            value={product.sku || ''}
                                            onChange={(e) => handleChange('sku', e.target.value)}
                                        />
                                    </div>
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-400 mb-1">Short Description</label>
                                    <textarea
                                        rows="3"
                                        className="w-full bg-gray-700 border-gray-600 rounded-md p-2 text-white outline-none focus:ring-2 focus:ring-blue-500"
                                        value={product.short_description}
                                        onChange={(e) => handleChange('short_description', e.target.value)}
                                    />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-400 mb-1">Full Description</label>
                                    <textarea
                                        rows="5"
                                        className="w-full bg-gray-700 border-gray-600 rounded-md p-2 text-white outline-none focus:ring-2 focus:ring-blue-500"
                                        value={product.description}
                                        onChange={(e) => handleChange('description', e.target.value)}
                                    />
                                </div>
                            </div>
                        </div>

                        {/* Inventory */}
                        <div className="bg-gray-800 p-6 rounded-xl border border-gray-700 shadow-lg">
                            <h2 className="text-lg font-semibold mb-4 text-blue-400">Inventory</h2>
                            <div className="space-y-4">
                                <div className="flex items-center">
                                    <input
                                        type="checkbox"
                                        id="manage_stock"
                                        checked={product.manage_stock}
                                        onChange={(e) => handleChange('manage_stock', e.target.checked)}
                                        className="h-4 w-4 bg-gray-700 border-gray-600 rounded text-blue-600 focus:ring-blue-500"
                                    />
                                    <label htmlFor="manage_stock" className="ml-2 text-sm font-medium text-gray-300">Enable Stock Management</label>
                                </div>
                                {product.manage_stock && (
                                    <div>
                                        <label className="block text-sm font-medium text-gray-400 mb-1">Stock Quantity</label>
                                        <input
                                            type="number"
                                            className="w-full bg-gray-700 border-gray-600 rounded-md p-2 text-white outline-none focus:ring-2 focus:ring-blue-500"
                                            value={product.stock_quantity || 0}
                                            onChange={(e) => handleChange('stock_quantity', parseInt(e.target.value))}
                                        />
                                    </div>
                                )}
                                <div>
                                    <label className="block text-sm font-medium text-gray-400 mb-1">Stock Status</label>
                                    <select
                                        className="w-full bg-gray-700 border-gray-600 rounded-md p-2 text-white outline-none focus:ring-2 focus:ring-blue-500"
                                        value={product.stock_status}
                                        onChange={(e) => handleChange('stock_status', e.target.value)}
                                    >
                                        <option value="instock">In Stock</option>
                                        <option value="outofstock">Out of Stock</option>
                                        <option value="onbackorder">On Backorder</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Sidebar */}
                    <div className="space-y-6">
                        {/* Images */}
                        <div className="bg-gray-800 p-6 rounded-xl border border-gray-700 shadow-lg">
                            <h2 className="text-lg font-semibold mb-4 text-blue-400">Product Images</h2>
                            <div className="space-y-4">
                                <div className="grid grid-cols-2 gap-2">
                                    {product.images.map((img, idx) => (
                                        <div key={idx} className="relative group">
                                            <img src={img.src} alt="" className="w-full h-24 object-cover rounded-md border border-gray-600" />
                                            <button
                                                onClick={() => removeImage(idx)}
                                                className="absolute top-1 right-1 bg-red-600 text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition"
                                            >
                                                <X className="h-3 w-3" />
                                            </button>
                                        </div>
                                    ))}
                                </div>
                                <label className="flex flex-col items-center justify-center w-full h-32 border-2 border-gray-600 border-dashed rounded-lg cursor-pointer hover:bg-gray-750 transition">
                                    <div className="flex flex-col items-center justify-center pt-5 pb-6">
                                        <Upload className="w-8 h-8 mb-2 text-gray-400" />
                                        <p className="text-xs text-gray-500">Click to upload image</p>
                                    </div>
                                    <input type="file" className="hidden" accept="image/*" onChange={handleImageUpload} />
                                </label>
                            </div>
                        </div>

                        {/* Meta Data / Plugins */}
                        {/* Meta Data / Plugins (Grouped) */}
                        <div className="bg-gray-800 p-6 rounded-xl border border-gray-700 shadow-lg">
                            <div className="flex justify-between items-center mb-4">
                                <h2 className="text-lg font-semibold text-blue-400">Plugin Settings</h2>
                                <button onClick={addMeta} className="text-blue-400 hover:text-blue-300 text-sm flex items-center">
                                    <Plus className="h-4 w-4 mr-1" />
                                    Add Custom Meta
                                </button>
                            </div>

                            <div className="space-y-6 max-h-[600px] overflow-y-auto pr-2 custom-scrollbar">
                                {(() => {
                                    // Grouping Logic
                                    const groups = {
                                        'Yoast SEO': { prefix: '_yoast_', items: [], icon: '🔍' },
                                        'Product Bundles': { prefix: '_bundle', items: [], icon: '📦' },
                                        'Facebook': { prefix: 'fb_', items: [], icon: 'f' },
                                        'Google Listings': { prefix: '_wc_gla', items: [], icon: 'G' },
                                        'Tax Settings': { prefix: '_tax', items: [], icon: '💰' },
                                        'Other': { prefix: '', items: [], icon: '🔧' }
                                    };

                                    // Helper to find readable name
                                    const getReadableName = (key) => {
                                        const names = {
                                            '_yoast_wpseo_title': 'SEO Title',
                                            '_yoast_wpseo_metadesc': 'Meta Description',
                                            '_yoast_wpseo_focuskw': 'Focus Keyword',
                                            '_regular_price': 'Regular Price (Meta)',
                                            '_price': 'Price (Meta)',
                                            '_sku': 'SKU (Meta)',
                                            '_tax_status': 'Tax Status',
                                            '_tax_class': 'Tax Class',
                                            '_bundle_data': 'Bundle Configuration',
                                            '_bundled_items': 'Bundled Item IDs'
                                        };
                                        return names[key] || key;
                                    };

                                    // Sort items into groups
                                    product.meta_data.forEach((meta, idx) => {
                                        if (meta.key.startsWith('_')) {
                                            // System/Hidden keys often start with _
                                        }

                                        let placed = false;
                                        for (const [groupName, config] of Object.entries(groups)) {
                                            if (groupName !== 'Other' && meta.key.includes(config.prefix)) {
                                                groups[groupName].items.push({ ...meta, originalIndex: idx });
                                                placed = true;
                                                break;
                                            }
                                        }
                                        if (!placed) {
                                            groups['Other'].items.push({ ...meta, originalIndex: idx });
                                        }
                                    });

                                    // Render Groups
                                    return Object.entries(groups).map(([groupName, config]) => {
                                        if (config.items.length === 0) return null;

                                        return (
                                            <div key={groupName} className="bg-gray-750/50 rounded-lg p-3 border border-gray-600/50">
                                                <h3 className="text-sm font-bold text-gray-300 mb-3 flex items-center uppercase tracking-wider">
                                                    <span className="mr-2 opacity-75">{config.icon}</span>
                                                    {groupName}
                                                </h3>
                                                <div className="space-y-3">
                                                    {config.items.map((meta) => (
                                                        <div key={meta.originalIndex} className="bg-gray-900/50 p-3 rounded border border-gray-700 relative group transition hover:border-blue-500/30">
                                                            <div className="space-y-1">
                                                                <div className="flex justify-between items-center mb-1">
                                                                    <label className="text-xs font-semibold text-blue-300" title={meta.key}>
                                                                        {getReadableName(meta.key)}
                                                                    </label>
                                                                    <span className="text-[10px] text-gray-600 font-mono hidden group-hover:block">{meta.key}</span>
                                                                </div>

                                                                {typeof meta.value === 'object' ? (
                                                                    <div className="text-xs text-gray-500 italic bg-gray-900 p-2 rounded">
                                                                        Complex Data (Editing disabled for safety)
                                                                        <details className="mt-1">
                                                                            <summary className="cursor-pointer hover:text-white">View JSON</summary>
                                                                            <pre className="mt-1 overflow-x-auto">{JSON.stringify(meta.value, null, 2)}</pre>
                                                                        </details>
                                                                    </div>
                                                                ) : meta.value && meta.value.length > 50 ? (
                                                                    <textarea
                                                                        className="w-full bg-gray-800 border-gray-700 rounded px-2 py-1 text-sm text-gray-200 outline-none focus:ring-1 focus:ring-blue-500 min-h-[60px]"
                                                                        value={meta.value}
                                                                        onChange={(e) => handleMetaChange(meta.originalIndex, e.target.value, meta.value)} // Corrected handler signature
                                                                    />
                                                                ) : (
                                                                    <input
                                                                        type="text"
                                                                        className="w-full bg-gray-800 border-gray-700 rounded px-2 py-1 text-sm text-gray-200 outline-none focus:ring-1 focus:ring-blue-500"
                                                                        value={meta.value}
                                                                        onChange={(e) => handleMetaChange(meta.originalIndex, meta.key, e.target.value)}
                                                                    />
                                                                )}
                                                            </div>
                                                            <button
                                                                onClick={() => removeMeta(meta.originalIndex)}
                                                                className="absolute top-2 right-2 text-gray-500 hover:text-red-400 opacity-0 group-hover:opacity-100 transition p-1"
                                                                title="Remove Field"
                                                            >
                                                                <Trash2 className="h-4 w-4" />
                                                            </button>
                                                        </div>
                                                    ))}
                                                </div>
                                            </div>
                                        );
                                    });
                                })()}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}
