import AdminLayout from '@/Layouts/AdminLayout';
import { Head, useForm, router } from '@inertiajs/react';
import { Plus, Trash2, Edit2, Folder, Check } from 'lucide-react';
import { useState } from 'react';

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

export default function Index({ categories }: { categories: Category[] }) {
    const [editing, setEditing] = useState<Category | null>(null);

    const { data, setData, post, put, processing, errors, reset } = useForm({
        name: '',
    });

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        if (editing) {
            put(route('admin.categories.update', editing.id), {
                onSuccess: () => {
                    setEditing(null);
                    reset();
                }
            });
        } else {
            post(route('admin.categories.store'), {
                onSuccess: () => reset()
            });
        }
    };

    const handleEdit = (category: Category) => {
        setEditing(category);
        setData('name', category.name);
    };

    const handleDelete = (id: number) => {
        if (confirm('Delete this category? This will fail if it has active posts.')) {
            router.delete(route('admin.categories.destroy', id));
        }
    };

    return (
        <AdminLayout>
            <Head title="Blog Categories" />

            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-6 mb-10">
                <div>
                    <h1 className="font-display text-[1.5rem] md:text-[1.75rem] font-normal tracking-[-0.02em] text-ink leading-tight">
                        Blog Categories
                    </h1>
                    <p className="mt-2 text-[13px] md:text-[14px] text-[#8C92AC]">
                        Organize your insights for better discoverability.
                    </p>
                </div>
            </div>

            <div className="grid lg:grid-cols-12 gap-8">
                {/* Form */}
                <div className="lg:col-span-4 order-2">
                    <div className="bg-white rounded-[2rem] border border-[#E8E6DF] p-8 shadow-sm sticky top-24">
                        <h3 className="text-[15px] font-bold text-ink mb-6 flex items-center gap-2">
                            {editing ? <Edit2 className="h-4 w-4 text-primary" /> : <Plus className="h-4 w-4 text-primary" />}
                            {editing ? 'Edit Category' : 'New Category'}
                        </h3>
                        <form onSubmit={handleSubmit} className="space-y-6">
                            <div>
                                <label className="block text-[11px] font-bold uppercase tracking-wider text-[#8C92AC] mb-3">Category Name</label>
                                <input
                                    type="text"
                                    value={data.name}
                                    onChange={(e) => setData('name', e.target.value)}
                                    className="w-full h-12 rounded-xl border border-[#E8E6DF] bg-[#FAFAF8] px-5 text-[14px] font-medium outline-none focus:border-primary/50 transition-all placeholder:text-[#C0BDBA]"
                                    placeholder="e.g. Growth Marketing"
                                />
                                {errors.name && <p className="text-red-500 text-[11px] mt-2 font-medium">{errors.name}</p>}
                            </div>

                            <div className="flex flex-col gap-3">
                                <button
                                    type="submit"
                                    disabled={processing}
                                    className="w-full inline-flex h-12 items-center justify-center gap-2 rounded-xl bg-ink text-white text-[13px] font-bold hover:bg-primary transition-all shadow-lg shadow-ink/5 disabled:opacity-50"
                                >
                                    {editing ? <Check className="h-4 w-4" /> : <Plus className="h-4 w-4" />}
                                    {editing ? 'Update Category' : 'Create Category'}
                                </button>
                                {editing && (
                                    <button
                                        type="button"
                                        onClick={() => { setEditing(null); reset(); }}
                                        className="w-full h-12 rounded-xl border border-[#E8E6DF] text-[13px] font-bold text-ink hover:bg-[#FAFAF8] transition-all"
                                    >
                                        Cancel Edit
                                    </button>
                                )}
                            </div>
                        </form>
                    </div>
                </div>

                {/* List */}
                <div className="lg:col-span-8 order-1">
                    {/* Mobile View */}
                    <div className="grid gap-3 md:hidden mb-8">
                        {categories.length > 0 ? categories.map((cat) => (
                            <div key={cat.id} className="bg-white rounded-[1.5rem] border border-[#E8E6DF] p-5 shadow-sm">
                                <div className="flex items-center gap-4 mb-4">
                                    <div className="h-11 w-11 rounded-xl bg-[#F5F3EF] flex items-center justify-center text-ink border border-[#E8E6DF] flex-shrink-0">
                                        <Folder className="h-5 w-5 text-[#8C92AC]" />
                                    </div>
                                    <div className="flex-1 min-w-0">
                                        <p className="text-[14px] font-bold text-ink leading-tight">{cat.name}</p>
                                        <p className="text-[10px] text-[#8C92AC] font-bold mt-1.5 uppercase tracking-tighter">{cat.posts_count} Articles</p>
                                    </div>
                                </div>
                                <div className="flex items-center justify-between pt-4 border-t border-[#F0EDE8]">
                                    <button onClick={() => handleEdit(cat)} className="flex items-center gap-2 px-4 py-2 bg-[#F5F3EF] text-[11px] font-bold text-ink rounded-lg border border-[#E8E6DF]">
                                        <Edit2 className="h-3.5 w-3.5" /> Edit
                                    </button>
                                    <button onClick={() => handleDelete(cat.id)} className="p-2 text-[#8C92AC] hover:text-red-500">
                                        <Trash2 className="h-4 w-4" />
                                    </button>
                                </div>
                            </div>
                        )) : (
                            <div className="bg-white rounded-[1.5rem] border border-[#E8E6DF] p-12 text-center text-[13px] text-[#8C92AC]">No categories yet.</div>
                        )}
                    </div>

                    {/* Desktop View */}
                    <div className="hidden md:block bg-white rounded-[2rem] border border-[#E8E6DF] overflow-hidden shadow-sm">
                        <table className="w-full text-left">
                            <thead>
                                <tr className="border-b border-[#F0EDE8] bg-[#FAFAF8]">
                                    <th className="px-8 py-4 text-[10px] font-bold uppercase tracking-widest text-[#8C92AC]">Category</th>
                                    <th className="px-8 py-4 text-[10px] font-bold uppercase tracking-widest text-[#8C92AC]">Articles</th>
                                    <th className="px-8 py-4 text-[10px] font-bold uppercase tracking-widest text-[#8C92AC] text-right">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                {categories.length > 0 ? categories.map((cat) => (
                                    <tr key={cat.id} className="border-b border-[#F0EDE8] last:border-0 hover:bg-[#FAFAF8] transition-colors group">
                                        <td className="px-8 py-5">
                                            <div className="flex items-center gap-3">
                                                <div className="h-10 w-10 rounded-xl bg-secondary flex items-center justify-center text-ink">
                                                    <Folder className="h-4 w-4" />
                                                </div>
                                                <div>
                                                    <p className="text-sm font-bold text-ink">{cat.name}</p>
                                                    <p className="text-[10px] text-[#8C92AC] font-mono uppercase mt-0.5">{cat.slug}</p>
                                                </div>
                                            </div>
                                        </td>
                                        <td className="px-8 py-5">
                                            <span className="inline-flex items-center justify-center h-6 px-3 rounded-full bg-[#F5F3EF] border border-[#E8E6DF] text-[10px] font-bold text-ink">
                                                {cat.posts_count} Posts
                                            </span>
                                        </td>
                                        <td className="px-8 py-5 text-right">
                                            <div className="flex items-center justify-end gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                                                <button
                                                    onClick={() => handleEdit(cat)}
                                                    className="p-2 text-[#8C92AC] hover:text-ink hover:bg-secondary rounded-xl transition-all"
                                                >
                                                    <Edit2 className="h-4 w-4" />
                                                </button>
                                                <button
                                                    onClick={() => handleDelete(cat.id)}
                                                    className="p-2 text-[#8C92AC] hover:text-red-500 hover:bg-red-50 rounded-xl transition-all"
                                                >
                                                    <Trash2 className="h-4 w-4" />
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                )) : (
                                    <tr>
                                        <td colSpan={3} className="px-8 py-20 text-center text-sm text-[#8C92AC] italic">
                                            No categories yet. Add one to get started.
                                        </td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </AdminLayout>
    );
}
