"use client";

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useAuth } from '@/context/AuthContext';
import { useRouter } from 'next/navigation';
import { Plus, Search, Edit, Trash2, Upload, X, Check, Save } from 'lucide-react';
import '@/styles/Auth.css';
import '@/styles/Admin.css';

// Types
interface Product {
    id: number;
    name: string;
    price: number;
    original_price?: number;
    stock_status: 'in_stock' | 'out_of_stock';
    in_stock: boolean; // Computed helper
    stock: number;
    images: string[];
    category_ids: number[];
    category_names: string[];
    created_at: string;
    // New fields
    description: string;
    width?: number;
    height?: number;
    depth?: number;
    brand?: string;
    product_condition: string;
    material?: string;
    color?: string;
    badge_text?: string;
    badge_color?: string;
    show_on_homepage?: boolean; // New field
}

interface Category {
    id: number;
    name: string;
}

export default function AdminProductsPage() {
    const { user, loading: authLoading } = useAuth();
    const router = useRouter();

    const [products, setProducts] = useState<Product[]>([]);
    const [categories, setCategories] = useState<Category[]>([]);
    const [loading, setLoading] = useState(true);
    const [searchTerm, setSearchTerm] = useState('');

    // Sort State
    const [sortConfig, setSortConfig] = useState<{ key: string; direction: 'asc' | 'desc' } | null>(null);

    // Modal State
    const [showModal, setShowModal] = useState(false);
    const [isEditing, setIsEditing] = useState(false);
    const [editId, setEditId] = useState<number | null>(null);
    const [saving, setSaving] = useState(false);
    const [isCreatingCategory, setIsCreatingCategory] = useState(false);
    const [newCategoryName, setNewCategoryName] = useState('');

    // Image Preview Modal
    const [previewImage, setPreviewImage] = useState<string | null>(null);

    // Form State
    const [formData, setFormData] = useState({
        name: '',
        description: '',
        price: '',
        original_price: '',
        stock_status: true, // true = in_stock
        stock: '1',
        width: '',
        height: '',
        depth: '',
        brand: '',
        product_condition: 'Good',
        material: '',
        color: '',
        badge_text: '',
        badge_color: '#ef4444', // Default red
        show_on_homepage: false,
        images: [] as string[],
        category_ids: [] as number[]
    });

    // Load Initial Data
    useEffect(() => {
        if (!authLoading && user?.role !== 'admin') {
            router.push('/login');
            return;
        }

        if (user?.role === 'admin') {
            fetchData();
        }
    }, [user, authLoading, router]);

    const fetchData = async () => {
        try {
            const token = localStorage.getItem('token') || sessionStorage.getItem('token');
            const [prodRes, catRes] = await Promise.all([
                fetch('/api/admin/products', { headers: { 'Authorization': `Bearer ${token}` } }),
                fetch('/api/categories') // Public endpoint usually fine, or create admin one
            ]);

            if (prodRes.ok) {
                const data = await prodRes.json();
                setProducts(data);
            }
            if (catRes.ok) {
                const data = await catRes.json();
                setCategories(data);
            }
        } catch (err) {
            console.error(err);
        } finally {
            setLoading(false);
        }
    };

    // Form Handlers
    const resetForm = () => {
        setFormData({
            name: '',
            description: '',
            price: '',
            original_price: '',
            stock_status: true,
            stock: '1',
            width: '',
            height: '',
            depth: '',
            brand: '',
            product_condition: 'Good',
            material: '',
            color: '',
            badge_text: '',
            badge_color: '#ef4444',
            show_on_homepage: false,
            images: [],
            category_ids: []
        });
        setIsEditing(false);
        setEditId(null);
    };

    const handleOpenAdd = () => {
        resetForm();
        setShowModal(true);
    };

    const handleEdit = (product: Product) => {
        setFormData({
            name: product.name,
            description: product.description || '',
            price: product.price.toString(),
            original_price: product.original_price?.toString() || '',
            stock_status: product.in_stock,
            stock: product.stock?.toString() || '0',
            width: product.width?.toString() || '',
            height: product.height?.toString() || '',
            depth: product.depth?.toString() || '',
            brand: product.brand || '',
            product_condition: product.product_condition,
            material: product.material || '',
            color: product.color || '',
            badge_text: product.badge_text || '',
            badge_color: product.badge_color || '#ef4444',
            show_on_homepage: !!product.show_on_homepage,
            images: product.images || [],
            category_ids: product.category_ids || []
        });
        setIsEditing(true);
        setEditId(product.id);
        setShowModal(true);
    };

    const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
        if (!e.target.files?.length) return;

        const uploadData = new FormData();
        Array.from(e.target.files).forEach(file => {
            uploadData.append('file', file);
        });

        try {
            const token = localStorage.getItem('token') || sessionStorage.getItem('token');
            const res = await fetch('/api/admin/upload', {
                method: 'POST',
                headers: { 'Authorization': `Bearer ${token}` },
                body: uploadData
            });

            if (res.ok) {
                const data = await res.json();
                setFormData(prev => ({
                    ...prev,
                    images: [...prev.images, ...data.urls]
                }));
            }
        } catch (_) {
            alert('Upload failed');
        }
    };

    const handleRemoveImage = (indexToRemove: number) => {
        setFormData(prev => ({
            ...prev,
            images: prev.images.filter((_, i) => i !== indexToRemove)
        }));
    };

    const handleSave = async (e: React.FormEvent) => {
        e.preventDefault();
        setSaving(true);

        try {
            const token = localStorage.getItem('token') || sessionStorage.getItem('token');
            const payload = {
                ...formData,
                stock_status: formData.stock_status, // api expects boolean or enum string mapping?
                // Map boolean to string manually or let api handle it if I update api
                // API expects: stock_status boolean in my previous thought? 
                // Let's check API: "stock_status ? 'in_stock' : 'out_of_stock'" OK so boolean is fine in body if var name matches
            };

            const url = isEditing ? `/api/admin/products/${editId}` : '/api/admin/products';
            const method = isEditing ? 'PUT' : 'POST';

            const res = await fetch(url, {
                method,
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(payload)
            });

            if (!res.ok) throw new Error('Failed to save');

            await fetchData(); // Refresh list
            setShowModal(false);
            resetForm();
        } catch (_) {
            alert('Kunde inte spara produkten');
        } finally {
            setSaving(false);
        }
    };

    const handleCreateCategory = async () => {
        if (!newCategoryName.trim()) return;

        try {
            const token = localStorage.getItem('token') || sessionStorage.getItem('token');
            const res = await fetch('/api/admin/categories', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ name: newCategoryName })
            });

            if (res.ok) {
                const data = await res.json();
                if (data.success && data.category) {
                    setCategories(prev => [...prev, data.category].sort((a, b) => a.name.localeCompare(b.name)));
                    setFormData(prev => ({
                        ...prev,
                        category_ids: [...prev.category_ids, data.category.id]
                    }));
                    setNewCategoryName('');
                    setIsCreatingCategory(false);
                }
            } else {
                alert('Kunde inte skapa kategori');
            }
        } catch (err) {
            console.error(err);
        }
    };

    const handleDelete = async (id: number) => {
        if (!confirm('Är du säker på att du vill ta bort den här produkten?')) return;

        try {
            const token = localStorage.getItem('token') || sessionStorage.getItem('token');
            const res = await fetch(`/api/admin/products/${id}`, {
                method: 'DELETE',
                headers: { 'Authorization': `Bearer ${token}` }
            });

            if (res.ok) {
                setProducts(prev => prev.filter(p => p.id !== id));
            } else {
                alert('Kunde inte radera produkten');
            }
        } catch (err) {
            console.error('Delete error', err);
            alert('Ett fel uppstod vid radering');
        }
    };

    const requestSort = (key: string) => {
        let direction: 'asc' | 'desc' = 'asc';
        if (sortConfig && sortConfig.key === key && sortConfig.direction === 'asc') {
            direction = 'desc';
        }
        setSortConfig({ key, direction });
    };

    // Filter & Sort Products
    const filteredProducts = products.filter(p => {
        const searchLower = searchTerm.toLowerCase();
        return (
            p.name.toLowerCase().includes(searchLower) ||
            p.brand?.toLowerCase().includes(searchLower) ||
            p.category_names.some(c => c.toLowerCase().includes(searchLower)) ||
            p.price.toString().includes(searchLower) ||
            p.product_condition.toLowerCase().includes(searchLower)
        );
    }).sort((a: Product, b: Product) => {
        if (!sortConfig) return 0;

        let aValue: string | number = '';
        let bValue: string | number = '';

        if (sortConfig.key === 'category') {
            aValue = a.category_names.join('');
            bValue = b.category_names.join('');
        } else {
            const valA = a[sortConfig.key as keyof Product];
            const valB = b[sortConfig.key as keyof Product];
            aValue = (typeof valA === 'number' || typeof valA === 'string') ? valA : String(valA);
            bValue = (typeof valB === 'number' || typeof valB === 'string') ? valB : String(valB);
        }

        if (aValue < bValue) {
            return sortConfig.direction === 'asc' ? -1 : 1;
        }
        if (aValue > bValue) {
            return sortConfig.direction === 'asc' ? 1 : -1;
        }
        return 0;
    });

    if (loading) return <div className="p-8 text-center">Laddar adminpanel...</div>;

    return (
        <div className="admin-container">
            <div className="admin-header">
                <div className="admin-title-group">
                    <h1>Produktlager</h1>
                    <p>Hantera {products.length} produkter i sortimentet</p>
                </div>
                <div className="admin-actions">
                    <Link href="/admin" className="auth-button secondary">
                        Tillbaka
                    </Link>
                    <button onClick={handleOpenAdd} className="auth-button">
                        <Plus size={18} className="mr-2" />
                        Ny Produkt
                    </button>
                </div>
            </div>

            <div className="admin-table-container">
                <div className="admin-controls">
                    <div className="relative flex-grow max-w-md">
                        <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" size={18} />
                        <input
                            type="text"
                            className="search-input pl-10"
                            placeholder="Sök på namn, märke..."
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                        />
                    </div>
                </div>

                <table className="admin-table">
                    <thead>
                        <tr>
                            <th onClick={() => requestSort('name')}>Produkt {sortConfig?.key === 'name' && (sortConfig.direction === 'asc' ? '↑' : '↓')}</th>
                            <th onClick={() => requestSort('price')}>Pris {sortConfig?.key === 'price' && (sortConfig.direction === 'asc' ? '↑' : '↓')}</th>
                            <th onClick={() => requestSort('stock')}>Lager {sortConfig?.key === 'stock' && (sortConfig.direction === 'asc' ? '↑' : '↓')}</th>
                            <th onClick={() => requestSort('category')}>Kategorier</th>
                            <th onClick={() => requestSort('product_condition')}>Skick</th>
                            <th onClick={() => requestSort('created_at')}>Datum {sortConfig?.key === 'created_at' && (sortConfig.direction === 'asc' ? '↑' : '↓')}</th>
                            <th className="text-right">Åtgärder</th>
                        </tr>
                    </thead>
                    <tbody>
                        {filteredProducts.map(product => (
                            <tr key={product.id}>
                                <td>
                                    <div className="flex items-center justify-between gap-3">
                                        <div className="flex-1">
                                            <div className="font-bold flex items-center gap-2">
                                                {product.name}
                                                {product.badge_text && (
                                                    <span
                                                        className="text-[10px] uppercase font-bold text-white px-1.5 py-0.5 rounded"
                                                        style={{ backgroundColor: product.badge_color || '#ef4444' }}
                                                    >
                                                        {product.badge_text}
                                                    </span>
                                                )}
                                            </div>
                                            <div className="text-xs text-gray-500">{product.brand}</div>
                                        </div>
                                        <div className="flex -space-x-2 overflow-hidden flex-shrink-0">
                                            {product.images.slice(0, 3).map((img, i) => (
                                                <img
                                                    key={i}
                                                    src={img}
                                                    alt=""
                                                    className="rounded-full border-2 border-white cursor-pointer hover:scale-110 transition-transform bg-gray-100"
                                                    style={{ width: '40px', height: '40px', objectFit: 'cover', minWidth: '40px' }}
                                                    onClick={(e) => {
                                                        e.stopPropagation();
                                                        setPreviewImage(img);
                                                    }}
                                                    title="Klicka för att förstora"
                                                />
                                            ))}
                                            {product.images.length > 3 && (
                                                <div
                                                    className="rounded-full bg-gray-100 border-2 border-white flex items-center justify-center text-xs font-bold text-gray-500"
                                                    style={{ width: '40px', height: '40px', minWidth: '40px' }}
                                                >
                                                    +{product.images.length - 3}
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                </td>
                                <td>{product.price} kr</td>
                                <td>
                                    {product.in_stock ? (
                                        <span className="status-badge status-instock">I Lager ({product.stock})</span>
                                    ) : (
                                        <span className="status-badge status-outstock">Slut</span>
                                    )}
                                </td>
                                <td className="text-sm max-w-[200px] truncate">{product.category_names.join(', ')}</td>
                                <td>{product.product_condition}</td>
                                <td className="text-sm text-gray-500">{new Date(product.created_at).toLocaleDateString('sv-SE')}</td>
                                <td className="text-right">
                                    <div className="flex justify-end gap-2">
                                        <button onClick={() => handleEdit(product)} className="p-2 hover:bg-gray-100 rounded text-blue-600">
                                            <Edit size={16} />
                                        </button>
                                        <button
                                            onClick={() => handleDelete(product.id)}
                                            className="p-2 hover:bg-gray-100 rounded text-red-600"
                                        >
                                            <Trash2 size={16} />
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>

                {filteredProducts.length === 0 && (
                    <div className="p-12 text-center text-gray-500">
                        Inga produkter hittades.
                    </div>
                )}
            </div>

            {/* PRODUCT MODAL */}
            {showModal && (
                <div className="modal-overlay" onClick={() => setShowModal(false)}>
                    <div className="modal-content product-modal bg-[var(--card-bg)] rounded-xl shadow-2xl" onClick={e => e.stopPropagation()}>
                        <div className="p-6 border-b flex justify-between items-center">
                            <h2 className="text-xl font-bold">{isEditing ? 'Redigera Produkt' : 'Ny Produkt'}</h2>
                            <button onClick={() => setShowModal(false)} className="p-2 hover:bg-gray-100 rounded-full">
                                <X size={20} />
                            </button>
                        </div>

                        <div className="modal-body scrollable">
                            <form onSubmit={handleSave} className="space-y-8">
                                {/* Section 1: Basic Info */}
                                <div>
                                    <h3 className="text-sm font-black uppercase tracking-wider text-gray-500 mb-4 border-b pb-2">Grundläggande Information</h3>
                                    <div className="form-grid">
                                        <div className="form-group form-full">
                                            <label className="form-label">Produktnamn *</label>
                                            <input
                                                required
                                                className="form-input"
                                                value={formData.name}
                                                onChange={e => setFormData({ ...formData, name: e.target.value })}
                                            />
                                        </div>

                                        <div className="form-group form-full">
                                            <label className="form-label">Beskrivning *</label>
                                            <textarea
                                                required
                                                className="form-input min-h-[100px]"
                                                value={formData.description}
                                                onChange={e => setFormData({ ...formData, description: e.target.value })}
                                            />
                                        </div>

                                        <div className="form-group">
                                            <label className="form-label">Märke (Brand)</label>
                                            <input
                                                className="form-input"
                                                value={formData.brand}
                                                onChange={e => setFormData({ ...formData, brand: e.target.value })}
                                                list="brands-list"
                                            />
                                            <datalist id="brands-list">
                                                <option value="Herman Miller" />
                                                <option value="Kinnarps" />
                                                <option value="IKEA" />
                                                <option value="HÅG" />
                                            </datalist>
                                        </div>

                                        <div className="form-group">
                                            <label className="form-label">Skick *</label>
                                            <select
                                                className="form-input"
                                                value={formData.product_condition}
                                                onChange={e => setFormData({ ...formData, product_condition: e.target.value })}
                                            >
                                                <option value="New">Ny</option>
                                                <option value="Excellent">Utmärkt</option>
                                                <option value="Good">Bra</option>
                                                <option value="Fair">Okej</option>
                                            </select>
                                        </div>

                                        {/* Badge Inputs */}
                                        <div className="form-group">
                                            <label className="form-label">Badge Text (Valfritt)</label>
                                            <input
                                                className="form-input"
                                                placeholder="T.ex. New Arrival, -30%"
                                                value={formData.badge_text}
                                                onChange={e => setFormData({ ...formData, badge_text: e.target.value })}
                                            />
                                        </div>
                                        <div className="flex items-center px-4 min-h-[3.5rem] border border-[var(--input-border)] bg-[var(--input-bg)] mb-2">
                                            <div className="flex-shrink-0">
                                                <input
                                                    type="color"
                                                    className="w-10 h-10 p-0 border-0 bg-transparent cursor-pointer rounded overflow-hidden"
                                                    value={formData.badge_color}
                                                    onChange={e => setFormData({ ...formData, badge_color: e.target.value })}
                                                    title="Välj färg"
                                                />
                                            </div>
                                            <div className="ml-6 flex flex-col justify-center">
                                                <label className="text-[10px] font-black uppercase tracking-widest text-[var(--text-secondary)] leading-none mb-1">Badge Färg</label>
                                                <span className="text-xs font-mono text-[var(--text-color)] uppercase font-bold">{formData.badge_color}</span>
                                            </div>
                                        </div>

                                        <div className="flex items-center gap-2 mb-2 p-3 border border-[var(--border-color)] bg-[var(--card-bg)] rounded">
                                            <input
                                                type="checkbox"
                                                id="show_on_homepage"
                                                checked={formData.show_on_homepage}
                                                onChange={e => setFormData({ ...formData, show_on_homepage: e.target.checked })}
                                                className="w-4 h-4"
                                            />
                                            <div className="flex flex-col">
                                                <label htmlFor="show_on_homepage" className="font-bold text-sm select-none cursor-pointer">Visa på startsidan</label>
                                                <span className="text-[10px] text-[var(--text-secondary)] uppercase font-bold tracking-wider">Max 8 visas totalt</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                {/* Section 2: Pricing & Stock */}
                                <div>
                                    <h3 className="text-sm font-black uppercase tracking-wider text-gray-500 mb-4 border-b pb-2">Pris & Lager</h3>
                                    <div className="form-grid">
                                        <div className="form-group">
                                            <label className="form-label">Pris (SEK) *</label>
                                            <input
                                                type="number"
                                                required
                                                className="form-input"
                                                value={formData.price}
                                                onChange={e => setFormData({ ...formData, price: e.target.value })}
                                            />
                                        </div>
                                        <div className="form-group">
                                            <label className="form-label">Originalpris (Nypris)</label>
                                            <input
                                                type="number"
                                                className="form-input"
                                                value={formData.original_price}
                                                onChange={e => setFormData({ ...formData, original_price: e.target.value })}
                                            />
                                        </div>

                                        <div className="form-group">
                                            <div className="flex items-center gap-2 mb-2">
                                                <input
                                                    type="checkbox"
                                                    id="stock_status"
                                                    checked={formData.stock_status}
                                                    onChange={e => setFormData({ ...formData, stock_status: e.target.checked })}
                                                    className="w-4 h-4"
                                                />
                                                <label htmlFor="stock_status" className="font-medium">Finns i lager</label>
                                            </div>
                                            {formData.stock_status && (
                                                <input
                                                    type="number"
                                                    className="form-input"
                                                    placeholder="Antal"
                                                    value={formData.stock}
                                                    onChange={e => setFormData({ ...formData, stock: e.target.value })}
                                                />
                                            )}
                                        </div>
                                    </div>
                                </div>

                                {/* Section 3: Attributes */}
                                <div>
                                    <h3 className="text-sm font-black uppercase tracking-wider text-gray-500 mb-4 border-b pb-2">Egenskaper & Mått</h3>
                                    <div className="form-grid">
                                        <div className="grid grid-cols-3 gap-2 form-full">
                                            <div>
                                                <label className="text-xs text-gray-500">Bredd (cm)</label>
                                                <input className="form-input" type="number" placeholder="B" value={formData.width} onChange={e => setFormData({ ...formData, width: e.target.value })} />
                                            </div>
                                            <div>
                                                <label className="text-xs text-gray-500">Höjd (cm)</label>
                                                <input className="form-input" type="number" placeholder="H" value={formData.height} onChange={e => setFormData({ ...formData, height: e.target.value })} />
                                            </div>
                                            <div>
                                                <label className="text-xs text-gray-500">Djup (cm)</label>
                                                <input className="form-input" type="number" placeholder="D" value={formData.depth} onChange={e => setFormData({ ...formData, depth: e.target.value })} />
                                            </div>
                                        </div>

                                        <div className="form-group">
                                            <label className="form-label">Material</label>
                                            <input
                                                className="form-input"
                                                placeholder="T.ex. Ek, Läder..."
                                                value={formData.material}
                                                onChange={e => setFormData({ ...formData, material: e.target.value })}
                                            />
                                        </div>
                                        <div className="form-group">
                                            <label className="form-label">Färg</label>
                                            <input
                                                className="form-input"
                                                placeholder="T.ex. Svart, Vit..."
                                                value={formData.color}
                                                onChange={e => setFormData({ ...formData, color: e.target.value })}
                                            />
                                        </div>
                                    </div>
                                </div>

                                {/* Section 4: Images */}
                                <div>
                                    <h3 className="text-sm font-black uppercase tracking-wider text-gray-500 mb-4 border-b pb-2">Bilder</h3>
                                    <div className="relative">
                                        <input
                                            type="file"
                                            multiple
                                            accept="image/*"
                                            onChange={handleUpload}
                                            className="hidden"
                                            id="file-upload"
                                        />
                                        <label htmlFor="file-upload" className="image-upload-area block">
                                            <Upload className="mx-auto mb-2 text-gray-400" size={32} />
                                            <p className="font-medium">Klicka för att ladda upp bilder</p>
                                            <p className="text-xs text-gray-400 mt-1">Stödjer JPG, PNG, WEBP</p>
                                        </label>
                                    </div>

                                    <div className="image-preview-grid">
                                        {formData.images.map((url, idx) => (
                                            <div key={idx} className="image-preview-card">
                                                <img src={url} alt={`Preview ${idx}`} />
                                                <button
                                                    type="button"
                                                    onClick={() => handleRemoveImage(idx)}
                                                    className="remove-image-btn"
                                                >
                                                    &times;
                                                </button>
                                                {idx === 0 && (
                                                    <div className="absolute bottom-0 left-0 right-0 bg-black/60 text-white text-[10px] text-center py-1 font-bold uppercase">
                                                        Omslag
                                                    </div>
                                                )}
                                            </div>
                                        ))}
                                    </div>
                                </div>

                                {/* Section 5: Categories */}
                                <div>
                                    <div className="flex justify-between items-center mb-4 border-b pb-2">
                                        <h3 className="text-sm font-black uppercase tracking-wider text-gray-500">Kategorier</h3>
                                        {!isCreatingCategory ? (
                                            <button
                                                type="button"
                                                onClick={() => setIsCreatingCategory(true)}
                                                className="text-xs font-bold text-blue-600 hover:text-blue-800 flex items-center"
                                            >
                                                <Plus size={14} className="mr-1" />
                                                Skapa Ny
                                            </button>
                                        ) : (
                                            <div className="flex items-center gap-2">
                                                <input
                                                    autoFocus
                                                    className="px-2 py-1 text-xs border rounded w-32"
                                                    placeholder="Namn..."
                                                    value={newCategoryName}
                                                    onChange={(e) => setNewCategoryName(e.target.value)}
                                                    onKeyDown={(e) => {
                                                        if (e.key === 'Enter') {
                                                            e.preventDefault();
                                                            handleCreateCategory();
                                                        }
                                                    }}
                                                />
                                                <button
                                                    type="button"
                                                    onClick={handleCreateCategory}
                                                    className="text-green-600 hover:text-green-800"
                                                >
                                                    <Check size={16} />
                                                </button>
                                                <button
                                                    type="button"
                                                    onClick={() => {
                                                        setIsCreatingCategory(false);
                                                        setNewCategoryName('');
                                                    }}
                                                    className="text-red-500 hover:text-red-700"
                                                >
                                                    <X size={16} />
                                                </button>
                                            </div>
                                        )}
                                    </div>

                                    <div className="flex flex-wrap gap-2">
                                        {categories.map(cat => (
                                            <label key={cat.id} className={`
                                                cursor-pointer px-3 py-1.5 rounded-full text-sm font-medium border transition-all
                                                ${formData.category_ids.includes(cat.id)
                                                    ? 'bg-black text-white border-black'
                                                    : 'bg-white text-gray-600 border-gray-200 hover:border-gray-400'}
                                            `}>
                                                <input
                                                    type="checkbox"
                                                    className="hidden"
                                                    checked={formData.category_ids.includes(cat.id)}
                                                    onChange={(e) => {
                                                        const checked = e.target.checked;
                                                        setFormData(prev => ({
                                                            ...prev,
                                                            category_ids: checked
                                                                ? [...prev.category_ids, cat.id]
                                                                : prev.category_ids.filter(id => id !== cat.id)
                                                        }));
                                                    }}
                                                />
                                                {cat.name}
                                            </label>
                                        ))}
                                    </div>
                                </div>

                                <div className="sticky bottom-0 flex justify-end gap-3 z-10">
                                    <button
                                        type="button"
                                        onClick={() => setShowModal(false)}
                                        className="auth-button secondary w-auto px-6"
                                    >
                                        Avbryt
                                    </button>
                                    <button
                                        type="submit"
                                        disabled={saving}
                                        className="auth-button success w-auto px-6"
                                    >
                                        <Save size={18} className="mr-2" />
                                        {saving ? 'Sparar...' : isEditing ? 'Uppdatera' : 'Spara Produkt'}
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            )}
            {/* IMAGE PREVIEW MODAL */}
            {previewImage && (
                <div
                    className="modal-overlay z-[2000]"
                    onClick={() => setPreviewImage(null)}
                >
                    <div className="relative max-w-4xl max-h-[90vh] p-2">
                        <button
                            className="absolute -top-10 right-0 text-white hover:text-gray-300 transition-colors"
                            onClick={() => setPreviewImage(null)}
                        >
                            <X size={32} />
                        </button>
                        <img
                            src={previewImage}
                            alt="Full preview"
                            className="max-w-full max-h-[90vh] object-contain rounded shadow-2xl"
                            onClick={(e) => e.stopPropagation()}
                        />
                    </div>
                </div>
            )}
        </div>
    );
}
