"use client";

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

interface Category {
    id: number;
    name: string;
    description: string;
    image_url?: string;
    show_on_homepage: boolean;
    created_at: string;
}

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

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

    const [showModal, setShowModal] = useState(false);
    const [isEditing, setIsEditing] = useState(false);
    const [editId, setEditId] = useState<number | null>(null);
    const [saving, setSaving] = useState(false);
    const [uploading, setUploading] = useState(false);

    // Form State
    const [formData, setFormData] = useState({
        name: '',
        description: '',
        image_url: '',
        show_on_homepage: false
    });

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

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

    const fetchCategories = async () => {
        try {
            const res = await fetch('/api/categories');
            if (res.ok) {
                const data = await res.json();
                setCategories(data);
            }
        } catch (err) {
            console.error(err);
        } finally {
            setLoading(false);
        }
    };

    const resetForm = () => {
        setFormData({
            name: '',
            description: '',
            image_url: '',
            show_on_homepage: false
        });
        setIsEditing(false);
        setEditId(null);
    };

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

    const handleEdit = (category: Category) => {
        setFormData({
            name: category.name,
            description: category.description || '',
            image_url: category.image_url || '',
            show_on_homepage: category.show_on_homepage || false
        });
        setIsEditing(true);
        setEditId(category.id);
        setShowModal(true);
    };

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

        setUploading(true);
        const uploadData = new FormData();
        uploadData.append('file', e.target.files[0]);

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

            if (res.ok) {
                const data = await res.json();
                setFormData(prev => ({
                    ...prev,
                    image_url: data.url
                }));
            } else {
                alert('Uppladdning misslyckades');
            }
        } catch (_) {
            alert('Uppladdning misslyckades');
        } finally {
            setUploading(false);
        }
    };

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

        try {
            const token = localStorage.getItem('token') || sessionStorage.getItem('token');
            const url = isEditing ? `/api/admin/categories/${editId}` : '/api/admin/categories';
            const method = isEditing ? 'PUT' : 'POST';

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

            if (!res.ok) {
                const data = await res.json();
                throw new Error(data.error || 'Failed to save');
            }

            await fetchCategories();
            setShowModal(false);
            resetForm();
        } catch (err: unknown) {
            const message = err instanceof Error ? err.message : 'Kunde inte spara kategorin';
            alert(message);
        } finally {
            setSaving(false);
        }
    };

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

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

            if (res.ok) {
                setCategories(prev => prev.filter(c => c.id !== id));
            } else {
                const data = await res.json();
                alert(data.error || 'Kunde inte radera kategorin');
            }
        } catch (err) {
            console.error('Delete error', err);
            alert('Ett fel uppstod vid radering');
        }
    };

    const filteredCategories = categories.filter(c =>
        c.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        (c.description && c.description.toLowerCase().includes(searchTerm.toLowerCase()))
    );

    if (loading) return <div className="p-8 text-center text-[var(--text-color)]">Laddar kategorier...</div>;

    return (
        <div className="admin-container">
            <div className="admin-header">
                <div className="admin-title-group">
                    <h1>Kategorier</h1>
                    <p>Hantera {categories.length} produktkategorier</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 Kategori
                    </button>
                </div>
            </div>

            <div className="admin-table-container">
                <div className="admin-controls">
                    <div className="relative flex-grow max-w-md">
                        <div className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400">
                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="8" /><path d="m21 21-4.3-4.3" /></svg>
                        </div>
                        <input
                            type="text"
                            className="search-input"
                            placeholder="Sök kategori..."
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                        />
                    </div>
                </div>

                <table className="admin-table">
                    <thead>
                        <tr>
                            <th>Bild</th>
                            <th>Namn</th>
                            <th>Beskrivning</th>
                            <th>Startsida</th>
                            <th>Skapad</th>
                            <th className="text-right">Åtgärder</th>
                        </tr>
                    </thead>
                    <tbody>
                        {filteredCategories.map(category => (
                            <tr key={category.id}>
                                <td>
                                    {category.image_url ? (
                                        <img src={category.image_url} alt={category.name} className="w-12 h-12 object-cover rounded" />
                                    ) : (
                                        <div className="w-12 h-12 bg-gray-200 rounded flex items-center justify-center text-gray-400 text-xs">-</div>
                                    )}
                                </td>
                                <td className="font-bold">{category.name}</td>
                                <td className="text-sm text-gray-500 max-w-[300px] truncate">
                                    {category.description || '-'}
                                </td>
                                <td>
                                    {category.show_on_homepage ? (
                                        <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                            Visas
                                        </span>
                                    ) : (
                                        <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-600">
                                            Dold
                                        </span>
                                    )}
                                </td>
                                <td className="text-sm text-gray-400">
                                    {new Date(category.created_at).toLocaleDateString('sv-SE')}
                                </td>
                                <td className="text-right">
                                    <div className="flex justify-end gap-2">
                                        <button onClick={() => handleEdit(category)} className="p-2 hover:bg-gray-100 rounded text-blue-600">
                                            <Edit size={16} />
                                        </button>
                                        <button
                                            onClick={() => handleDelete(category.id)}
                                            className="p-2 hover:bg-gray-100 rounded text-red-600"
                                        >
                                            <Trash2 size={16} />
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>

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

            {/* CATEGORY 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 bg-[var(--card-bg)] rounded-t-xl">
                            <h2 className="text-xl font-bold">{isEditing ? 'Redigera Kategori' : 'Ny Kategori'}</h2>
                            <button onClick={() => setShowModal(false)} className="p-2 hover:bg-gray-100 rounded-full">
                                <X size={20} />
                            </button>
                        </div>

                        <div className="modal-body scrollable p-6">
                            <form onSubmit={handleSave} className="space-y-6">
                                <div className="form-group">
                                    <label className="form-label">Kategorinamn *</label>
                                    <input
                                        required
                                        className="form-input"
                                        value={formData.name}
                                        onChange={e => setFormData({ ...formData, name: e.target.value })}
                                    />
                                </div>

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

                                <div className="form-group">
                                    <label className="form-label">Kategoribild</label>
                                    <div className="flex items-center gap-4">
                                        <label className="auth-button secondary cursor-pointer flex items-center gap-2">
                                            <Upload size={18} />
                                            {uploading ? 'Laddar upp...' : 'Välj bild'}
                                            <input
                                                type="file"
                                                accept="image/*"
                                                className="hidden"
                                                onChange={handleUpload}
                                                disabled={uploading}
                                            />
                                        </label>
                                        {formData.image_url && (
                                            <div className="relative">
                                                <img src={formData.image_url} alt="Preview" className="w-24 h-24 object-cover rounded border" />
                                                <button
                                                    type="button"
                                                    onClick={() => setFormData({ ...formData, image_url: '' })}
                                                    className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1"
                                                >
                                                    <X size={12} />
                                                </button>
                                            </div>
                                        )}
                                    </div>
                                    <p className="text-xs text-gray-500 mt-1">Ladda upp en bild för kategorin (visas på startsidan)</p>
                                </div>

                                <div className="form-group">
                                    <label className="flex items-center gap-3 cursor-pointer">
                                        <input
                                            type="checkbox"
                                            checked={formData.show_on_homepage}
                                            onChange={e => setFormData({ ...formData, show_on_homepage: e.target.checked })}
                                            className="w-5 h-5 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                                        />
                                        <span className="form-label mb-0">Visa på startsidan</span>
                                    </label>
                                    <p className="text-xs text-gray-500 mt-1">Max 8 kategorier kan visas på startsidan</p>
                                </div>

                                <div className="sticky bottom-0 bg-[var(--card-bg)]/80 backdrop-blur-md pt-6 pb-2 mt-8 flex justify-end gap-3 z-10 rounded-b-xl border-t border-[var(--border-color)]">
                                    <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 Kategori'}
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
