import { getServerSession } from "next-auth";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { redirect } from "next/navigation";
import { getAnnonceByIdInclude } from "@/lib/services/annonceService";
import { getUserById } from "@/lib/services/userService";
import Link from "next/link";
import ImageCarrousel from "@/lib/components/ImageCarrousel";
import AddQuestionButton from "@/lib/components/addQuestionButtonComponent";
import AnswerQuestionButton from "@/lib/components/answerQuestionButtonComponent";

export default async function AnnonceDetail({ params }: { params: { id: string } }) {
    const session = await getServerSession(authOptions);

    const annonce = await getAnnonceByIdInclude(Number(params.id));
    if (!annonce) return <div className="p-20 text-center">Annonce non trouvée.</div>;

    const agent = annonce.agent;
    const formattedPrice = new Intl.NumberFormat("fr-FR", {
        style: "currency",
        currency: "EUR",
        minimumFractionDigits: 0,
    }).format(annonce.price);
    const imageSrc = annonce.mainImg ? `data:image/jpeg;base64,${annonce.mainImg}` : "/default-image-annonce.jpg";

    let imagesSrc = [];

    if (annonce.gallery && annonce.gallery.length > 0) {
        const autresImagesSrc = annonce.gallery.map((img) => `data:image/jpeg;base64,${img.imageData}`);
        imagesSrc = [imageSrc, ...autresImagesSrc];
    } else {
        imagesSrc = [imageSrc];
    }

    return (
        <div className="min-h-screen bg-white">
            <div className="container mx-auto p-4 sm:p-6 lg:p-8">
                <header className="mb-4 py-4">
                    <Link
                        href="/"
                        className="mb-8 inline-flex items-center text-sm font-medium text-gray-500 hover:text-black">
                        &larr; Retour aux annonces
                    </Link>
                </header>

                <main className="grid grid-cols-1 lg:grid-cols-3 lg:gap-12">
                    {/* Colonne principale (Image et Description) */}
                    <div className="lg:col-span-2">
                        {/* Carrousel */}
                        <div className="mb-8">
                            <ImageCarrousel images={imagesSrc} titre={annonce.title} />
                        </div>

                        {/* Titre et Adresse */}
                        <div className="mb-6 border-b border-gray-200 pb-6">
                            <h1 className="text-4xl font-bold text-gray-900">{annonce.title}</h1>
                            <p className="text-md mt-2 text-gray-500">
                                {annonce.address}, {annonce.city}
                            </p>
                        </div>

                        {/* Description */}
                        <h2 className="mb-4 text-2xl font-semibold text-gray-800">Description</h2>
                        <p className="leading-relaxed text-gray-600">{annonce.description || "Aucune description."}</p>
                    </div>

                    {/* Prix et Agent */}
                    <aside className="mt-8 lg:mt-0">
                        <div className="sticky top-8 rounded-xl border border-gray-200 bg-white p-6 shadow-sm">
                            <p className="mb-6 text-3xl font-bold text-gray-900">{formattedPrice}</p>

                            <h3 className="border-t border-gray-200 pt-6 text-xl font-semibold text-gray-800">
                                Agent en charge
                            </h3>
                            {agent ? (
                                <div className="mt-4 space-y-3">
                                    <p className="text-gray-600">
                                        <span className="font-medium text-gray-900">Nom:</span> {agent.firstName}{" "}
                                        {agent.lastName}
                                    </p>
                                    <p className="text-gray-600">
                                        <span className="font-medium text-gray-900">Email:</span> {agent.email}
                                    </p>
                                    <button className="mt-4 w-full rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-black">
                                        Contacter l'agent
                                    </button>
                                </div>
                            ) : (
                                <p className="mt-4 text-gray-600">Information indisponible.</p>
                            )}
                        </div>
                    </aside>
                </main>
                <section className="mt-12 bg-gray-50">
                    <h2 className="mb-4 text-2xl font-semibold text-gray-800">FAQ</h2>

                    {annonce.questions && annonce.questions.length > 0 ? (
                        <div className="space-y-4">
                            {annonce.questions.map((q) => (
                                <div key={q.id} className="rounded-lg border border-gray-200 bg-white p-4 shadow-sm">
                                    <p className="font-medium text-gray-900">
                                        💬{" "}
                                        <span className="text-gray-800">{q.authorName ?? "Utilisateur anonyme"}</span> :
                                    </p>
                                    <p className="mt-1 text-gray-700">{q.content}</p>

                                    <div className="mt-2 border-t pt-2 text-gray-700">
                                        {q.answer ? (
                                            <>
                                                <p className="font-semibold">Réponse :</p>
                                                <p>{q.answer}</p>
                                                <p className="text-sm text-gray-500">
                                                    — {q.answerAuthorName ?? "Agent"} le{" "}
                                                    {q.answeredAt ? new Date(q.answeredAt).toLocaleDateString() : ""}
                                                </p>
                                            </>
                                        ) : (
                                            <>
                                                <p className="text-gray-500 italic">Pas encore de réponse.</p>
                                                {session &&
                                                    (session.user?.role === "ADMIN" ||
                                                        Number(session.user?.id) === annonce.agent.id) && (
                                                        <AnswerQuestionButton questionId={q.id} />
                                                    )}
                                            </>
                                        )}
                                    </div>
                                </div>
                            ))}
                        </div>
                    ) : (
                        <p className="text-gray-600">Aucune question posée pour le moment.</p>
                    )}

                    {session && <AddQuestionButton annonceId={annonce.id} />}
                </section>
            </div>
        </div>
    );
}
