import React, { useState } from 'react';
import { Link, router } from '@inertiajs/react';
import { AdminLayout } from '../AdminLayout';
import { SEOHead } from '@/Components/SEOHead';
import { Pagination } from '@/Components/Pagination';
import { ConfirmDeleteModal } from '@/Components/ConfirmDeleteModal';
import { formatCustomDate } from '@/lib/utils';
import { Plus, SquarePen, Trash2, Eye, Sparkles, RefreshCw, X, CheckCircle2, AlertCircle, ExternalLink, Search } from 'lucide-react';

interface BlogIndexProps {
    posts: any;
    categories?: any[];
    freeModels?: any[];
    filters?: {
        search?: string;
        category?: string;
        status?: string;
    };
}

export default function Index({ posts, categories = [], freeModels = [], filters = {} }: BlogIndexProps) {
    const [search, setSearch] = useState(filters.search || '');
    const [categoryFilter, setCategoryFilter] = useState(filters.category || 'all');
    const [statusFilter, setStatusFilter] = useState(filters.status || 'all');
    const [deleteId, setDeleteId] = useState<number | null>(null);
    const [aiModalOpen, setAiModalOpen] = useState(false);
    const [aiTopic, setAiTopic] = useState('');
    const [aiCategory, setAiCategory] = useState('all');
    const [aiModel, setAiModel] = useState('openrouter/free');
    const [aiStatus, setAiStatus] = useState('published');
    const [aiLoading, setAiLoading] = useState(false);
    const [aiResult, setAiResult] = useState<{ success: boolean; message: string; url?: string } | null>(null);

    const postsList = posts.data ? posts.data : posts;

    const handleFilterSubmit = (e?: React.FormEvent) => {
        if (e) e.preventDefault();
        router.get('/admin/blog', {
            search: search || undefined,
            category: categoryFilter !== 'all' ? categoryFilter : undefined,
            status: statusFilter !== 'all' ? statusFilter : undefined,
        }, {
            preserveState: true,
            preserveScroll: true,
        });
    };

    const handleResetFilters = () => {
        setSearch('');
        setCategoryFilter('all');
        setStatusFilter('all');
        router.get('/admin/blog');
    };


    const handleDelete = () => {
        if (deleteId) {
            router.delete(`/admin/blog/${deleteId}`);
        }
    };

    const handleAiGenerate = async (e: React.FormEvent) => {
        e.preventDefault();
        setAiLoading(true);
        setAiResult(null);

        try {
            const res = await fetch('/admin/ai/generate-blog-post', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement)?.content || '',
                    'Accept': 'application/json',
                },
                body: JSON.stringify({
                    category_slug: aiCategory,
                    topic: aiTopic || null,
                    status: aiStatus,
                    model: aiModel,
                }),
            });

            const text = await res.text();
            let data: any;
            try {
                data = JSON.parse(text);
            } catch {
                data = {
                    success: false,
                    message: `Server returned an invalid response (Status: ${res.status}). Please check OpenRouter connection in Settings.`,
                };
            }

            setAiResult(data);

            if (data.success) {
                setAiTopic('');
                router.reload({ only: ['posts'] });
            }
        } catch (err: any) {
            setAiResult({
                success: false,
                message: err.message || 'Generation failed. Check server logs.',
            });
        } finally {
            setAiLoading(false);
        }
    };


    const modelsList = freeModels.length > 0 ? freeModels : [
        { id: 'openrouter/free', name: 'OpenRouter Free Auto-Router (Recommended)' },
        { id: 'google/gemma-4-31b-it:free', name: 'Google Gemma 4 31B (Free)' },
        { id: 'nvidia/nemotron-3-super-120b-a12b:free', name: 'NVIDIA Nemotron 3 Super 120B (Free)' },
    ];

    return (
        <AdminLayout title="Blog CMS Management">
            <SEOHead title="Blog Management | Tech in Soul Admin" description="Publish, edit, schedule, and organize technical blog posts and articles." />

            <div className="w-full space-y-6">
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                    <div>
                        <h2 className="text-xl font-bold text-white">Articles & Insights</h2>
                        <p className="text-xs text-slate-400">Publish, schedule, and edit technical blog articles with manual writing or OpenRouter AI.</p>
                    </div>
                    <div className="flex items-center gap-3">
                        <button
                            type="button"
                            onClick={() => {
                                setAiModalOpen(true);
                                setAiResult(null);
                            }}
                            className="px-4 py-2 rounded-xl text-xs font-bold bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-500 hover:to-indigo-500 text-white shadow-lg shadow-indigo-500/20 border border-purple-400/30 flex items-center gap-2 transition-all"
                        >
                            <Sparkles className="w-4 h-4 text-yellow-300" /> ✨ AI Generate Article
                        </button>
                        <Link href="/admin/blog/create" className="btn-aqua px-4 py-2 rounded-xl text-xs font-bold flex items-center gap-1.5">
                            <Plus className="w-4 h-4" /> Write New Article
                        </Link>
                    </div>
                </div>

                {/* Search & Filter Bar */}
                <div className="glass-card rounded-2xl p-4 border border-slate-800">
                    <form onSubmit={handleFilterSubmit} className="flex flex-col md:flex-row items-center gap-3">
                        <div className="relative flex-grow w-full">
                            <Search className="w-4 h-4 text-slate-400 absolute left-3.5 top-1/2 -translate-y-1/2" />
                            <input
                                type="text"
                                value={search}
                                onChange={(e) => setSearch(e.target.value)}
                                placeholder="Search articles by title, slug, or excerpt..."
                                className="w-full bg-[#060B18] border border-slate-800 rounded-xl pl-10 pr-4 py-2 text-xs text-white placeholder-slate-500 focus:outline-none focus:border-[#00F2FE]"
                            />
                        </div>

                        <div className="flex items-center gap-2 w-full md:w-auto">
                            <select
                                value={categoryFilter}
                                onChange={(e) => setCategoryFilter(e.target.value)}
                                className="bg-[#060B18] border border-slate-800 rounded-xl px-3 py-2 text-xs text-slate-300 focus:outline-none focus:border-[#00F2FE]"
                            >
                                <option value="all">All Categories</option>
                                {categories.map((cat: any) => (
                                    <option key={cat.id} value={cat.id}>{cat.name}</option>
                                ))}
                            </select>

                            <select
                                value={statusFilter}
                                onChange={(e) => setStatusFilter(e.target.value)}
                                className="bg-[#060B18] border border-slate-800 rounded-xl px-3 py-2 text-xs text-slate-300 focus:outline-none focus:border-[#00F2FE]"
                            >
                                <option value="all">All Statuses</option>
                                <option value="published">Published</option>
                                <option value="draft">Draft</option>
                                <option value="scheduled">Scheduled</option>
                            </select>

                            <button
                                type="submit"
                                className="btn-aqua px-4 py-2 rounded-xl text-xs font-bold shrink-0"
                            >
                                Filter
                            </button>

                            {(search || categoryFilter !== 'all' || statusFilter !== 'all') && (
                                <button
                                    type="button"
                                    onClick={handleResetFilters}
                                    className="p-2 rounded-xl bg-slate-800/60 hover:bg-slate-800 text-slate-400 hover:text-white text-xs font-semibold shrink-0 transition-colors"
                                    title="Clear filters"
                                >
                                    <X className="w-4 h-4" />
                                </button>
                            )}
                        </div>
                    </form>
                </div>

                <div className="glass-card rounded-2xl overflow-hidden border border-slate-800">

                    <table className="w-full text-left text-sm text-slate-300">
                        <thead className="bg-[#060B18] text-xs font-bold text-slate-400 uppercase border-b border-slate-800">
                            <tr>
                                <th className="px-6 py-4">Title</th>
                                <th className="px-6 py-4">Category</th>
                                <th className="px-6 py-4">Published Date</th>
                                <th className="px-6 py-4">Views</th>
                                <th className="px-6 py-4">Status</th>
                                <th className="px-6 py-4 text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-800/80">
                            {postsList.length === 0 ? (
                                <tr>
                                    <td colSpan={6} className="px-6 py-12 text-center text-slate-500">
                                        <div className="flex flex-col items-center gap-2">
                                            <p className="text-sm font-semibold text-slate-400">No blog articles published yet</p>
                                            <p className="text-xs text-slate-500">Click "Write New Article" above to draft and publish your first post.</p>
                                        </div>
                                    </td>
                                </tr>
                            ) : (
                                postsList.map((post: any) => (
                                    <tr key={post.id} className="hover:bg-[#060B18]/40 transition-colors">
                                        <td className="px-6 py-4 font-bold text-white max-w-xs truncate">{post.title}</td>
                                        <td className="px-6 py-4 text-xs text-slate-400">{post.category?.name || 'General'}</td>
                                        <td className="px-6 py-4 text-xs font-mono text-slate-400">{formatCustomDate(post.published_at)}</td>
                                        <td className="px-6 py-4 text-xs font-mono text-[#00F2FE]">{post.views || 0} views</td>
                                        <td className="px-6 py-4">
                                            <span className={`text-[10px] font-semibold px-2.5 py-0.5 rounded-full capitalize ${
                                                post.status === 'published' ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' : 'bg-slate-700 text-slate-300'
                                            }`}>
                                                {post.status}
                                            </span>
                                        </td>
                                        <td className="px-6 py-4 text-right">
                                            <div className="flex items-center justify-end gap-2">
                                                <a
                                                    href={`/blog/${post.slug}`}
                                                    target="_blank"
                                                    rel="noreferrer"
                                                    className="inline-flex items-center justify-center p-1.5 rounded-lg text-slate-400 hover:text-emerald-400 hover:bg-emerald-500/10 transition-colors"
                                                    title="View Live Article"
                                                >
                                                    <Eye className="w-4 h-4" />
                                                </a>
                                                <Link
                                                    href={`/admin/blog/${post.id}/edit`}
                                                    className="inline-flex items-center justify-center p-1.5 rounded-lg text-slate-400 hover:text-[#00F2FE] hover:bg-[#00F2FE]/10 transition-colors"
                                                    title="Edit Article"
                                                >
                                                    <SquarePen className="w-4 h-4" />
                                                </Link>
                                                <button
                                                    onClick={() => setDeleteId(post.id)}
                                                    className="inline-flex items-center justify-center p-1.5 rounded-lg text-rose-400 hover:text-rose-300 hover:bg-rose-500/10 transition-colors"
                                                    title="Delete Article"
                                                >
                                                    <Trash2 className="w-4 h-4" />
                                                </button>
                                            </div>
                                        </td>

                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>

                    {posts.links && (
                        <Pagination links={posts.links} from={posts.from} to={posts.to} total={posts.total} />
                    )}
                </div>
            </div>

            {/* AI Generator Modal */}
            {aiModalOpen && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm animate-fade-in">
                    <div className="bg-[#0B132B] border border-purple-500/30 rounded-3xl w-full max-w-xl p-6 sm:p-8 shadow-2xl shadow-purple-900/40 relative space-y-6">
                        <button
                            type="button"
                            onClick={() => !aiLoading && setAiModalOpen(false)}
                            className="absolute top-5 right-5 text-slate-400 hover:text-white p-1 rounded-lg hover:bg-slate-800"
                        >
                            <X className="w-5 h-5" />
                        </button>

                        <div className="flex items-center gap-3">
                            <div className="w-10 h-10 rounded-2xl bg-gradient-to-tr from-purple-600 to-indigo-600 flex items-center justify-center shadow-lg shadow-purple-600/30 text-yellow-300">
                                <Sparkles className="w-5 h-5" />
                            </div>
                            <div>
                                <h3 className="text-base font-bold text-white">Autonomous AI Blog Article Generator</h3>
                                <p className="text-xs text-slate-400">Generate a comprehensive, high-ranking technical post with code snippets and headings.</p>
                            </div>
                        </div>

                        <form onSubmit={handleAiGenerate} className="space-y-4">
                            <div>
                                <label className="text-xs font-bold text-slate-300 uppercase block mb-1">Article Topic / Keyword Prompt</label>
                                <input
                                    type="text"
                                    value={aiTopic}
                                    onChange={(e) => setAiTopic(e.target.value)}
                                    placeholder="e.g. Modern Event-Driven Architecture with Laravel 12 & Redis (or leave empty for AI auto-selection)..."
                                    className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-4 py-2.5 text-xs text-white focus:outline-none focus:border-purple-500"
                                />
                            </div>

                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                <div>
                                    <label className="text-xs font-bold text-slate-300 uppercase block mb-1">Target Category</label>
                                    <select
                                        value={aiCategory}
                                        onChange={(e) => setAiCategory(e.target.value)}
                                        className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-4 py-2.5 text-xs text-white focus:outline-none focus:border-purple-500"
                                    >
                                        <option value="all">Auto / All Categories</option>
                                        {categories.map((c: any) => (
                                            <option key={c.id} value={c.slug}>{c.name}</option>
                                        ))}
                                    </select>
                                </div>

                                <div>
                                    <label className="text-xs font-bold text-slate-300 uppercase block mb-1">Publication Status</label>
                                    <select
                                        value={aiStatus}
                                        onChange={(e) => setAiStatus(e.target.value)}
                                        className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-4 py-2.5 text-xs text-white focus:outline-none focus:border-purple-500"
                                    >
                                        <option value="published">Published — Live Immediately</option>
                                        <option value="draft">Draft — Save for Review</option>
                                    </select>
                                </div>
                            </div>

                            <div>
                                <label className="text-xs font-bold text-slate-300 uppercase block mb-1">OpenRouter AI Model</label>
                                <select
                                    value={aiModel}
                                    onChange={(e) => setAiModel(e.target.value)}
                                    className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-4 py-2.5 text-xs text-white focus:outline-none focus:border-purple-500"
                                >
                                    {modelsList.map((m: any) => (
                                        <option key={m.id} value={m.id}>{m.name}</option>
                                    ))}
                                </select>
                            </div>

                            {aiResult && (
                                <div className={`p-4 rounded-xl text-xs flex items-start gap-3 ${
                                    aiResult.success
                                        ? 'bg-emerald-500/10 border border-emerald-500/30 text-emerald-300'
                                        : 'bg-rose-500/10 border border-rose-500/30 text-rose-400'
                                }`}>
                                    {aiResult.success ? (
                                        <CheckCircle2 className="w-4 h-4 shrink-0 text-emerald-400 mt-0.5" />
                                    ) : (
                                        <AlertCircle className="w-4 h-4 shrink-0 text-rose-400 mt-0.5" />
                                    )}
                                    <div className="flex-1">
                                        <p className="font-semibold">{aiResult.message}</p>
                                        {aiResult.url && (
                                            <a
                                                href={aiResult.url}
                                                target="_blank"
                                                rel="noreferrer"
                                                className="text-[#00F2FE] font-bold hover:underline inline-flex items-center gap-1 mt-1"
                                            >
                                                View Live Post <ExternalLink className="w-3 h-3" />
                                            </a>
                                        )}
                                    </div>
                                </div>
                            )}

                            <div className="flex flex-col-reverse sm:flex-row items-center justify-end gap-3 pt-3 border-t border-slate-800/80">
                                <button
                                    type="button"
                                    disabled={aiLoading}
                                    onClick={() => setAiModalOpen(false)}
                                    className="w-full sm:w-auto px-5 py-2.5 rounded-xl text-xs font-semibold bg-slate-800 hover:bg-slate-700 text-slate-300 hover:text-white border border-slate-700/80 transition-all text-center"
                                >
                                    Cancel
                                </button>
                                <button
                                    type="submit"
                                    disabled={aiLoading}
                                    className="w-full sm:w-auto px-6 py-2.5 rounded-xl text-xs font-bold bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-500 hover:to-indigo-500 text-white shadow-lg shadow-purple-600/20 flex items-center justify-center gap-2 disabled:opacity-50"
                                >
                                    {aiLoading ? (
                                        <>
                                            <RefreshCw className="w-3.5 h-3.5 animate-spin" /> Authoring Post...
                                        </>
                                    ) : (
                                        <>
                                            <Sparkles className="w-3.5 h-3.5 text-yellow-300" /> Generate & Publish
                                        </>
                                    )}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}


            <ConfirmDeleteModal
                isOpen={deleteId !== null}
                title="Delete Blog Article?"
                message="Are you sure you want to delete this article? It will be removed permanently."
                onConfirm={handleDelete}
                onClose={() => setDeleteId(null)}
            />
        </AdminLayout>
    );
}

