import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft, ExternalLink, Pencil } from "lucide-react";
import { getProduct } from "@/lib/data";
import { getCurrentAssociate } from "@/lib/identity";
import { StatusBadge } from "@/components/StatusBadge";
import { StatusSelector } from "@/components/StatusSelector";
import { VoteButtons } from "@/components/VoteButtons";
import { CommentThread } from "@/components/CommentThread";
import { CommentForm } from "@/components/CommentForm";
import { Badge } from "@/components/ui/badge";
import { buttonVariants } from "@/components/ui/button";
import { formatPrice, formatRelativeTime } from "@/lib/utils";

export default async function ProductDetailPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const [product, associate] = await Promise.all([
    getProduct(id),
    getCurrentAssociate(),
  ]);
  if (!product) notFound();

  const myVote =
    product.votes.find((v) => v.associate === associate)?.value ?? null;
  const price = formatPrice(product.price, product.currency);

  return (
    <div className="mx-auto max-w-3xl px-4 py-6">
      <Link
        href="/"
        className="mb-4 inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
      >
        <ArrowLeft className="h-4 w-4" /> Retour à la liste
      </Link>

      <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
        <div className="aspect-square overflow-hidden rounded-xl bg-muted">
          {product.image_url ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img
              src={product.image_url}
              alt={product.title}
              className="h-full w-full object-cover"
            />
          ) : (
            <div className="flex h-full w-full items-center justify-center text-6xl">
              🛍️
            </div>
          )}
        </div>

        <div className="flex flex-col gap-3">
          <div className="flex items-start justify-between gap-2">
            <h1 className="text-xl font-semibold leading-snug">
              {product.title}
            </h1>
            <StatusBadge status={product.status} />
          </div>

          {price && <p className="text-lg font-semibold">{price}</p>}

          {product.tags.length > 0 && (
            <div className="flex flex-wrap gap-1">
              {product.tags.map((tag) => (
                <Badge key={tag} variant="secondary" className="font-normal">
                  {tag}
                </Badge>
              ))}
            </div>
          )}

          {product.description && (
            <p className="whitespace-pre-wrap text-sm text-muted-foreground">
              {product.description}
            </p>
          )}

          <div className="flex flex-wrap gap-2 text-sm">
            {product.source_url && (
              <a
                href={product.source_url}
                target="_blank"
                rel="noreferrer"
                className={buttonVariants({ variant: "outline", size: "sm" })}
              >
                <ExternalLink className="h-3.5 w-3.5" /> Voir la source
              </a>
            )}
            <Link
              href={`/products/${product.id}/edit`}
              className={buttonVariants({ variant: "outline", size: "sm" })}
            >
              <Pencil className="h-3.5 w-3.5" /> Modifier
            </Link>
          </div>

          <p className="text-xs text-muted-foreground">
            Ajouté par {product.created_by} ·{" "}
            {formatRelativeTime(product.created_at)}
            {product.status_updated_by && (
              <>
                {" "}
                · statut mis à jour par {product.status_updated_by}
              </>
            )}
          </p>

          <div className="mt-2 flex flex-col gap-2">
            <span className="text-sm font-medium">Statut</span>
            <StatusSelector productId={product.id} current={product.status} />
          </div>

          <div className="mt-2 flex flex-col gap-2">
            <span className="text-sm font-medium">Ton vote</span>
            <VoteButtons
              productId={product.id}
              upvotes={product.upvotes}
              downvotes={product.downvotes}
              myVote={myVote as 1 | -1 | null}
            />
          </div>
        </div>
      </div>

      <div className="mt-10 border-t pt-6">
        <h2 className="mb-4 text-sm font-medium">
          Discussion ({product.comments.length})
        </h2>
        <CommentThread comments={product.comments} />
        <div className="mt-4">
          <CommentForm productId={product.id} />
        </div>
      </div>
    </div>
  );
}
