'use client';

import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { api } from '@/lib/api';
import { useAuthStore } from '@/lib/auth-store';
import { useLanguage } from '@/lib/language-context';
import { sanitizeBlogHtml } from '@/lib/sanitize-blog-html';
import { BookOpenText, CalendarDays, Eye, EyeOff, PenSquare, Sparkles, Trash2 } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useCallback, useEffect, useRef, useState } from 'react';
import ConfirmDialog from '@/components/common/ConfirmDialog';
import PaginationControls from '@/components/common/PaginationControls';

interface BlogPost {
    _id: string;
    title: string;
    excerpt: string;
    content: string;
    authorName: string;
    published: boolean;
    createdAt: string;
}

export default function AdminBlogPage() {
    const { token, user } = useAuthStore();
    const { t } = useLanguage();
    const router = useRouter();

    const [posts, setPosts] = useState<BlogPost[]>([]);
    const [loading, setLoading] = useState(true);
    const [actionLoadingId, setActionLoadingId] = useState<string | null>(null);
    const [error, setError] = useState('');
    const [selectedPost, setSelectedPost] = useState<BlogPost | null>(null);
    const [pendingDeletePost, setPendingDeletePost] = useState<BlogPost | null>(null);
    const [createLoading, setCreateLoading] = useState(false);
    const [editingPost, setEditingPost] = useState<BlogPost | null>(null);
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(6);
    const formCardRef = useRef<HTMLDivElement | null>(null);
    const titleInputRef = useRef<HTMLInputElement | null>(null);
    const [form, setForm] = useState({
        title: '',
        excerpt: '',
        content: '',
    });

    const hasBlobMediaUrl = (html: string): boolean => {
        return /<(img|iframe)\b[^>]*\bsrc\s*=\s*["']\s*blob:/i.test(html);
    };

    const fetchBlogs = useCallback(async () => {
        if (!token) return;
        setLoading(true);
        setError('');
        const res = await api.content.getAdminBlogs(token);
        if (res.success && Array.isArray(res.data)) {
            setPosts(res.data as BlogPost[]);
            setCurrentPage(1);
        } else {
            setError(res.error || t('adminBlog.failedLoadBlogs'));
        }
        setLoading(false);
    }, [token]);

    useEffect(() => {
        if (!user || user.userType !== 'admin') {
            router.replace('/dashboard');
            return;
        }
        const timer = window.setTimeout(() => {
            void fetchBlogs();
        }, 0);
        return () => window.clearTimeout(timer);
    }, [user, router, fetchBlogs]);

    const toggleVisibility = async (post: BlogPost) => {
        if (!token) return;
        setActionLoadingId(post._id);
        const res = await api.content.setBlogVisibility(token, post._id, !post.published);
        if (!res.success) {
            setError(res.error || t('adminBlog.failedUpdateVisibility'));
            setActionLoadingId(null);
            return;
        }
        setPosts((prev) => prev.map((item) => (
            item._id === post._id ? { ...item, published: !item.published } : item
        )));
        setActionLoadingId(null);
    };

    const deletePost = async (post: BlogPost) => {
        setPendingDeletePost(post);
    };

    const confirmDeletePost = async () => {
        if (!token || !pendingDeletePost) return;
        setActionLoadingId(pendingDeletePost._id);
        const res = await api.content.deleteBlog(token, pendingDeletePost._id);
        if (!res.success) {
            setError(res.error || t('adminBlog.failedDeleteBlog'));
            setActionLoadingId(null);
            return;
        }
        setPosts((prev) => prev.filter((item) => item._id !== pendingDeletePost._id));
        setCurrentPage((prev) => {
            const nextTotal = posts.length - 1;
            const nextTotalPages = Math.max(1, Math.ceil(nextTotal / pageSize));
            return Math.min(prev, nextTotalPages);
        });
        setActionLoadingId(null);
        setPendingDeletePost(null);
    };

    const upsertPost = async (e: React.SyntheticEvent<HTMLFormElement>) => {
        e.preventDefault();
        if (!token) return;
        if (hasBlobMediaUrl(form.content)) {
            setError(t('adminBlog.blobUrlNotSupported'));
            return;
        }
        setCreateLoading(true);
        setError('');
        const res = editingPost
            ? await api.content.updateBlog(token, editingPost._id, {
                title: form.title,
                excerpt: form.excerpt,
                content: form.content,
            })
            : await api.content.createBlog(token, {
                title: form.title,
                excerpt: form.excerpt,
                content: form.content,
                published: true,
            });
        if (!res.success) {
            setError(res.error || (editingPost ? t('adminBlog.failedUpdateBlog') : t('adminBlog.failedCreateBlog')));
            setCreateLoading(false);
            return;
        }
        setForm({ title: '', excerpt: '', content: '' });
        setEditingPost(null);
        await fetchBlogs();
        setCreateLoading(false);
    };

    if (!user || user.userType !== 'admin') return null;

    const visibleCount = posts.filter((p) => p.published).length;
    const hiddenCount = posts.length - visibleCount;
    const totalPages = Math.max(1, Math.ceil(posts.length / pageSize));
    const paginatedPosts = posts.slice((currentPage - 1) * pageSize, currentPage * pageSize);

    return (
        <div className="space-y-8">
            <div className="rounded-2xl border border-cyan-100 bg-linear-to-r from-cyan-50 via-white to-blue-50 p-6 shadow-sm">
                <div className="flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
                    <div>
                        <h1 className="text-3xl font-bold tracking-tight text-slate-900">{t('adminBlog.title')}</h1>
                        <p className="mt-1 text-sm text-slate-600">
                            {t('adminBlog.description')}
                        </p>
                    </div>
                    <div className="rounded-xl border border-cyan-200 bg-white px-4 py-2 text-right">
                        <p className="text-xs text-slate-500">{t('adminBlog.publishedNow')}</p>
                        <p className="text-2xl font-bold text-cyan-700">{visibleCount}</p>
                    </div>
                </div>
                <div className="mt-4 flex flex-wrap gap-3 text-xs">
                    <span className="rounded-full border border-cyan-200 bg-white px-3 py-1 text-cyan-800 font-semibold">
                        {t('adminBlog.totalLabel')} {posts.length}
                    </span>
                    <span className="rounded-full border border-green-200 bg-green-50 px-3 py-1 text-green-700 font-semibold">
                        {t('adminBlog.visibleLabel')} {visibleCount}
                    </span>
                    <span className="rounded-full border border-amber-200 bg-amber-50 px-3 py-1 text-amber-700 font-semibold">
                        {t('adminBlog.hiddenLabel')} {hiddenCount}
                    </span>
                </div>
            </div>

            <div className="grid grid-cols-1 gap-6 xl:grid-cols-[1.1fr_0.9fr]">
                <Card className="border-cyan-100 shadow-sm">
                    <div ref={formCardRef} />
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                            <PenSquare className="h-4 w-4 text-cyan-600" />
                            {editingPost ? `${t('common.edit')} Post` : t('adminBlog.createPost')}
                        </CardTitle>
                    </CardHeader>
                    <CardContent>
                        <form onSubmit={upsertPost} className="space-y-4">
                            <div className="space-y-2">
                                <Label htmlFor="blog-title">{t('adminBlog.titleLabel')}</Label>
                                <Input
                                    id="blog-title"
                                    ref={titleInputRef}
                                    value={form.title}
                                    onChange={(e) => setForm((prev) => ({ ...prev, title: e.target.value }))}
                                    placeholder={t('adminBlog.titlePlaceholder')}
                                    required
                                />
                            </div>
                            <div className="space-y-2">
                                <div className="flex items-center justify-between">
                                    <Label htmlFor="blog-excerpt">{t('adminBlog.excerptLabel')}</Label>
                                    <span className="text-xs text-slate-500">{form.excerpt.length}/180</span>
                                </div>
                                <Input
                                    id="blog-excerpt"
                                    value={form.excerpt}
                                    onChange={(e) => setForm((prev) => ({ ...prev, excerpt: e.target.value.slice(0, 180) }))}
                                    placeholder={t('adminBlog.excerptPlaceholder')}
                                    required
                                />
                            </div>
                            <div className="space-y-2">
                                <div className="flex items-center justify-between">
                                    <Label htmlFor="blog-content">{t('adminBlog.contentLabel')}</Label>
                                    <span className="text-xs text-slate-500">{form.content.length} {t('adminBlog.characters')}</span>
                                </div>
                                <textarea
                                    id="blog-content"
                                    value={form.content}
                                    onChange={(e) => setForm((prev) => ({ ...prev, content: e.target.value }))}
                                    required
                                    className="min-h-44 w-full rounded-md border border-input bg-white px-3 py-2 text-sm leading-relaxed shadow-xs focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-cyan-500"
                                />
                            </div>
                            <div className="flex justify-end gap-2">
                                <Button
                                    type="button"
                                    variant="outline"
                                    onClick={() => {
                                        setForm({ title: '', excerpt: '', content: '' });
                                        setEditingPost(null);
                                    }}
                                    disabled={createLoading}
                                >
                                    {editingPost ? t('common.cancel') : t('adminBlog.clear')}
                                </Button>
                                <Button type="submit" disabled={createLoading} className="bg-cyan-600 hover:bg-cyan-500">
                                    {createLoading ? t('common.saving') : (editingPost ? t('common.save') : t('adminBlog.publish'))}
                                </Button>
                            </div>
                        </form>
                    </CardContent>
                </Card>

                <Card className="border-slate-200 shadow-sm">
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                            <Sparkles className="h-4 w-4 text-amber-500" />
                            {t('adminBlog.quickPreview')}
                        </CardTitle>
                    </CardHeader>
                    <CardContent>
                        <div className="rounded-xl border border-slate-200 bg-white p-4">
                            <p className="text-xs text-slate-500">{new Date().toLocaleDateString()}</p>
                            <p className="mt-2 text-lg font-semibold text-slate-900">
                                {form.title || t('adminBlog.previewTitlePlaceholder')}
                            </p>
                            <p className="mt-2 text-sm text-slate-600">
                                {form.excerpt || t('adminBlog.previewExcerptPlaceholder')}
                            </p>
                            <p className="mt-4 border-t border-slate-100 pt-3 text-xs text-slate-500">
                                {t('adminBlog.by')} {user.firstName} {user.lastName}
                            </p>
                        </div>
                        <p className="mt-3 text-xs text-slate-500">
                            {t('adminBlog.tip')}
                        </p>
                    </CardContent>
                </Card>
            </div>

            <Card className="border-slate-200 shadow-sm">
                <CardHeader>
                    <CardTitle className="flex items-center gap-2 text-slate-900">
                        <BookOpenText className="h-4 w-4 text-cyan-600" />
                        {t('adminBlog.postsTitle')}
                    </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                    {error ? (
                        <p className="rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">{error}</p>
                    ) : null}
                    {loading ? <p className="text-sm text-muted-foreground">{t('common.loading')}</p> : null}
                    {!loading && posts.length === 0 ? <p className="text-sm text-muted-foreground">{t('adminBlog.noPostsFound')}</p> : null}
                    {!loading && posts.length > 0 ? (
                        <PaginationControls
                            currentPage={currentPage}
                            totalPages={totalPages}
                            onPageChange={setCurrentPage}
                            alignment="right"
                            showSummary={false}
                            showPageSize={false}
                            className="border-0 px-0 py-0"
                            labels={{
                                showing: t('common.showing'),
                                to: t('common.to'),
                                of: t('common.of'),
                                perPage: t('common.perPage'),
                                previous: t('common.previous'),
                                next: t('common.next'),
                            }}
                        />
                    ) : null}

                    {paginatedPosts.map((post) => (
                        <div key={post._id} className="rounded-xl border border-slate-200 bg-white p-5 transition-colors hover:border-cyan-300">
                            <div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
                                <div className="min-w-0">
                                    <div className="flex flex-wrap items-center gap-2 text-xs text-slate-500">
                                        <span className="inline-flex items-center gap-1 rounded-full bg-cyan-100 px-2 py-0.5 text-cyan-700">
                                            <CalendarDays className="h-3 w-3" />
                                            {new Date(post.createdAt).toLocaleDateString()}
                                        </span>
                                        <span>{t('adminBlog.by')} {post.authorName}</span>
                                        {post.published ? (
                                            <span className="rounded-full bg-green-100 px-2 py-0.5 text-green-700 font-semibold">{t('adminBlog.visibleBadge')}</span>
                                        ) : (
                                            <span className="rounded-full bg-amber-100 px-2 py-0.5 text-amber-700 font-semibold">{t('adminBlog.hiddenBadge')}</span>
                                        )}
                                    </div>
                                    <p className="mt-3 text-lg font-semibold text-slate-900">{post.title}</p>
                                    <p className="mt-1 text-sm text-slate-600">{post.excerpt}</p>
                                </div>

                                <div className="flex w-full flex-wrap items-center gap-2 md:w-auto md:flex-nowrap">
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        onClick={() => setSelectedPost(post)}
                                        className="flex-1 sm:flex-none"
                                    >
                                        <Eye className="mr-1 h-4 w-4" />
                                        {t('common.view')}
                                    </Button>
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        onClick={() => {
                                            setEditingPost(post);
                                            setForm({
                                                title: post.title,
                                                excerpt: post.excerpt,
                                                content: post.content,
                                            });
                                            formCardRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
                                            setTimeout(() => {
                                                titleInputRef.current?.focus();
                                            }, 150);
                                        }}
                                        className="flex-1 sm:flex-none"
                                    >
                                        <PenSquare className="mr-1 h-4 w-4" />
                                        {t('common.edit')}
                                    </Button>
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        disabled={actionLoadingId === post._id}
                                        onClick={() => void toggleVisibility(post)}
                                        className="flex-1 sm:flex-none"
                                    >
                                        {post.published ? <EyeOff className="mr-1 h-4 w-4" /> : <Eye className="mr-1 h-4 w-4" />}
                                        {post.published ? t('adminBlog.hide') : t('adminBlog.show')}
                                    </Button>
                                    <Button
                                        variant="destructive"
                                        size="sm"
                                        disabled={actionLoadingId === post._id}
                                        onClick={() => void deletePost(post)}
                                        className="flex-1 sm:flex-none"
                                    >
                                        <Trash2 className="mr-1 h-4 w-4" />
                                        {t('common.delete')}
                                    </Button>
                                </div>
                            </div>
                        </div>
                    ))}

                    <PaginationControls
                        currentPage={currentPage}
                        totalPages={totalPages}
                        onPageChange={setCurrentPage}
                        pageSize={pageSize}
                        pageSizeOptions={[6, 10, 20]}
                        onPageSizeChange={(size) => {
                            setPageSize(size);
                            setCurrentPage(1);
                        }}
                        showingFrom={(currentPage - 1) * pageSize + 1}
                        showingTo={Math.min(currentPage * pageSize, posts.length)}
                        totalItems={posts.length}
                        labels={{
                            showing: t('common.showing'),
                            to: t('common.to'),
                            of: t('common.of'),
                            perPage: t('common.perPage'),
                            previous: t('common.previous'),
                            next: t('common.next'),
                        }}
                    />
                </CardContent>
            </Card>

            <Dialog open={!!selectedPost} onOpenChange={(open) => !open && setSelectedPost(null)}>
                <DialogContent className="max-h-[85vh] overflow-auto">
                    <DialogHeader>
                        <DialogTitle>{selectedPost?.title}</DialogTitle>
                    </DialogHeader>
                    <div className="space-y-3">
                        <p className="text-sm text-slate-500">
                            {t('adminBlog.by')} {selectedPost?.authorName} {t('adminBlog.on')} {selectedPost ? new Date(selectedPost.createdAt).toLocaleDateString() : ''}
                        </p>
                        <p className="text-sm font-medium text-slate-700">{selectedPost?.excerpt}</p>
                        <div
                            className="rounded-lg border border-slate-200 p-4 text-sm leading-relaxed text-slate-700 space-y-3 [&_img]:max-w-full [&_img]:h-auto [&_iframe]:w-full [&_iframe]:aspect-video [&_iframe]:max-w-full [&_a]:text-cyan-700 [&_a]:underline"
                            dangerouslySetInnerHTML={{ __html: sanitizeBlogHtml(selectedPost?.content || '') }}
                        />
                    </div>
                </DialogContent>
            </Dialog>

            <ConfirmDialog
                open={!!pendingDeletePost}
                onOpenChange={(open) => !open && setPendingDeletePost(null)}
                title={`${t('adminBlog.deleteConfirmTitlePrefix')} "${pendingDeletePost?.title || ''}"?`}
                description={t('adminBlog.deleteConfirmDescription')}
                confirmLabel={t('common.delete')}
                cancelLabel={t('common.cancel')}
                loading={actionLoadingId === pendingDeletePost?._id}
                onConfirm={confirmDeletePost}
            />
        </div>
    );
}
