'use client';

import { Button } from '@/components/ui/button';
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 { useRouter } from 'next/navigation';
import { useCallback, useEffect, useState } from 'react';

interface Testimonial {
    _id: string;
    quote: string;
    rating: number;
    authorName: string;
    role: string;
    createdAt: string;
}

export default function TestimonialsPage() {
    const { token, user } = useAuthStore();
    const { t } = useLanguage();
    const router = useRouter();
    const [quote, setQuote] = useState('');
    const [rating, setRating] = useState<number>(5);
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState('');
    const [items, setItems] = useState<Testimonial[]>([]);

    const fetchMine = useCallback(async () => {
        if (!token) return;
        const res = await api.content.getMyTestimonials(token);
        if (res.success && Array.isArray(res.data)) {
            setItems(res.data as Testimonial[]);
        }
    }, [token]);

    useEffect(() => {
        const role = user?.userType;
        if (!user || (role !== 'doctor' && role !== 'dentist')) {
            router.replace('/dashboard');
            return;
        }
        const timer = window.setTimeout(() => {
            void fetchMine();
        }, 0);
        return () => window.clearTimeout(timer);
    }, [user, router, fetchMine]);

    const handleSubmit = async (e: React.SyntheticEvent<HTMLFormElement>) => {
        e.preventDefault();
        if (!token) return;
        setSaving(true);
        setError('');
        const res = await api.content.createTestimonial(token, { quote, rating });
        if (!res.success) {
            setError(res.error || t('testimonials.failedToSubmit'));
            setSaving(false);
            return;
        }
        setQuote('');
        setRating(5);
        await fetchMine();
        setSaving(false);
    };

    const role = user?.userType;
    if (!user || (role !== 'doctor' && role !== 'dentist')) return null;

    return (
        <div className="space-y-6">
            <h1 className="text-3xl font-bold">{t('testimonials.title')}</h1>

            <Card>
                <CardHeader>
                    <CardTitle>{t('testimonials.shareTitle')}</CardTitle>
                </CardHeader>
                <CardContent>
                    <form onSubmit={handleSubmit} className="space-y-3">
                        <div className="space-y-1">
                            <label htmlFor="rating" className="text-sm font-medium">{t('testimonials.ratingLabel')}</label>
                            <select
                                id="rating"
                                value={rating}
                                onChange={(e) => setRating(parseInt(e.target.value, 10))}
                                className="h-10 w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm"
                            >
                                <option value={5}>{t('testimonials.rating5')}</option>
                                <option value={4}>{t('testimonials.rating4')}</option>
                                <option value={3}>{t('testimonials.rating3')}</option>
                                <option value={2}>{t('testimonials.rating2')}</option>
                                <option value={1}>{t('testimonials.rating1')}</option>
                            </select>
                        </div>
                        <textarea
                            value={quote}
                            onChange={(e) => setQuote(e.target.value)}
                            required
                            minLength={10}
                            placeholder={t('testimonials.writePlaceholder')}
                            className="w-full min-h-32 rounded-md border border-input bg-transparent px-3 py-2 text-sm"
                        />
                        {error && <p className="text-sm text-red-600">{error}</p>}
                        <Button type="submit" disabled={saving}>
                            {saving ? t('testimonials.submitting') : t('testimonials.submit')}
                        </Button>
                    </form>
                </CardContent>
            </Card>

            <Card>
                <CardHeader>
                    <CardTitle>{t('testimonials.yourTestimonials')}</CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                    {items.length === 0 ? <p className="text-sm text-muted-foreground">{t('testimonials.noTestimonialsYet')}</p> : null}
                    {items.map((item) => (
                        <div key={item._id} className="rounded-lg border p-4">
                            <div className="mb-2 flex gap-1 text-yellow-500">
                                {Array.from({ length: item.rating || 5 }).map((_, idx) => (
                                    <span key={idx}>★</span>
                                ))}
                            </div>
                            <p className="text-sm leading-relaxed">&quot;{item.quote}&quot;</p>
                            <p className="text-xs text-muted-foreground mt-2">
                                {new Date(item.createdAt).toLocaleDateString()}
                            </p>
                        </div>
                    ))}
                </CardContent>
            </Card>
        </div>
    );
}
