'use client';

import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { api } from '@/lib/api';
import { useAuthStore } from '@/lib/auth-store';
import { useLanguage } from '@/lib/language-context';
import { Mail, MessageSquareText, Star } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useCallback, useEffect, useState } from 'react';

interface FeedbackItem {
    _id: string;
    name: string;
    email: string;
    subject: string;
    rating: number;
    message: string;
    createdAt: string;
}

export default function AdminSupportFeedbackPage() {
    const { token, user } = useAuthStore();
    const { t } = useLanguage();
    const router = useRouter();
    const [items, setItems] = useState<FeedbackItem[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState('');

    const fetchFeedback = useCallback(async () => {
        if (!token) return;
        setLoading(true);
        const res = await api.content.getAdminSupportFeedback(token);
        if (res.success && Array.isArray(res.data)) {
            setItems(res.data as FeedbackItem[]);
        } else {
            setError(res.error || t('adminSupportFeedback.failedLoadFeedback'));
        }
        setLoading(false);
    }, [token]);

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

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

    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('adminSupportFeedback.title')}</h1>
                <p className="mt-1 text-sm text-slate-600">{t('adminSupportFeedback.description')}</p>
            </div>

            <Card className="border-slate-200 shadow-sm">
                <CardHeader>
                    <CardTitle className="flex items-center gap-2 text-slate-900">
                        <MessageSquareText className="h-4 w-4 text-cyan-600" />
                        {t('adminSupportFeedback.messagesTitle')}
                    </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                    {error ? <p className="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('adminSupportFeedback.noFeedbackFound')}</p> : null}

                    {items.map((item) => (
                        <div key={item._id} className="rounded-xl border border-slate-200 p-4">
                            <div className="flex flex-wrap items-center gap-3 text-xs text-slate-500">
                                <span className="font-semibold text-slate-700">{item.name}</span>
                                <span className="inline-flex items-center gap-1">
                                    <Mail className="h-3.5 w-3.5" />
                                    {item.email}
                                </span>
                                <span>{new Date(item.createdAt).toLocaleString()}</span>
                            </div>
                            <p className="mt-2 text-sm font-semibold text-slate-800">{item.subject}</p>
                            <div className="mt-1 flex gap-1 text-yellow-500">
                                {Array.from({ length: item.rating }).map((_, idx) => (
                                    <Star key={idx} className="h-4 w-4 fill-yellow-400 text-yellow-400" />
                                ))}
                            </div>
                            <p className="mt-2 text-sm leading-relaxed text-slate-700 whitespace-pre-wrap">{item.message}</p>
                        </div>
                    ))}
                </CardContent>
            </Card>
        </div>
    );
}
