import React, { useEffect, useRef, useState } from 'react';
import { useForm, Link } from '@inertiajs/react';
import { AdminLayout } from '../AdminLayout';
import { Save, ArrowLeft, Eye, CheckCircle2, AlertTriangle, Loader2, Sparkles, Plus, X } from 'lucide-react';
import { DarkCKEditor } from '@/components/DarkCKEditor';

interface BlogFormProps {
    post?: any;
    categories: any[];
    tags: any[];
}

export default function Form({ post, categories, tags }: BlogFormProps) {
    const { data, setData, post: sendPost, put, processing, errors } = useForm({
        title: post?.title || '',
        slug: post?.slug || '',
        category_id: post?.category_id || '',
        excerpt: post?.excerpt || '',
        content: post?.content || '',
        reading_time: post?.reading_time || 5,
        status: post?.status || 'published',
        featured: post?.featured || false,
        meta_title: post?.meta_title || '',
        meta_description: post?.meta_description || '',
    });

    const [contentMode, setContentMode] = useState<'editor' | 'preview'>('editor');
    const [aiFixLoading, setAiFixLoading] = useState(false);
    const [aiMessage, setAiMessage] = useState<{ type: 'success' | 'error' | 'info'; message: string } | null>(null);
    const [slugStatus, setSlugStatus] = useState<'idle' | 'checking' | 'available' | 'taken'>('idle');
    const [slugSuggestions, setSlugSuggestions] = useState<string[]>([]);
    const checkTimerRef = useRef<any>(null);

    const handleAiFixFormatting = async () => {
        if (!data.content || !data.content.trim()) {
            setAiMessage({ type: 'info', message: 'Please enter or paste some article content first to format.' });
            return;
        }

        setAiFixLoading(true);
        setAiMessage(null);

        try {
            const csrfToken = (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement)?.content;
            const res = await fetch('/admin/blog/ai-fix-formatting', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': csrfToken || '',
                },
                body: JSON.stringify({
                    content: data.content,
                    title: data.title,
                }),
            });

            const result = await res.json();
            if (result.success && result.formatted_content) {
                setData('content', result.formatted_content);
                setAiMessage({ type: 'success', message: result.message || 'Formatting perfected successfully by AI!' });
            } else {
                setAiMessage({ type: 'error', message: result.message || 'Could not format content. Deterministic formatter applied.' });
            }
        } catch (err: any) {
            console.error('Error fixing formatting with AI:', err);
            setAiMessage({ type: 'info', message: 'AI request timed out or network error. Instant formatter fallback applied.' });
        } finally {
            setAiFixLoading(false);
        }
    };




    // Auto-check slug availability on slug change with 300ms debounce
    useEffect(() => {
        if (!data.slug.trim()) {
            setSlugStatus('idle');
            setSlugSuggestions([]);
            return;
        }

        setSlugStatus('checking');
        if (checkTimerRef.current) {
            clearTimeout(checkTimerRef.current);
        }

        checkTimerRef.current = setTimeout(async () => {
            try {
                const res = await fetch('/admin/blog/check-slug', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'X-CSRF-TOKEN': (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement)?.content || '',
                    },
                    body: JSON.stringify({
                        slug: data.slug,
                        exclude_id: post?.id || null,
                    }),
                });
                const result = await res.json();
                if (result.available) {
                    setSlugStatus('available');
                    setSlugSuggestions([]);
                } else {
                    setSlugStatus('taken');
                    setSlugSuggestions(result.suggestions || []);
                }
            } catch (err) {
                setSlugStatus('idle');
            }
        }, 300);

        return () => {
            if (checkTimerRef.current) {
                clearTimeout(checkTimerRef.current);
            }
        };
    }, [data.slug]);

    const handleApplySuffix = (suffix: string) => {
        const cleanBase = data.slug.replace(/(-\d+|-\w+)?$/, '');
        const newSlug = `${data.slug.replace(/-+$/, '')}-${suffix}`;
        setData('slug', newSlug);
    };

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        if (post) {
            put(`/admin/blog/${post.id}`);
        } else {
            sendPost('/admin/blog');
        }
    };

    return (
        <AdminLayout title={post ? `Edit Article: ${post.title}` : 'Write New Article'}>
            <div className="w-full space-y-6">
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
                    <div>
                        <h2 className="text-xl font-bold text-white">{post ? 'Edit Article' : 'Write New Article'}</h2>
                        <p className="text-xs text-slate-400">Craft detailed technical articles and tutorials with formatted text, images, and code snippets.</p>
                    </div>
                    <Link
                        href="/admin/blog"
                        className="px-4 py-2 rounded-xl text-xs font-semibold bg-[#0B132B] border border-slate-800 text-slate-300 hover:text-white hover:border-[#00F2FE]/40 flex items-center gap-2 transition-all shrink-0 w-fit"
                    >
                        <ArrowLeft className="w-4 h-4" /> Back to Blog List
                    </Link>
                </div>

                {/* AI Formatting Message Alert */}
                {aiMessage && (
                    <div className={`p-4 rounded-2xl border text-sm flex items-center gap-3 animate-in fade-in ${
                        aiMessage.type === 'success'
                            ? 'bg-emerald-500/10 border-emerald-500/30 text-emerald-400'
                            : aiMessage.type === 'error'
                            ? 'bg-rose-500/10 border-rose-500/30 text-rose-400'
                            : 'bg-cyan-500/10 border-cyan-500/30 text-[#00F2FE]'
                    }`}>
                        {aiMessage.type === 'success' && <CheckCircle2 className="w-5 h-5 shrink-0" />}
                        {aiMessage.type === 'error' && <AlertTriangle className="w-5 h-5 shrink-0" />}
                        {aiMessage.type === 'info' && <Sparkles className="w-5 h-5 shrink-0" />}
                        <span className="font-medium leading-relaxed">{aiMessage.message}</span>
                        <button type="button" onClick={() => setAiMessage(null)} className="ml-auto text-slate-400 hover:text-white">
                            <X className="w-4 h-4" />
                        </button>
                    </div>
                )}

                <form onSubmit={handleSubmit} className="glass-card rounded-2xl p-6 sm:p-8 space-y-6">

                    <div>
                        <label className="text-xs font-bold text-slate-300 uppercase block mb-2">Article Title *</label>
                        <input
                            type="text"
                            value={data.title}
                            onChange={(e) => {
                                setData('title', e.target.value);
                                if (!post) {
                                    setData('slug', e.target.value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, ''));
                                }
                            }}
                            placeholder="e.g. Scaling Real-Time WebSocket Infrastructure with Laravel Reverb"
                            required
                            className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-[#00F2FE]"
                        />
                        {errors.title && <span className="text-xs text-rose-400 mt-1 block">{errors.title}</span>}
                    </div>

                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div>
                            <div className="flex items-center justify-between mb-2">
                                <label className="text-xs font-bold text-slate-300 uppercase">URL Slug *</label>
                                {slugStatus === 'checking' && (
                                    <span className="text-[11px] text-slate-400 flex items-center gap-1">
                                        <Loader2 className="w-3 h-3 animate-spin text-[#00F2FE]" /> Checking...
                                    </span>
                                )}
                                {slugStatus === 'available' && data.slug && (
                                    <span className="text-[11px] text-emerald-400 font-semibold flex items-center gap-1">
                                        <CheckCircle2 className="w-3.5 h-3.5" /> Available: /blog/{data.slug}
                                    </span>
                                )}
                                {slugStatus === 'taken' && (
                                    <span className="text-[11px] text-amber-400 font-bold flex items-center gap-1">
                                        <AlertTriangle className="w-3.5 h-3.5" /> Slug Already Taken
                                    </span>
                                )}
                            </div>

                            <input
                                type="text"
                                value={data.slug}
                                onChange={(e) => setData('slug', e.target.value.toLowerCase().replace(/[^a-z0-9-_]+/g, ''))}
                                required
                                className={`w-full bg-[#060B18] border rounded-xl px-4 py-2.5 text-sm font-mono focus:outline-none transition-all ${
                                    slugStatus === 'taken'
                                        ? 'border-amber-500/70 text-amber-300 focus:border-amber-400'
                                        : slugStatus === 'available'
                                        ? 'border-emerald-500/50 text-[#00F2FE] focus:border-[#00F2FE]'
                                        : 'border-slate-800 text-white focus:border-[#00F2FE]'
                                }`}
                            />

                            {/* One-Click Suggestions when Slug is Taken */}
                            {slugStatus === 'taken' && slugSuggestions.length > 0 && (
                                <div className="mt-2.5 p-3 rounded-xl bg-amber-500/10 border border-amber-500/25 space-y-1.5 animate-in fade-in">
                                    <p className="text-[11px] font-semibold text-amber-300">
                                        ⚠️ This slug is in use. Choose an available alternative in 1-click:
                                    </p>
                                    <div className="flex flex-wrap items-center gap-1.5">
                                        {slugSuggestions.map((sug) => (
                                            <button
                                                key={sug}
                                                type="button"
                                                onClick={() => setData('slug', sug)}
                                                className="px-2.5 py-1 rounded-lg text-xs font-mono font-bold bg-[#0B132B] hover:bg-[#00F2FE] hover:text-[#060B18] text-[#00F2FE] border border-cyan-500/40 transition-all flex items-center gap-1 shadow-sm"
                                            >
                                                <Plus className="w-3 h-3" /> {sug}
                                            </button>
                                        ))}
                                    </div>
                                </div>
                            )}

                            {/* Quick Suffix Modifiers */}
                            <div className="flex flex-wrap items-center gap-1 mt-2 text-[11px] text-slate-400">
                                <span className="text-[10px] text-slate-500 uppercase tracking-wider font-semibold">Quick Suffix:</span>
                                {['2', '3', '2026', 'guide', 'insights', 'overview'].map((suf) => (
                                    <button
                                        key={suf}
                                        type="button"
                                        onClick={() => handleApplySuffix(suf)}
                                        className="px-2 py-0.5 rounded-md bg-[#0B132B] hover:bg-[#1C2541] hover:text-cyan-300 text-slate-400 border border-slate-800 text-[10px] font-mono transition-all"
                                    >
                                        +{suf}
                                    </button>
                                ))}
                            </div>

                            {errors.slug && <span className="text-xs text-rose-400 mt-1 block">{errors.slug}</span>}
                        </div>

                        <div>
                            <label className="text-xs font-bold text-slate-300 uppercase block mb-2">Category</label>
                            <select
                                value={data.category_id}
                                onChange={(e) => setData('category_id', e.target.value)}
                                className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-[#00F2FE]"
                            >
                                <option value="">Select Category</option>
                                {categories.map((c) => (
                                    <option key={c.id} value={c.id}>{c.name}</option>
                                ))}
                            </select>
                        </div>
                    </div>


                    <div>
                        <label className="text-xs font-bold text-slate-300 uppercase block mb-2">Article Excerpt</label>
                        <textarea
                            rows={2}
                            value={data.excerpt}
                            onChange={(e) => setData('excerpt', e.target.value)}
                            placeholder="Short 2-sentence summary displayed in blog index cards..."
                            className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-[#00F2FE]"
                        />
                    </div>

                    {/* Rich Formatted Content Editor with Live Preview & AI Formatter */}
                    <div>
                        <div className="flex flex-wrap items-center justify-between gap-2 mb-2">
                            <label className="text-xs font-bold text-slate-300 uppercase">Article Content *</label>

                            <div className="flex items-center gap-2">
                                {/* AI Formatting Fix Button */}
                                <button
                                    type="button"
                                    onClick={handleAiFixFormatting}
                                    disabled={aiFixLoading || !data.content?.trim()}
                                    className="inline-flex items-center gap-1.5 px-3 py-1 rounded-xl text-xs font-bold bg-gradient-to-r from-[#00F2FE]/15 to-[#4FACFE]/15 hover:from-[#00F2FE]/25 hover:to-[#4FACFE]/25 text-[#00F2FE] border border-[#00F2FE]/40 transition-all shadow-sm disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer"
                                    title="AI will analyze, repair unparsed markdown asterisks, clean HTML entities in code blocks, and fix table/list formatting"
                                >
                                    {aiFixLoading ? (
                                        <>
                                            <Loader2 className="w-3.5 h-3.5 animate-spin text-[#00F2FE]" />
                                            <span>AI Fixing Formatting...</span>
                                        </>
                                    ) : (
                                        <>
                                            <Sparkles className="w-3.5 h-3.5 text-[#00F2FE]" />
                                            <span>AI Fix & Beautify Formatting</span>
                                        </>
                                    )}
                                </button>

                                {/* Editor / Preview Switch */}
                                <div className="flex items-center bg-[#060B18] border border-slate-800 rounded-xl p-0.5 text-xs">
                                    <button
                                        type="button"
                                        onClick={() => setContentMode('editor')}
                                        className={`px-3 py-1 rounded-lg font-semibold transition-all ${
                                            contentMode === 'editor'
                                                ? 'bg-[#00F2FE]/15 text-[#00F2FE] border border-[#00F2FE]/30 shadow-sm'
                                                : 'text-slate-400 hover:text-white'
                                        }`}
                                    >
                                        Editor
                                    </button>
                                    <button
                                        type="button"
                                        onClick={() => setContentMode('preview')}
                                        className={`px-3 py-1 rounded-lg font-semibold flex items-center gap-1 transition-all ${
                                            contentMode === 'preview'
                                                ? 'bg-[#00F2FE]/15 text-[#00F2FE] border border-[#00F2FE]/30 shadow-sm'
                                                : 'text-slate-400 hover:text-white'
                                        }`}
                                    >
                                        <Eye className="w-3 h-3" /> Live Preview
                                    </button>
                                </div>
                            </div>
                        </div>

                        {contentMode === 'editor' ? (

                            <DarkCKEditor
                                value={data.content}
                                onChange={(val) => setData('content', val)}
                                placeholder="Write formatted article body with headings, code blocks, bullet points, and quotes..."
                            />
                        ) : (
                            <div className="p-6 rounded-2xl bg-[#060B18] border border-slate-800 min-h-[350px]">
                                <div className="text-[10px] text-slate-500 font-mono uppercase mb-4 pb-2 border-b border-slate-800 flex items-center justify-between">
                                    <span>Public Rendering Preview</span>
                                    <span className="text-[#00F2FE]">.article-prose active</span>
                                </div>
                                <div
                                    className="article-prose text-sm text-slate-300 leading-relaxed"
                                    dangerouslySetInnerHTML={{ __html: data.content || '<p class="text-slate-500 italic">No content written yet...</p>' }}
                                />
                            </div>
                        )}
                        {errors.content && <span className="text-xs text-rose-400 mt-1 block">{errors.content}</span>}
                    </div>


                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 pt-2 border-t border-slate-800">
                        <div>
                            <label className="text-xs font-bold text-slate-300 uppercase block mb-2">Estimated Reading Time (min)</label>
                            <input
                                type="number"
                                value={data.reading_time}
                                onChange={(e) => setData('reading_time', parseInt(e.target.value) || 5)}
                                className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-[#00F2FE]"
                            />
                        </div>

                        <div>
                            <label className="text-xs font-bold text-slate-300 uppercase block mb-2">Publication Status</label>
                            <select
                                value={data.status}
                                onChange={(e) => setData('status', e.target.value)}
                                className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-[#00F2FE]"
                            >
                                <option value="published">Published — Live on site</option>
                                <option value="draft">Draft — Hidden</option>
                            </select>
                        </div>
                    </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-2">SEO Meta Title</label>
                            <input
                                type="text"
                                value={data.meta_title}
                                onChange={(e) => setData('meta_title', e.target.value)}
                                placeholder="Article Title | Tech in Soul"
                                className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-[#00F2FE]"
                            />
                        </div>

                        <div>
                            <label className="text-xs font-bold text-slate-300 uppercase block mb-2">SEO Meta Description</label>
                            <input
                                type="text"
                                value={data.meta_description}
                                onChange={(e) => setData('meta_description', e.target.value)}
                                placeholder="150-160 characters summary for Google search..."
                                className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-[#00F2FE]"
                            />
                        </div>
                    </div>

                    <div className="flex flex-col-reverse sm:flex-row items-center justify-between gap-3 pt-4 border-t border-slate-800">
                        <Link
                            href="/admin/blog"
                            className="w-full sm:w-auto px-5 py-2.5 rounded-xl text-xs font-semibold bg-slate-800/80 hover:bg-slate-700 text-slate-300 hover:text-white border border-slate-700/80 text-center transition-all"
                        >
                            Cancel
                        </Link>
                        <button
                            type="submit"
                            disabled={processing}
                            className="btn-aqua w-full sm:w-auto px-6 py-2.5 rounded-xl font-bold text-xs flex items-center justify-center gap-2 disabled:opacity-50"
                        >
                            <Save className="w-4 h-4" /> {post ? 'Update Article' : 'Publish Article'}
                        </button>
                    </div>
                </form>
            </div>
        </AdminLayout>
    );
}



