'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 { api } from '@/lib/api';
import { useAuthStore } from '@/lib/auth-store';
import { useLanguage } from '@/lib/language-context';
import { CalendarDays, Eye, EyeOff, MessageSquareQuote, Trash2 } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useCallback, useEffect, useState } from 'react';
import ConfirmDialog from '@/components/common/ConfirmDialog';

interface TestimonialItem {
    _id: string;
    quote: string;
    authorName: string;
    role: string;
    approved: boolean;
    createdAt: string;
}

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

    const [items, setItems] = useState<TestimonialItem[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState('');
    const [selected, setSelected] = useState<TestimonialItem | null>(null);
    const [actionLoadingId, setActionLoadingId] = useState<string | null>(null);
    const [pendingDeleteItem, setPendingDeleteItem] = useState<TestimonialItem | null>(null);

    const fetchTestimonials = useCallback(async () => {
        if (!token) return;
        setLoading(true);
        setError('');
        const res = await api.content.getAdminTestimonials(token);
        if (res.success && Array.isArray(res.data)) {
            setItems(res.data as TestimonialItem[]);
        } else {
            setError(res.error || t('adminTestimonials.failedLoadTestimonials'));
        }
        setLoading(false);
    }, [token]);

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

    const toggleVisibility = async (item: TestimonialItem) => {
        if (!token) return;
        setActionLoadingId(item._id);
        const res = await api.content.setTestimonialVisibility(token, item._id, !item.approved);
        if (!res.success) {
            setError(res.error || t('adminTestimonials.failedUpdateVisibility'));
            setActionLoadingId(null);
            return;
        }
        setItems((prev) => prev.map((current) => (
            current._id === item._id ? { ...current, approved: !current.approved } : current
        )));
        setActionLoadingId(null);
    };

    const deleteItem = async (item: TestimonialItem) => {
        setPendingDeleteItem(item);
    };

    const confirmDeleteItem = async () => {
        if (!token || !pendingDeleteItem) return;
        setActionLoadingId(pendingDeleteItem._id);
        const res = await api.content.deleteTestimonial(token, pendingDeleteItem._id);
        if (!res.success) {
            setError(res.error || t('adminTestimonials.failedDeleteTestimonial'));
            setActionLoadingId(null);
            return;
        }
        setItems((prev) => prev.filter((current) => current._id !== pendingDeleteItem._id));
        setActionLoadingId(null);
        setPendingDeleteItem(null);
    };

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

    const visibleCount = items.filter((item) => item.approved).length;
    const hiddenCount = items.length - visibleCount;

    return (
        <div className="space-y-6">
            <div className="rounded-2xl border border-cyan-100 bg-linear-to-r from-cyan-50 via-white to-blue-50 p-6">
                <h1 className="text-3xl font-bold tracking-tight text-slate-900">{t('adminTestimonials.title')}</h1>
                <p className="mt-1 text-sm text-slate-600">{t('adminTestimonials.description')}</p>
                <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 font-semibold text-cyan-800">{t('adminTestimonials.totalLabel')} {items.length}</span>
                    <span className="rounded-full border border-green-200 bg-green-50 px-3 py-1 font-semibold text-green-700">{t('adminTestimonials.visibleLabel')} {visibleCount}</span>
                    <span className="rounded-full border border-amber-200 bg-amber-50 px-3 py-1 font-semibold text-amber-700">{t('adminTestimonials.hiddenLabel')} {hiddenCount}</span>
                </div>
            </div>

            <Card className="border-slate-200 shadow-sm">
                <CardHeader>
                    <CardTitle className="flex items-center gap-2 text-slate-900">
                        <MessageSquareQuote className="h-4 w-4 text-cyan-600" />
                        {t('adminTestimonials.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 && items.length === 0 ? <p className="text-sm text-muted-foreground">{t('adminTestimonials.noItemsFound')}</p> : null}

                    {items.map((item) => (
                        <div key={item._id} className="rounded-xl border border-slate-200 bg-white p-5">
                            <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(item.createdAt).toLocaleDateString()}
                                        </span>
                                        <span>{item.authorName} ({item.role})</span>
                                        {item.approved
                                            ? <span className="rounded-full bg-green-100 px-2 py-0.5 font-semibold text-green-700">{t('adminTestimonials.visibleBadge')}</span>
                                            : <span className="rounded-full bg-amber-100 px-2 py-0.5 font-semibold text-amber-700">{t('adminTestimonials.hiddenBadge')}</span>}
                                    </div>
                                    <p className="mt-3 text-sm leading-relaxed text-slate-700">&quot;{item.quote}&quot;</p>
                                </div>

                                <div className="flex shrink-0 items-center gap-2">
                                    <Button size="sm" variant="outline" onClick={() => setSelected(item)}>
                                        <Eye className="mr-1 h-4 w-4" />
                                        {t('common.view')}
                                    </Button>
                                    <Button
                                        size="sm"
                                        variant="outline"
                                        disabled={actionLoadingId === item._id}
                                        onClick={() => void toggleVisibility(item)}
                                    >
                                        {item.approved ? <EyeOff className="mr-1 h-4 w-4" /> : <Eye className="mr-1 h-4 w-4" />}
                                        {item.approved ? t('adminTestimonials.hide') : t('adminTestimonials.show')}
                                    </Button>
                                    <Button
                                        size="sm"
                                        variant="destructive"
                                        disabled={actionLoadingId === item._id}
                                        onClick={() => void deleteItem(item)}
                                    >
                                        <Trash2 className="mr-1 h-4 w-4" />
                                        {t('common.delete')}
                                    </Button>
                                </div>
                            </div>
                        </div>
                    ))}
                </CardContent>
            </Card>

            <Dialog open={!!selected} onOpenChange={(open) => !open && setSelected(null)}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>{t('adminTestimonials.dialogTitle')}</DialogTitle>
                    </DialogHeader>
                    <div className="space-y-3">
                        <p className="text-sm text-slate-500">
                            {selected?.authorName} ({selected?.role})
                        </p>
                        <div className="rounded-lg border border-slate-200 p-4 text-sm leading-relaxed text-slate-700 whitespace-pre-wrap">
                            {selected?.quote}
                        </div>
                    </div>
                </DialogContent>
            </Dialog>

            <ConfirmDialog
                open={!!pendingDeleteItem}
                onOpenChange={(open) => !open && setPendingDeleteItem(null)}
                title={`${t('adminTestimonials.deleteConfirmTitlePrefix')} ${pendingDeleteItem?.authorName || ''}?`}
                description={t('adminTestimonials.deleteConfirmDescription')}
                confirmLabel={t('common.delete')}
                cancelLabel={t('common.cancel')}
                loading={actionLoadingId === pendingDeleteItem?._id}
                onConfirm={confirmDeleteItem}
            />
        </div>
    );
}
